Groovy web console

subscribe to the feed Subscribe
to this
site

TailorSoft

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

@ToString
class Product {
    String id
    String name
    Double price
}

def getHttpResponse(url) {
    def getConnection = url.openConnection()
    getConnection.requestMethod = 'GET'

    try {
        if (getConnection.responseCode != 200) {
            throw new Exception("An Error has occurred invoking the service: ${url.toString()} -> ${getConnection.responseCode}")
        } else {
            def jsonString = getConnection.getInputStream().getText()
            return (new JsonSlurper()).parseText(jsonString)
        }
    } catch (UnknownHostException e) {
        println("An Unexpected error occurred invoking the service: ${url.toString()}")
        e.printStackTrace()
        System.exit(0)
    } catch (Exception e) {
        println(e.getMessage())
        e.printStackTrace()
        System.exit(0)
    }
}

def url_Json = new URL("https://www.tailorsoft.co/sample.json")
def responseMap = getHttpResponse(url_Json)
Map <String, Product> products = responseMap.products
        .collectEntries {[(it.id) : new Product(id: it.id, name: it.name, price: it.price as Double)]}
def orders = responseMap.orders
        .collect {order -> order.items}
        .flatten()
        .groupBy {it.productId}


// Print the table header
def border = "+${("-" * 30)}+${("-" * 10)}+${("-" * 10)}+"

println border
println "|${ sprintf("%-30s","Product") }|${ sprintf("%-10s","Orders") }|${ sprintf("%-10s","Total") }|"
println border
orders.each {key, value ->
    def product = products[key]
    def total = sprintf("\$ %.2f", value.sum{ it.quantity } * product.price)
    println "|${ sprintf("%-30s", product.name) }|${ sprintf("%10s", value.size()) }|${ sprintf("%10s", total) }|"
    println border
}