Question

Java Concurrency! You have been given a simple API to buy and print postage. Write a...

Java Concurrency!

You have been given a simple API to buy and print postage. Write a program that submits each incoming order to the API and then prints the shipping label.

Unfortunately each call to the shipping label API is SLOW… To compensate for this, use concurrency so that your program can be making several calls to the API at one time.

We also need to keep track of our expenses, so make sure to calculate how much money is being spent on shipping.

Starter Code:

1) ShippingService.java

https://drive.google.com/open?id=1SknHyOgUL5gH07hHJQQ_MZjsbTdSCDCe

2) ShippingLabel.java

https://drive.google.com/open?id=1aeUvOarp_7wc5jCU6vDATejZeZsJPXLX

Details:

The attached code simulates an API that generates shipping labels. Include it with your code.

1) Create an "Order" class to represent an incoming order with the following fields

a. Customer Name

b. Customer Address

c. Pounds of Chocolate

2) Create a list to hold incoming orders and populate it with at least 6 orders

3) Create an ExecutorService instance to manage threads

4) Write a Runnable class to process each order by calling the API to generate a shipping label

a) "Print" each label by printing it to the console

   i. Although ShippingLabel does have a toString() method, it is not very readable. Print the shipping label in a more user-friendly way.

   ii. Watch out for concurrency problems!

b) Keep track of the total cost of all shipments

   i. There are many ways to do this - use any mechanism you like, but make sure that you account for any possible race conditions

5) Cleanly shutdown the ExecutorService

6) Print the total cost after all orders have been filled

0 0
Add a comment Improve this question Transcribed image text
Answer #1

