Groovy web console

subscribe to the feed Subscribe
to this
site

ChristianGarciaTest

Published 4 weeks ago by Christian Garcia
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.json.JsonSlurper
import java.util.stream.*

def url_Json = new URL("https://www.tailorsoft.co/sample.json")
URLConnection connection = url_Json.openConnection();
InputStream inputStream = connection.getInputStream();
def response = new groovy.json.JsonSlurper().parseText(inputStream.text);

println "+--------------+---------+------------+";
println "| Product      |  Orders |    Total   |";

for(product in response.products){


   numberOrders=getCountOrders(response.orders,product)
   totalOrders= geTotalOrders(response.orders,product)
   println "  "+ product.name+ calculateSpaces(product.name,17)+numberOrders+ calculateSpaces(numberOrders+"",10)+totalOrders
}

println "+--------------+---------+------------+";

int getCountOrders(orders,product){

   int cont=0

   for(order in orders){
      for(item in order.items){
         if(item.productId==product.id){
            cont ++;
         }
      }
   }


   return cont
}

String geTotalOrders(orders,product){

   double total=0

   for(order in orders){
      for(item in order.items){
         if(item.productId==product.id){
            total =total+ ( Double.parseDouble(product.price)* item.quantity);
         }
      }
   }

   return String.format( "%.2f",total)
}

String calculateSpaces(productName,contador){
   def spaces=""
   for (int i =productName.length();i<=contador;i++){
      spaces=spaces+" "
   }
   return spaces
}