University of Portsmouth

School of Computing Postgraduate Programme

Lecturer:

Jim Briggs / Mark Baker

Unit Code:

WEB2P

Unit Title:

Web Programming 2

Date of Test:

Semester 2 2004-2005 MAIN

Time of Test:

--

Duration of Test:

2 hours

Requirements:

None

Office Code

 

Student Groups

 

 

Rubric:

Number of Questions

Answer 4 out of 8 questions (25 marks per question). Use separate answer books for each section. There is no need to answer a minimum number of questions in each section.

 

Mode and Restrictions

CLOSED book - no books or notes to be allowed

 

Pass mark as a percentage

40%

 

Weighting as percentage of Unit

60%

Tags such as [JSB1] signify the answers (appended as Word comments). In Word, Tools|Options|Print|Comments switches these on/off.

Section A

1.      This question is about Apache Struts.

a)      What general facilities does Struts provide for managing the detection and reporting of errors to the user? [8 marks[JSB1] ]

b)      A Struts action in a banking application must detect that an account number specified by the user represents an account that both exists and is owned by that user before allowing any operations on it. Sketch the code for the part of the action's execute method indicated below, showing how you would verify access and report any error to the user. [17 marks[JSB2] ]

package com.supabank;

 

import javax.servlet.http.*;

import org.apache.struts.action.*;

 

public class AccountUpdateAction extends Action {

    //Useful declarations which in a real application would be elsewhere

    class User {…}

    class Account {…}

    class Money {…

    class AccountForm extends ActionForm {…}

    class NoSuchAccount extends Exception {}

   

    Account findAccount (String number, User user) throws NoSuchAccount {

        …

    }

 

    public ActionForward execute(

        ActionMapping mapping,

        ActionForm form,

        HttpServletRequest request,

        HttpServletResponse response) {

        User user = (User)request.getSession().getAttribute("user");

        String number = ((AccountForm)form).getAccountNumber();

        Money amount = ((AccountForm)form).getAmount();

        Account account;

 

        //Find account corresponding to number and verify user

        //YOUR ANSWER GOES HERE!

 

        account.update(amount);

        return mapping.findForward("success");

    }

2.      This question is about the Model View Controller pattern (MVC).

a)      Describe briefly what the three elements of MVC are intended to represent. [6 marks[JSB3] ]

b)      Why is splitting an application into these three elements a "good thing"? [6 marks[JSB4] ]

c)      In the so-called "Model 2" version of MVC, how is each component of an application conventionally implemented in Java? [3 marks[JSB5] ]

d)      Describe how the Apache Struts framework supports the MVC pattern, identifying the features of Struts that contribute to the implementation of the different aspects of MVC. [10 marks[JSB6] ]

3.      Consider the following fragment of code from an online banking system implemented as a Java web application:

      1         public int getBalance (String accnum) throws NoSuchAccount {

      2             int balance;

      3             String driver = "oracle.jdbc.driver.OracleDriver";

      4             String URL = "jdbc:oracle:thin:@localhost:1521:JIM";

      5             Class.forName(driver).newInstance();

      6             Connection conn = DriverManager.getConnection(URL);

      7             Statement stmt = conn.createStatement();

      8             String query = "SELECT accountNumber, balance FROM Accounts "

      9             + "WHERE accountNumber = " + accnum;

  10             ResultSet result = stmt.executeQuery(query);

  11             //AAA

  12             while (result.next()) {

  13                 //BBB

  14             }

  15             //CCC

  16             return balance;

  17         }

a)      Explain what is happening in lines 3-6 of the above. What component would need to be installed (and where) in the Java web application in order for the above code to work? [6 marks[JSB7] ]

b)      In a real application, why would it not be appropriate to include lines 3-6 in this method? [4 marks[JSB8] ]

c)      Assuming that accountNumber was the primary key of the table Accounts, how many times would you expect the code at BBB (line 13) to be executed and what would this tell you? [6 marks[JSB9] ]

d)      Write some Java code that will test for the existence of an account with the specified number and throw a NoSuchAccount exception if it does not. Would you place this code at AAA, BBB or CCC? [4 marks[JSB10] ]

e)      Write some Java code that will extract the balance from the ResultSet and assign it to the variable balance. Would you place this code at AAA, BBB or CCC? [5 marks[JSB11] ]

4.      What, in your judgement, is the future of web applications and their development? [25 marks[JSB12] ]

Section B – Answer these questions in a separate booklet