`Hey,

Note: Brother in case of any queries, just comment in box I would be very happy to assist all your queries

import java.util.Objects;
import java.util.Random;
import java.util.UUID;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class PrintOrders implements Runnable {
private final Queue<Orders> orders;

public PrintOrders(Queue<Orders> list){
this.orders = list;
}

@Override
public void run(){

double sum = 0;
int num = 1;
ShippingLabel sticker;
ShippingService service = new ShippingService();


while(orders.size() > 0){

Orders ship = orders.poll();
sticker = service.getShippingLabel(ship.getName(), ship.getAddress(), ship.getPounds());


System.out.printf("Order Number: %s\n"
+ "Recipient Name: %s\n"
+ "Tracking Number: %s\n"
+ "Destination: %s\n"
+ "Weight in Pounds: %s\n"
+ "Cost in Cents: %s\n\n", num, sticker.getRecipientName(), sticker.getTrackingNumber(),
sticker.getDestinationAddress(), sticker.getWeightInPounds(), sticker.getCostInCents());

sum += sticker.getCostInCents();
num++;
}

System.out.print("Total cost: " + String.format("%.2f", sum));
System.out.println();

}
}
class Orders {
private String name;
private String address;
private double pounds;

public Orders(String name, String address, double pounds){

this.name = name;
this.address = address;
this.pounds = pounds;

}


public String getName() {return name;}

public void setName(String name) {

this.name = name;

}

public String getAddress() {return address;}

public void setAddress(String address) {

this.address = address;

}

public double getPounds() {return pounds;}

public void setPounds(double pounds) {

this.pounds = pounds;

}

}
class ShippingLabel {

private String trackingNumber;
private String recipientName;
private String destinationAddress;
private double weightInPounds;
private int costInCents;

public ShippingLabel() {

}

public ShippingLabel(String trackingNumber, String recipientName, String destinationAddress, double weightInPounds, int costInCents) {
this.trackingNumber = trackingNumber;
this.recipientName = recipientName;
this.destinationAddress = destinationAddress;
this.weightInPounds = weightInPounds;
this.costInCents = costInCents;
}

public String getTrackingNumber() {
return trackingNumber;
}

public void setTrackingNumber(String trackingNumber) {
// this.trackingNumber = trackingNumber;
}

public String getRecipientName() {
return recipientName;
}

public void setRecipientName(String recipientName) {
this.recipientName = recipientName;
}

public String getDestinationAddress() {
return destinationAddress;
}

public void setDestinationAddress(String destinationAddress) {
this.destinationAddress = destinationAddress;
}

public double getWeightInPounds() {
return weightInPounds;
}

public void setWeightInPounds(double weightInPounds) {
this.weightInPounds = weightInPounds;
}

public int getCostInCents() {
return costInCents;
}

public void setCostInCents(int costInCents) {
this.costInCents = costInCents;
}

@Override
public String toString() {
return "ShippingLabel{" + "trackingNumber=" + trackingNumber + ", recipientName=" + recipientName + ", destinationAddress=" + destinationAddress + ", weightInPounds=" + weightInPounds + ", costInCents=" + costInCents + '}';
}

@Override
public int hashCode() {
int hash = 3;
hash = 97 * hash + Objects.hashCode(this.trackingNumber);
hash = 97 * hash + Objects.hashCode(this.recipientName);
hash = 97 * hash + Objects.hashCode(this.destinationAddress);
hash = 97 * hash + (int) (Double.doubleToLongBits(this.weightInPounds) ^ (Double.doubleToLongBits(this.weightInPounds) >>> 32));
hash = 97 * hash + this.costInCents;
return hash;
}

@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final ShippingLabel other = (ShippingLabel) obj;
if (Double.doubleToLongBits(this.weightInPounds) != Double.doubleToLongBits(other.weightInPounds)) {
return false;
}
if (this.costInCents != other.costInCents) {
return false;
}
if (!Objects.equals(this.trackingNumber, other.trackingNumber)) {
return false;
}
if (!Objects.equals(this.recipientName, other.recipientName)) {
return false;
}
if (!Objects.equals(this.destinationAddress, other.destinationAddress)) {
return false;
}
return true;
}

}

class ShippingService {

private final Random random = new Random();

private static final int BASE_COST_IN_CENTS = 950;
private static final int COST_PER_POUND_IN_CENTS = 75;

private static final int MIN_TIME_TO_SLEEP = 3;
private static final int MAX_TIME_TO_SLEEP = 5;

// Purchase a shipping label

public ShippingLabel getShippingLabel(String recipientName, String destinationAddress, double weightInPounds) {

Integer millis = random.ints(1, MIN_TIME_TO_SLEEP, MAX_TIME_TO_SLEEP).map(seconds -> seconds * 1_000).findFirst().getAsInt();
try {
Thread.sleep(millis);
} catch (InterruptedException ex) {
ex.printStackTrace();
}

String confirmationNumber = UUID.randomUUID().toString().replace("-", "");
int shippingCost = (int) (BASE_COST_IN_CENTS + COST_PER_POUND_IN_CENTS * weightInPounds);
return new ShippingLabel(confirmationNumber, recipientName, destinationAddress, weightInPounds, shippingCost);

}

}
public class Driver {

public static void main(String[] args) {

Queue<Orders> orders = new LinkedList<>();

orders.add(new Orders("John Lnnon", "453 Lower St", 55.23));
orders.add(new Orders("Bob Marley", "634 Manshion St", 32));
orders.add(new Orders("Taylor Swift", "904 Greenpark St", 57.5));
orders.add(new Orders("Bob Dylan", "375 Stock Exchange St", 12));
orders.add(new Orders("Chris Harris", "123 Downtown St", 44));
orders.add(new Orders("Steve Wah", "555 Central Avenue St", 83));

System.out.println("Shipment Orders\n");

ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(new PrintOrders(orders));

executorService.shutdown();


}

}

Kindly revert for any queries

Thanks.

Add a comment
Know the answer?
Add Answer to:
Java Concurrency! You have been given a simple API to buy and print postage. Write a...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • What if you had to write a program that would keep track of a list of...

    What if you had to write a program that would keep track of a list of rectangles? This might be for a house painter to use in calculating square footage of walls that need paint, or for an advertising agency to keep track of the space available on billboards. The first step would be to define a class where one object represents one rectangle's length and width. Once we have class Rectangle, then we can make as many objects of...

  • program Java oop The project description As a programmer; you have been asked to write a...

    program Java oop The project description As a programmer; you have been asked to write a program for a Hospital with the following The Hospital has several employees and each one of them has an ID, name, address, mobile number, email and salary. . The employees are divided into Administration staff: who have in addition to the previous information their position. Nurse: who have their rank and specialty stored in addition to the previous o o Doctor: who have the...

  • Write a simple Java program with the following naming structure: Open Eclipse Create a workspace called...

    Write a simple Java program with the following naming structure: Open Eclipse Create a workspace called hw1 Create a project called hw1 (make sure you select the “Use project folder as root for sources and class files”) Create a class called Hw1 in the hw1 package (make sure you check the box that auto creates the main method). Add a comment to the main that includes your name Write code that demonstrates the use of each of the following basic...

  • .Need code for my java class !! Write a simple java program that uses loops. You...

    .Need code for my java class !! Write a simple java program that uses loops. You may use ‘WHILE’ or ‘FOR’ or ‘DO-WHILE’ – you decide. The program should use a loop to compute the semester average for up to 5 students. In the loop the user will ask for a student name and their 3 test scores and add them up and divide the total by 3 giving the semester average. You will print out the student name and...

  • Description: You have been asked to help the College of IST Running Club by designing a...

    Description: You have been asked to help the College of IST Running Club by designing a program to help them keep track of runners in the club, the races that will occur, and each runner's performance in each race! Requirements: Please use Java to implement the program Your program must: Store information about each Runner. Store information about each Race. Store information about the performance of each runner in each race that they compete in. Note that each race may...

  • This should be in Java Create a simple hash table You should use an array for...

    This should be in Java Create a simple hash table You should use an array for the hash table, start with a size of 5 and when you get to 80% capacity double the size of your array each time. You should create a class to hold the data, which will be a key, value pair You should use an integer for you key, and a String for your value. For this lab assignment, we will keep it simple Use...

  • Write the following program in Java using Eclipse. A cash register is used in retail stores...

    Write the following program in Java using Eclipse. A cash register is used in retail stores to help clerks enter a number of items and calculate their subtotal and total. It usually prints a receipt with all the items in some format. Design a Receipt class and Item class. In general, one receipt can contain multiple items. Here is what you should have in the Receipt class: numberOfItems: this variable will keep track of the number of items added to...

  • If your program does not compile, you will not receive any points! You will write a program to keep up with a Jewelry...

    If your program does not compile, you will not receive any points! You will write a program to keep up with a Jewelry store and some of the Inventory (rings/necklaces/earrings) purchased there (The Jewelry store can be real or not) using Object-Oriented Programming (OOP). The important aspect of object-oriented programming is modular development and testing of reusable software modules. You love selling rings, necklaces, and earrings as well as programming and have decided to open a Jewelry store. To save...

  • Project: Using Java API Classes Page 3 of 5 SpaceTicket.java Requirements: The purpose of this program is accept coded...

    Project: Using Java API Classes Page 3 of 5 SpaceTicket.java Requirements: The purpose of this program is accept coded space ticket information as input that includes the ticket price, category, time, date, and seat, followed by the description of the travel. Note that the eight digits for price have an implied decimal point. The program should then print the ticket information including the actual cost, which is the price with discount applied as appropriate: 25% for a student ticket (s),...

  • Assignment 1. You are to write a simple program using Netbeans Java IDE  that consists of two...

    Assignment 1. You are to write a simple program using Netbeans Java IDE  that consists of two classes. The program will allow the user to place an order for a Tesla Model X car. 2. Present the user with a menu selection for each option on the site. We will use JOptionPane to generate different options for the user. See the examples posted for how to use JOPtionPane. 3. Each menu will have multiple items each item will be in the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT