Groovy web console

subscribe to the feed Subscribe
to this
site

Groovy Test

Published 4 weeks ago by Frayba OTalora with tags Groovy
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.json.JsonSlurper

static getProducts (products) {
    def map = [:]
     products?.each {
        map.put(it.id, [name: it.name, orderAmount: 0, price: new BigDecimal(it.price), total: 0.0])
    }
    
    map
}

static getItems (items, map) {
    items?.each {
        it.each {
            map[it.productId].total += (map[it.productId].price * it.quantity)
            map[it.productId].orderAmount += 1
        }
    }
}



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

def map = [:]
def response = new JsonSlurper().parseText(url_Json.text)

    map = getProducts(response?.products)
    
    getItems (response?.orders?.items, map)


    if (map) {
        // Print the table header
        println "+--------------+---------+------------+";
        println "| Product      |  Orders |      Total |";
        println "+--------------+---------+------------+";
        map.each { key, val ->
            println val.name.padRight(15, ' ') + "|" + val.orderAmount.toString().padLeft(5, ' ') + "\t |" + val.total.toString().padLeft(11, ' ')
        }
    } else {
        println "Not information to display"
    }
}
catch (Exception e) {
    println("Something went wrong: ${e}")
}