Groovy web console

subscribe to the feed Subscribe
to this
site

Test

Published 3 weeks ago by ChristianRojas
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.json.JsonSlurper
import groovy.*

def url_Json = new URL("https://www.tailorsoft.co/sample.json")


def json_info = new JsonSlurper().parseText(response(url_Json));
def products= json_info.products;
def orders= json_info.orders;
println "+--------------+---------+------------+";
println "| Product      |  Orders |      Total |";
println "+--------------+---------+------------+";
productList(products,orders);
println "+--------------+---------+------------+";


def response(url_Json){
HttpURLConnection connection = (HttpURLConnection) url_Json.openConnection();        
connection.addRequestProperty("Accept", "application/json")          
connection.with {            
    doOutput = true            
    requestMethod = 'GET'            
    return content.text          
    }
}

def productList(products,orders){
    def myList= products.collect { 
        ele -> println "| "+ele.name + (ele.name.length()>10?" ":"       ")+ ordersQuantity(orders,ele.id) ;
    }
}

def ordersQuantity(orders,product){
 def quantity=0;
 def total=0;
 def myList= orders.collect { 
        ele -> 
            ele.items.collect{item->
                if(item.productId==product){
                   quantity+=item.quantity;
                    total++;
                } 
            }
        }
  return "|   "+total+"     |\t "+quantity+"    |";
}