CS636 Practice Final Exam Solution

Open books, handouts, solutions, etc.

Show all work on these pages, using backs of pages if needed.  Points are marked in parentheses.  Total points = 150.

1.      (15) Important Examples

a.       In the Download application of Chapter 7, available in project ch07downloadS, there are these notable components:

A servlet, DownloadServlet.java     M  V  C

File-accessing code, UserIO.java    M  V  C

Various JSP files                    M V  C

This is an MVC application, although not as layered as our main projects. Classify these parts of the application by circling/underlining M for model, V for view and C for controller.

 

b.      In the Cart application of Chapter 7, available in project ch07cart, allowed a user to manipulate the contents of a shopping cart, adding, removing, and updating its items on various requests.  Through what mechanism provided by tomcat (and other application servers) is an app allowed to keep around an object in memory through the various requests by one user. Specifically:

Mechanism name: sessions or session management

Brief description of how it works, and what software in involved:

Tomcat sends a cookie to the browser with an session id, and the browser sends the cookie back with each request to the same website, allowing tomcat to figure out which old session the new request belongs to.

           

2.       (15) Concurrency Suppose a MVC web application (pizza3 or music3) running in tomcat has 6 user sessions active, and of these, 3 (with all different users) are doing concurrent requests, and of these, 2 are doing concurrent transactions at this moment.

a. How many JDBC Connections are active and communicating with the database? 2

b.      What object manages these connections as a group for the app, optimizing short-term use of JDBC connections? Specifically:

Class name of object: DataSource    
What code creates this object: Spring support code (DataSource is a Spring bean here)

c.       How many Session objects are in tomcat’s memory? 6

d.      Is there any worry that the two requests with concurrent transactions for different users of pizza3 will be sharing a PizzaOrder object in memory? Explain.

n   No such worry, because PizzaOrder objects are always created anew for each request, either in the DAO based on database data, or in the service layer when a new order is being created. These objects are never held in fields in the service or DAO layers by the stateless requirement, and are never allowed to go to the presentation layer (instead, PizzaOrderData objects are sent to presentation, but even they are not held long-term). Thus they are private to the request, i.e., to the thread for the request.

 

3. (30) Application Design and Layers. Currently the products in the music project are unchanging. Suppose you have been asked to add an admin capability tochange the price of any specific product. This change will make Products mutable, but don’t worry here about those mutable objects being in the presentation layer.

a.     a. Explain why

public void changePrice(Product updatedProduct) throws ServiceException

 is not a good choice for a new service layer method. Hint: what code would provide the“updatedProduct” object?

Answer: since the "updatedProduct" object is being sent down from the caller to the method, i.e. from the presentation layer to the service layer, it must mean that the update to the Product object happened in the presentation layer, but we do not allow domain objects to be changed in presentation: that's the job of the service layer.

b.      b. Show a good choice for the changePrice service method signature.            

vo         public void changePrice(long productId, BigDecimal newPrice) throws ServiceException

               or use productCode instead of productId here. (Or even use two values, oldPrice and newPrice, if you want the update to fail if the old price is not as expected.) T

o

c.       c. Describe any changes needed to the DAO API for your design, or explain why none are needed.

     For music1 or music3, we would need an update DAO method, for ex., public void updateProduct(Product p) throws SQLException

    (If we were using JPA, it would track such a change and do it at commit time without needing such a DAO method)

d.       d. Describe any changes needed to the database schema for your design

 None.

e.       e. In your design, is there a new transaction?  If so, what does it do?

 Yes, any DB access needs a transaction. It would run inside the service method and do the update of the product's row in table product.

 

(30) 4. The Database Model and SQL.

Suppose we want to enhance the music project to allow users to submit votes (or “likes”) for songs, i.e., tracks.  A user vote is submitted by a certain registered user for a certain track. A user can’t undo their vote once made, and each user can only vote at most once for each track, that is, additional votes for the same track and user will be just ignored. We also want to record the time the vote was submitted (the one that counted, not a discarded duplicate votes). Note the core schema at the end of the exam.

