Groovy web console

subscribe to the feed Subscribe
to this
site

Tailorsoft Test

Published 1 month ago by Farid Rico with tags v1
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.json.JsonSlurper

import java.text.DecimalFormat

class App {

    static void main(String[] args) {
        try {
            def response = mapResponse(getData())

            printHeader()
            printInfo(response)
        } catch (Exception e) {
            println(e.getMessage())
        }
    }

    static void printHeader() {
        // Print the table header
        println "+--------------+---------+------------+";
        println "| Product      |  Orders |      Total |";
        println "+--------------+---------+------------+";
    }

    static void printInfo(Response response) {

        for(Product product in response.products) {

            def order = response?.orders?.find {
                it.items?.find {
                    it.productId == product.id
                }
            }

            def item = order?.items?.find {
                it.productId == product.id
            }

            if(order != null && item != null) {

                def decimalFormat = new DecimalFormat("#.##");
                def total = Double.parseDouble(product.price) * item.quantity
                
                println("| ${product.name} | ${order.id} | ${decimalFormat.format(total)} |")
            }
        }
        print("+--------------+---------+------------+")
    }

    static Response mapResponse(InputStream inputStream) {
        def jsonSlurper = new JsonSlurper();
        def mapResponse = jsonSlurper.parse(inputStream);

        return new Response(products: (List<Product>) mapResponse['products'],
                orders: (List<Order>) mapResponse['orders'])
    }

    static InputStream getData() throws RuntimeException {
        def urlJson = new URL("https://www.tailorsoft.co/sample.json")
        HttpURLConnection httpURLConnection = (HttpURLConnection) urlJson.openConnection()
        httpURLConnection.addRequestProperty("Accept", "application/json")

        httpURLConnection.with {
            doOutput = true
            requestMethod = 'GET'
        }

        def status = httpURLConnection.responseCode;

        if(status != 200) {
            throw new RuntimeException("An error occurred status: ${status}")
        }

        return httpURLConnection.inputStream;
    }
}

class Response {
    private List<Product> products;
    private List<Order> orders;

    List<Product> getProducts() {
        return products;
    }

    List<Order> getOrders() {
        return orders;
    }
}

class Product {
    private String id;
    private String name;
    private String price;

    String getId() {
        return id;
    }

    String getName() {
        return name;
    }

    String getPrice() {
        return price;
    }
}

class Order {
    private String id;
    private List<Item> items;

    String getId() {
        return id;
    }

    List<Item> getItems() {
        return items;
    }

    static class Item {
        private String productId;
        private Integer quantity;

        String getProductId() {
            return productId;
        }

        Integer getQuantity() {
            return quantity;
        }
    }
}