Groovy web console

subscribe to the feed Subscribe
to this
site

Script Test

Published 3 weeks ago by Alexis Y with tags test script
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.json.JsonSlurper 

static void main(String[] args) {
try {
  
    def url_json = new URL("https://www.tailorsoft.co/sample.json")
    def data = new JsonSlurper().parseText(url_json.text)
    def products= data.products
    def orders= data.orders
    
    def productsList = new ProductList() 
    for(product in products){
        productsList.addProduct(new ProductRecord(product))
          for(order in orders){ 
                for(item in order.items ){
                    productsList.update(item.productId, item.quantity)
                }
            }
    }
    productsList.printTable()    
    } catch (Exception e)
    {
        println(e.getMessage())
    }
}

class ProductList{    
def list = []
 
def addProduct(recorder){
    list.add(recorder)
}     
 
def update(id, quantity){
    for(recorder in list){
        if(recorder.product.id == id )
           recorder.actQuantity(quantity)
    }
}     
 
def printTable(){
    println "+--------------+---------+------------+";
    println "| Product      |  Orders |      Total |";
    println "+--------------+---------+------------+";
    for(recorder in list){
         recorder.printTable()
    }
    println "+--------------+---------+------------+";

    }
}   

class ProductRecord{    
    def product    
    def quantity
 
    ProductRecord(product){        
        quantity = 0        
        this.product = product
    }     
 
    void actQuantity(quantity){        
        this.quantity += quantity    
    }     
 
    float calculateSpent (){
        quantity * Float.valueOf(product.price)
    }
 
    void printTable(){
        println product.name + "            " +quantity +"        " + calculateSpent();
    }
}