5.      Examine the Java Servlet code in Table 1 and answer the following questions.

      1     public class ThreeParams extends HttpServlet {

      2       public void doGet(HttpServletRequest request, HttpServletResponse response)

      3                           throws ServletException, IOException {

      4         response.setContentType("text/html");

      5         PrintWriter out = response.getWriter(); 

      6         String title = "Reading Three Request Parameters";

      7         out.println("<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +

      8                     "<BODY BGCOLOR=\"lightblue">\n" +

      9                     "<H1 ALIGN=CENTER>" + title + "</H1>\n" + "<UL>\n" +

  10                     " <LI><B>param1</B>: “ + request.getParameter("param1") +        

  11                     "\n" + " <LI><B>param2</B>: "

  12                     + request.getParameter("param2") + "\n" +

  13                     " <LI><B>param3</B>: “ + request.getParameter("param3") +     

  14                     "\n" + "</UL>\n" + "</BODY></HTML>");

  15       }

  16     }

Table 1: Java Servlet Code

a)      In the doGet() method (line 2) what are the parameters HttpServletRequest and HttpSerlvetResponse used for? [3 marks each, 6 marks in total[JSB13] ]

b)      What does the statement “PrintWriter out = response.getWriter(); ” on line 5 do? [2 marks[JSB14] ]

c)      If the servlet is invoked by using a Web browser and accessing the URL http://localhost:8080/servlet/ThreeParams – exactly what would be displayed by the browser? [Maximum of 12 marks[JSB15] ]

d)      If the servlet is invoked by using a Web browser and accessing the URL http://localhost:8080/servlet/ThreeParams?param1=one&param2=two&param3=three.  What would be displayed in the updated browser page? [3 marks[JSB16] ]

e)      Rather than explicitly printing the various HTML tags in out.println() statements, what would be a better solution? [2 marks[JSB17] ]

6.      This question is about Web Services.

a)      There are three components that take part in a SOAP application: the client application, the SOAP processor, and the application server. Briefly describe the role of each part of the SOAP application [2 marks per part, 6 marks in total[JSB18] ].

import org.apache.axis.client.Call;

import org.apache.axis.client.Service;

import java.net.URL;

public class Client1 {

  public static void main(String[] args) throws Exception {     

    String endpoint = "http://localhost:8080/axis/servlet/AxisServlet";

    Service service = new Service();

 

    Call call = (Call) service.createCall();

 

    call.setTargetEndpointAddress(new URL (endpoint));  

 

    String ret = (String) call.invoke("HelloServer", "sayHelloTo",

        new Object[]{args[0]});

    System.out.println(ret);

  }  

}

Table 2: Java Client Code

b)      Consider the Java Client code shown in Table 2. Answer the following questions about this code [marks as indicated, 10 marks in total]:

i)        What is special about the endpoint used in this program? [2 marks[JSB19] ]

ii)       Identify the Java class and the method that is invoked on the deployed Web Service [4 marks[JSB20] ].

iii)     What are the output and input sent from, and a received by, the Java client? Name the datatype of each in your answer [4 mark[JSB21] ]

c)      The scope of a Web service can be request, session, or application. Describe each type of scope [3 marks per, 9 marks in total[JSB22] ].

7.      The Web Services architecture can be said to have a "publish and subscribe" architecture. Web Services is based on three XML-based standards; SOAP for communications, WSDL for describing services, and UDDI for the publication of services.

a)      Draw a diagram showing how a service provider and requestor use this publish and subscribe architecture of Web Services, label where SOAP, WSDL and UDDI would be used [10 marks[JSB23] ].

b)      Explain briefly the function and purpose of each of the following:

i)        SOAP [5 marks[JSB24] ],

ii)       WSDL [5 marks[JSB25] ],

iii)     UDDI [5 marks[JSB26] ].

8.      This question is about concurrency and distributed systems.

a)      What is concurrency and how does it differ from parallelism? [2 marks[JSB27] ]

b)      Give three reasons why concurrent programming is useful. [6 marks[JSB28] ]

c)      In distributed systems, the overall aim is to avoid deadlock– that is to design systems where deadlock cannot occur. What are the four necessary and sufficient conditions for deadlock to occur? [12 marks[JSB29] ]

d)      In the lectures we looked at the Dining Philosophers Problem; which is one where five philosophers sit around a circular table and spend their life alternatively thinking and eating a large plate of noodles. A philosopher needs two chopsticks to eat a helping of noodles. Unfortunately, the philosophers only have five chopsticks. One chopstick is placed between each pair of philosophers and they agree that each will only use the chopstick to his immediate right and left. Name two simple strategies that can be used to avoid the deadlock that occurs. [5 marks[JSB30] ]


