Groovy web console

subscribe to the feed Subscribe
to this
site

Groovy Test

Published 1 month ago by Carlos Alfredo Guerrero
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
package com.tailorsoft.test
import groovy.json.JsonSlurper

def callGet(String url) {
	new groovy.json.JsonSlurper().parseText(url.toURL().getText())
}

def getRows(sample) {
	
	def rows = [:];
	
	sample.products.each { product ->
  rows[product.id] = product;
  rows[product.id].orders = 0;
  rows[product.id].total =0;
	}

	sample.orders.each { order ->    
  order.items.each {item ->   
   def product = rows[item.productId];
   product.orders += 1;
   product.total += Float.parseFloat(product.price);
  }
  
	}

	return rows;
}

def printRows(rows) {

	rows.each{row ->
  print String.format("|%-14s|", row.value.name);
  print String.format("%9d|", row.value.orders);
  println String.format("%12f|", (float)row.value.total);
	}
	
}	

def printTable(sample, rows) {
	// Print the table header
	println "+--------------+---------+------------+";
	println "| Product      |  Orders |      Total |";
	println "+--------------+---------+------------+";
	
	printRows(rows);
	
	println "+--------------+---------+------------+";
}

def sample =  callGet("https://www.tailorsoft.co/sample.json");
def rows = getRows(sample);
printTable(sample, rows);