a.       Give the create table statement for your new vote table, complete with foreign key constraints.

This is very much like a download in terms of relationships, so we  copy and modify that create table;

CREATE TABLE votes (
    vote_id INT NOT NULL,
    user_id INT NOT NULL,
    vote_date TIMESTAMP NOT NULL,
    track_id INT NOT NULL,
    UNIQUE(track_id, email_address),  -- to enforce only one vote per user, track combo
    PRIMARY KEY (vote_id),
    FOREIGN KEY (user_id) REFERENCES site_user (user_id),
    FOREIGN KEY (track_id) REFERENCES track (track_id)
);

 

b.      Show the new Vote domain class, with references to related domain objects corresponding to any foreign keys you specified above. As usual, you can put “// getters and setters…”

public class Vote {
private long id;
private Date voteTime;
private User user;
private Track track;

// getters and setters

c.       Write SQL to find the number of votes each CD has received, that is, summed over all their tracks.  List CD's product code and number of votes.

   select p.product_code, count(*) from votes v, tracks t, products p
       where v.track_id = t.track_id and t.product_id = p.product_id
       group by p.product_code

 

d.      Write SQL to find users (by their email addresses) who have voted for a track but never downloaded that track.

select u.email_address from votes v, site_user u
where v.user_id = u.user_id and v.track_id not in
    (select d.track_id from downloads d where d.user_id = v.user_id)
 

(30)  5.Consider the application scenario from the practice midterm. Suppose you are automating operations for a store selling PCs.   All PCs of a certain model number are equivalent as far as buyers are concerned, but the store wants to sell them in FIFO (first-in, first-out) order so that no box gets too worn-looking.  Each PC has a model number (int), serial number (10-char string), vendor id (int), and delivery date (int day number, when the PC arrived at the store.)  At sale-time, the salesperson will enter a model number and get back the serial number of the system to sell (in case of ties for oldest, any one of the oldest.)

  1. Write a business layer (service) API that allows entry of new PCs by inventory clerks and another call to retrieval of the next one to sell by salespeople.  Don’t forget the exceptions.

   public void addPC(String modelNo, String serialNo, int vendor, int deliveryDay)
                          throws ServiceException;

   public String getPcToSell(String modelNo) throws ServiceException;

   b.  You are asked to write a web app for the salesperson to use. It has a form page with a form with method=”POST” action=”lookupPC.html” and an input text field with name “model” for the model number. It also has a result page found_pc.jsp, also in the top-level directory. Following our Spring Boot webapp design, we would write a InventoryController that handles the form submission (and other actions). Assume all the infrastructure code is there: SBApplication,  CommandRun, etc. Write a controller method, with appropriate annotation, to handle the URL from the form submission, calling your API and forwarding to the result page. Don’t worry about errors here. Assume your InventoryController class has a field inventoryService with annotation @Autowired to your service object, i.e., the singleton object created for the API you wrote for part a.


@RequestMapping("lookupPC.html")    

public String submit(Model model, @RequestParam(value = "model") String modelNo)
                  throws ServletException {

  String result = inventoryService.getPcToSell(modelNo);  // should be in try-catch, but ignoring errors

  Model.setAttribute("serialNo", result);

 
return “found_pc”;

}

or, more classically, provide a request parameter and work with the request directly:

@RequestMapping("lookupPC.html")    

public String submit(HttpServletRequest request)
                  throws ServletException {
  String modelNo = request.getParameter(“model”);

  String result = inventoryService.getPcToSell(modelNo);  // should be in try-catch, but ignoring errors
  request.setAttribute(“serialNo”, result);  // request var
       
  return “found_pc”; 
}

  1. Write found_pc.jsp, using data you attached to the request object in DispatcherServlet.
found_pc.jsp:

<html>
<body>
      Serial number to use is ${serialNo}
</body>
</html>