·         [JSB1]ActionError or ActionMessage represent a message from application to user

·        ActionErrors / ActionMessages is a collection of above normally passed to view as a request attribute

·        Struts taglibs provide means to display and format messages, and also to relate them to particular properties on a form

·        Could also mention facilities for internationalisation

 [JSB2]Sample solution:

        ActionErrors errors = new ActionErrors();

        try {

            account = findAccount(accnum, user);

        } catch (NoSuchAccount ex) {

            ActionError err = new ActionError("error.noSuchAccount", accnum);

            errors.add("accnum", err);

            saveErrors(request, errors);

            return mapping.findForward("failure");

        }

 [JSB3] [JSB3]Model

The model represents enterprise data and the business rules that govern access to and updates of this data. Often the model serves as a software approximation to a real-world process, so simple real-world modeling techniques apply when defining the model.

View

The view renders the contents of a model. It accesses enterprise data through the model and specifies how that data should be presented. It is the view's responsibility to maintain consistency in its presentation when the model changes. This can be achieved by using a push model, where the view registers itself with the model for change notifications, or a pull model, where the view is responsible for calling the model when it needs to retrieve the most current data.

Controller

The controller translates interactions with the view into actions to be performed by the model. In a stand-alone GUI client, user interactions could be button clicks or menu selections, whereas in a Web application, they appear as GET and POST HTTP requests. The actions performed by the model include activating business processes or changing the state of the model. Based on the user interactions and the outcome of the model actions, the controller responds by selecting an appropriate view.

Need to show basic understanding of above to get 3 x 2 marks.

Good thing because:

  1. It is good software engineering practice to maintain separation of concerns.
  2. An application might have more than one user interface (for example users might be able to access either as a windows application and a web application) and the elements of the user interface need to be kept separate from the parts that are common to each.
  3. Different developers (with different skills) may be responsible for different aspects of the application. Frequently, user-interface designers will be responsible for the view while conventional programmers may be responsible for the controller and model. In some circumstances, the controller might be the responsibility of an interaction engineer (or team).

2 marks for appreciation of each of above 3.

Marks deducted for silly answers.

 [JSB5]Controller = servlets; model = set of Java Bean classes; view = JSPs

 [JSB6]Struts provides:

·        an ActionServlet that centres control of the application and allows specific actions to be invoked

·        taglibs to help with the view

·        lots of bits (including the taglibs) provide support for JavaBeans to facilitate integration of model and view

Marks (out of 10) for identifying these (or other) aspects

 [JSB7]Line 3 instantiates an object of the class whose name is specified in line 1. This requires the Oracle JDBC driver classes to be available (e.g. by installing the JAR in the WEB-INF/lib (normally) directory.

 [JSB8]Because you wouldn't want to instantiate this class over and over, and you would probably want to maintain a pool of database connections somewhere.

 [JSB9]Either zero times (indicating account not found) or once (indicating account found). Because the query is by primary key, a maximum of one row can be returned.

 [JSB10]The line

if (!result.first()) { throw new NoSuchAccount(); }

at AAA would do the trick but there are other result methods that could achieve the same end, and I don't care if the student makes a sensible one up!

 [JSB11]Either balance = result.getInt(2); or balance = result.getInt("balance");

at BBB. At CCC, result will be pointing to the empty row.

 [JSB12]Marked by generic essay criteria.

·         [JSB13]Use " HttpServletRequest" to read incoming HTTP headers (e.g. cookies) and HTML form data (e.g. data the user entered and submitted) [3 marks]

·         Use " HttpSerlvetResponse" to specify the HTTP response line and headers (e.g. specifying the content type, setting cookies) [3 marks]

 [JSB14]Binds "out" to send content to browser (response).

 [JSB15]

Figure 1: Answer c)

Marking: [marks as indicated, 12 marks]

HTML <Title> – 1 mark

Page Title in <CENTER>– 2 mark

List item + param1:null – 3 mark

List item + param2:null – 3 mark

List item + param3:null – 3 mark

 [JSB16]param1:one – 1 mark

param2:two – 1mark

param3:three – 1 mark

 [JSB17]Write a set of utilities to output the various HTML tags, such as “ServletUtilities.headWithTitle(title)”

·           [JSB18]Client Application: A program/Servlet/JSP/etc. that sends a SOAP request. (it wants to use a service) [2 marks].

·          SOAP Processor: A program that can receive SOAP requests and act accordingly (e.g., call an method of the application server) [2 marks].

·          Application Server: A program that supplies the Web service [2 marks].

 [JSB19]http://localhost:8080/axis/servlet/AxisServlet is the default endpoint for a deployed Web Service.[ 2 marks].

 [JSB20]HelloServer is the class [2 marks]

SayHelloTo is the method invoked [2 mark].

 [JSB21]Sent: Object[]{args[0]}) – 2 marks.

Received: String ret – 2 marks

·           [JSB22]"request"  – make a new object to service each request - this is the default [3 marks].

·          "session"  – associate a new object with each session [3 marks.

·          "application" – all users share a singleton object, i.e. the same service instance is used to serve all invocations [3 marks].

 [JSB23]10 marks in total, marks shown [7] + 1 mark for service registry + service provider + service requestor

 [JSB24]Simple Object Access Protocol [5 marks, marks for understanding and significant points]:

 

o       SOAP provides a simple and lightweight mechanism for exchanging structured and typed information between peers in a decentralized, distributed environment using XML.

o       SOAP does not itself define any application semantics such as a programming model or implementation specific semantics.

o       SOAP defines a simple mechanism for expressing application semantics by providing a modular packaging model and encoding mechanisms for encoding data within modules.

o       This allows SOAP to be used in a large variety of systems ranging from messaging systems to RPC.

o       SOAP consists of three parts:

a. The SOAP envelope construct defines an overall framework for expressing what is in a message; that should deal with it, and whether it is optional or mandatory.

b. The SOAP encoding rules defines a serialization mechanism that can be used to exchange instances of application-defined datatypes.

c. The SOAP RPC representation defines a convention that can be used to represent remote procedure calls and responses.

 [JSB25]Web Services Description Language (WSDL) [5 marks, marks for understanding and significant points]:

 

·         WSDL is an XML grammar for specifying a public interface for a Web Service.

·         This public interface can include the following:

a. Information on all publicly available functions.

b. Datatype information for all XML messages.

c. Binding information about the specific transport protocol to be used.

d. Address information for locating the specified service.

 [JSB26]Universal Description Discovery and Integration (UDDI) [5 marks, marks for understanding and significant points]:

·          UDDI currently represents the discovery layer within the Web Services protocol stack.

·          UDDI supports ‘publish, find and bind’.

·          At its core, UDDI consists of two parts:

o       The UDDI is a technical specification for building a distributed directory of businesses and Web Services.

§         Data is stored within a specific XML format, and the UDDI specification includes API details for searching existing data and publishing new data.

o       The UDDI Business Registry is a fully operational implementation of the UDDI specification.

Launched in May 2001 by Microsoft and IBM, the UDDI registry now enables anyone to search existing UDDI data.

 [JSB27][1 mark for each correct explanation, 2 marks in total]

Concurrency - Logically simultaneous processing, does not imply multiple processing elements (PEs). Requires interleaved execution on a single PE [1 mark].

Parallelism - Physically simultaneous processing, involves multiple PEs and/or independent device operations [1 mark]

 [JSB28][2 marks for each correct reason, 6 marks in total]

  • Performance gain from multiprocessing hardware

o                    Parallelism for example.

  • Increased application throughput

o                    An I/O call need only block one thread.

  • Increased application responsiveness

o                    High priority thread for user requests.

  • More appropriate structure

for programs which interact with the environment, control multiple activities and handle multiple events

 [JSB29][3 marks per correct condition, 12 marks in total]

1.      Serially reusable resources: the processes involved share resources, which they use under mutual exclusion [3 marks]

2.      Incremental acquisition: processes hold on to resources already allocated to them while waiting to acquire additional resources [3 marks]

3.      No pre-emption: once acquired by a process, resources cannot be pre-empted (forcibly withdrawn) but are only released voluntarily [3 marks]

4.      Wait-for cycle: a circular chain (or cycle) of processes exists such that each process holds a resource, which its successor in the cycle is waiting to acquire [3 marks].

 [JSB30][2/3 marks for each strategy, 5 marks in total]

 

The Dining Philosophers program deadlocks when every philosopher has obtained his/her right (or left) chopstick. No philosopher can obtain his/her left chopstick and so no progress can be made – the system is deadlocked.

 

Deadlock can be avoided in the Dining Philosophers system by for example:

·          Making one of the philosophers picks up his/her chopsticks in the reverse order (i.e. left before right). [2 marks]

Making a philosopher drop their chopstick if held for more than a certain time (use pre-emption) [3 marks]