Likes

Advance Java Subjective Question

1.Define the following terms:Purchase OrderDelivery ChallanRejection NoteGoods Received NoteGoods Inwards Note

Ans:
i)Purchase Order - A document from the customer to the seller listing the required items and providing a description of the goods.
ii)Delivery Challan - A document that is sent with the shipment of goods. It lists the description, and quantity of the goods that are delivered.
iii)Rejection Note - A document that lists the materials that are rejected due to defects found during quality inspection. The reason of rejection is also included.
iv)Goods Received Note - A document that acknowledges that the materials have been inspected and accepted by the manufacturer.
v)Goods Inwards Note - A document that records the entries of the materials when they are received at the store of the organization.


2.Identify the various criteria for classifying an organization and discuss them in detail.

Ans:
An organization consists of a group of people working specifically to achieve a common goal. Organizations can be classified on the basis of nature of work, profitability, type of system, and ownership

i)Based on the Nature of Work:
Organizations can be classified depending on their nature of work as:

a)Manufacturing-based: Business organizations involved in producing tangible goods or products are called manufacturing organizations. b)Automobile manufacturing companies, iron and steel plants, and food and beverage processing units are examples of manufacturing organizations.
c)Service-based: Business organizations involved in providing services to other businesses or people, rather than producing tangible goods, are called service-based organizations. Airlines, hotels, hospitals, banks, and insurance agencies are examples of service organizations.
Based on Profitability:

ii)Organizations may be classified on the basis of their focus on profit. These organizations can be:

a)Profit-based organizations: The primary goal of these organizations is to increase their profit margin. These organizations try to increase the value of their share by increasing the value of the company stock.
b)Nonprofit-based organizations: These organizations do not have profit as their primary goal. They are usually involved with socially relevant issues. Some examples of nonprofit organizations include social groups, universities, human rights commissions, and worker unions.

iii)Based on the Type of System:
Based on the type of system an organization implements, it can be classified as simple or complex and adaptive or nonadaptive.

a)Simple or complex: A simple system consists of a lesser number of elements that interact with each other in a simple and uncomplicated manner. An eating joint is an example of a simple system, wherein the customer places an order, the ordered food is prepared, and the food is served to the customer.  Components in a complex system have a high level of interaction with each other. A car manufacturing organization is an example of a complex system.
b)Adaptive or nonadaptive: An adaptive organization is one that is able to change in response to the changes in the environment. For example, the fashion and cosmetics industries are highly dependent on external stimuli. A nonadaptive organization is one that is not able to change easily in response to external stimuli. For example, the automobile industry needs to take many factors into account before deciding on a change. These factors may include the cost of manufacturing a modified product or the availability of raw materials.

iv)Based on Ownership:
On the basis of the nature of ownership, business organizations can be classified into the following types:

a)Sole proprietorship: When one individual heads a business organization, it is said to be sole proprietorship.
b)Partnership: A partnership organization has two or more individuals conducting the business together. Corporation: A corporation is a legal entity conducting business with numerous owners.


3.Explain the following terms briefly:
Test case
Collaboration
Generalization
Job shops
Batch processing

Ans:
i)Test case: A test case is a set of actions that is executed to examine whether or not the implemented code of the software system complies with the requirements stated by the customer. This helps you to validate the system functionality against system requirements. A test case developed for a particular function of the software system includes a set of test input, execution conditions, and expected results.
ii)Collaboration: UML provides specific modeling constructs, known as collaborations, to model a use case realization in the design phase. Collaboration is a collection of classes, interfaces, and sub-systems that interact with each other to achieve the functions of a use case. It can be represented by creating an oval with a dotted line.
iii)Generalization: The generalization relationship exists among the actors or use cases that have similar behavior and properties. Two actors or use cases are said to have a generalization relationship when the characteristics of one actor or use case can be derived from the characteristics of another actor or use case.
iv)Job shops: The Job shop production process involves the manufacturing of a wide variety of products in small numbers for a specific customer requirement. This production process is used to make a higher number of products as compared to projects. Job shops require general-purpose equipment that is flexible, because every product goes through a different sequence of processes. In job shops, resources are sometimes overloaded, while at other times, they may be idle. Examples of a job shop include manufacturing of special items, such as furniture.
v)Batch processing: The batch processing production process involves large-scale manufacturing of products on the same equipment. Every new product incurs additional setup costs that can be reduced by manufacturing more units in each cycle. Products are stocked and supplied based on customer demand. Batch processing caters to those products that are generic in nature. Therefore, general-purpose equipment is used. The process does not undergo many changes, but skilled workers are required to perform tasks. Examples of batch processing include book publishing, garment manufacturing, and pharmaceutical production.


4.Describe the class diagram and class notations used in UML. Explain the visibility of attributes and operations in a class diagram. Explain the syntax of attributes and operations in class diagrams.

Ans:
Class diagram and class notations used in UML

A class diagram is used to create a structural model of a software system. The structural model describes the static architecture of a system and helps the software developer to translate the system use cases into system design.

 UML provides a class notation to represent classes in class diagrams. The class notation has three compartments where the first compartment depicts the name of the class, the second compartment depicts the attributes of the class, and the third compartment depicts the operations of the class.You can use class notations to document the design of a system in accordance with the requirements identified during the requirements analysis phase.
Visibility of attributes and operations

It is vital to ensure that the data of your classes remain secure. For this, UML allows you to specify the visibility of the class attributes and operations, which controls the accessibility of these class members from other classes. UML provides the following four visibilities for the attributes and operations of a class:

i)+: Indicates that the attribute or operation is accessible to other classes. In other words, the attribute or operation is public.
ii)-: Indicates that the attribute or operation is inaccessible to other classes. In other words, the attribute or operation is private.
iii)#: Indicates that the attribute or operation in the base class is accessible to derived classes. In other words, the attribute or operation is protected.
iv)~: Indicates that the attribute or operation is accessible to the classes, which are within the same package.
Syntax of attributes in class diagrams

The attributes of a class follow certain syntax in the class diagrams. The syntax to depict an attribute in a class diagram is:

visibility name: type

The preceding syntax contains the following mandatory fields:

i)visibility: Specifies whether the attribute of the class is private, public, protected, or package.
ii)name: Indicates the name of the attribute. This is a mandatory field.
iii)type: This is an optional field. It specifies the data type of the attribute.
For example, the Name attribute of the Employee class can be represented as:

-Name: String

Syntax of operations in class diagrams

The syntax to represent an operation of a class in the class diagrams is:

visibility name (parameter-list): return-type

The preceding syntax contains the following fields:

i)visibility: Specifies whether the operation of the class is private, public, protected, or package.
ii)name: Indicates the name of the operation.
iii)parameter-list: Indicates the list of parameters for the operat.
iv)return-type: Represents the data type of the value returned by the operation. This field can take the null value when the operation does not return any value.
The parameters of an operation are denoted using the following syntax:

Parameter name: type

For example, the getName() operation of the Employee class can be represented as:

+getName(EmpId : int) : string


5.What is meant by logistics? Explain the activities involved in logistics planning (any two) in detail.

Ans:
Logistics is a business-planning framework. It involves planning for the movement and storage of materials and information from any point in the operational process to the final order-fulfillment stage. Organizations thrive on the effectiveness and efficiency of their operational strategies. An efficient logistics plan supports in implementing the organizational processes, such as production and sales and marketing, effectively.

Logistics planning involves the following activities:

Analyzing the core business processes

Analysis of the core business processes of an organization is important as the logistics activities differ depending on the nature of the business undertaken by an organization.

Some of the general processes for a typical manufacturing-based business organization include:

i)Purchasing of material
ii)Receiving the material
iii)Warehousing
iv)Controlling the inventory
v)Handling the material
vi)Shipping
vii)Making decisions for physical distribution

The distribution of products is an important activity for an organization and its customers. For example, in a manufacturing organization, the goods are typically moved from the Production department to the warehouses, where they are stored until they are sent to the dealers.
The main factors to be considered while making decisions for the physical distribution are:

The size, number, and location of warehouses
The mode of transport depending on the type of goods, distances, and weights
The work force to be employed or hired.
Deciding the location of facilities:

Whenever an organization wants a new factory, warehouse, shop, office or other facilities, it is important to identify a strategic location.

Most organizations evaluate the feasibility of the location of a facility, such as a production plant, based on the factors, such as:

i)The locations of competitors, suppliers, and customers
ii)Availability of skilled workforce in the area
iii)Costs pertaining to operations, wages, transport, and taxes
iv)Transport and services availability
v)Plans regarding future expansion, or globalization

6.What is a state machine diagram? Explain its various components.

Ans:
Before developing a software system, a developer must understand the various states through which a component goes from its creation to termination. For this, UML provides a state machine diagram. A state machine diagram represents the various states that an object goes through during its lifecycle in response to events. You need to model the behavioral aspects of a system by using state diagrams. Therefore, you create a state diagram for the objects that respond to events. The various constituents of a state diagram are states, events, and transitions.

i)A state depicts a condition of an object and the activities of an object during its lifecycle. An initial state is the starting state of an object and is represented as a dot. A final state is the end state of an object and is represented as a dot encircled by a ring.
ii)An event is an occurrence that triggers a change of state of an object. It signifies the receipt of a message that requests for an operation to be performed.
iii)A transition is a change of state of an object due to the occurrence of an event. For example, the state of customer complaint transitions from Open to Closed when the Complaint Resolved on Phone event occurs. Similarly, the state transitions from Open to Waiting when the Complaint Not Resolved on Phone event occurs and from Waiting to Closed when the Complaint Resolved Onsite event occurs.

7.What is a product? Explain the product life cycle in detail.

Ans:
A product is an article or a substance that is manufactured or produced by a company for sale. The main objective of a product is to make the customer feel satisfied or benefited after the purchase of the product. Before marketing a product, it is important to understand the life cycle of a product in the market. When a product is launched, the demand for it varies with time. There are different stages through which the product passes when it is introduced in the market. These stages comprise the product life cycle. The life cycle of a product starts when it is launched in the market till the time it remains in the market. This life cycle helps organizations in analyzing the product's impact on the organization's market share. The different stages of a product life cycle are: introduction, growth, maturity, and decline.

i)Introduction: This is the first stage when the product is introduced in the market. The main focus of the organization at this stage is to make the customer aware of the product and its benefits. For this, organizations invest more in advertising and other promotional strategies. The focus is not on revenue generation.
ii)Growth: At the growth stage, once the product is established in the market, more retailers and customers are attracted to it. At this stage, the organization maintains the quality and price of the product to attract more customers. This results in profits for the organization.
iii)Maturity: At the maturity stage, the sale of the product first reaches saturation in the market. The distribution of the product reaches to the fullest in the market, leaving minimum demand for the product. Thereafter, its sale starts declining. The primary goals of an organization at this stage are to maintain the market share and promote the product by differentiating it from competitors? product.
iv)Decline: At the decline stage, there is a rapid increase of competing products that may be better in quality and low in price. As a result, sales start declining and production volumes need to be reduced. The primary goal of an organization at this stage is to try maintaining the sale of the product by adding new features and reducing the cost. However, if the product is still incurring loss, the organization may discontinue the product.

8.What is meant by logistics? Explain the activities involved in logistics planning (any two) in detail.

Ans:
Logistics is a business-planning framework. It involves planning for the movement and storage of materials and information from any point in the operational process to the final order-fulfillment stage. Organizations thrive on the effectiveness and efficiency of their operational strategies. An efficient logistics plan supports in implementing the organizational processes, such as production and sales and marketing, effectively.

Logistics planning involves the following activities:

i)Analyzing the core business processes

ii)Analysis of the core business processes of an organization is important as the logistics activities differ depending on the nature of the business undertaken by an organization.

Some of the general processes for a typical manufacturing-based business organization include:

i)Purchasing of material
ii)Receiving the material
iii)Warehousing
iv)Controlling the inventory
v)Handling the material
vi)Shipping
vii)Making decisions for physical distribution

The distribution of products is an important activity for an organization and its customers. For example, in a manufacturing organization, the goods are typically moved from the Production department to the warehouses, where they are stored until they are sent to the dealers.
The main factors to be considered while making decisions for the physical distribution are:

i)The size, number, and location of warehouses
ii)The mode of transport depending on the type of goods, distances, and weights
iii)The work force to be employed or hired.
Deciding the location of facilities:

Whenever an organization wants a new factory, warehouse, shop, office or other facilities, it is important to identify a strategic location.

Most organizations evaluate the feasibility of the location of a facility, such as a production plant, based on the factors, such as:

i)The locations of competitors, suppliers, and customers
ii)Availability of skilled workforce in the area
iii)Costs pertaining to operations, wages, transport, and taxes
iv)Transport and services availability
v)Plans regarding future expansion, or globalization

9.Explain the various stages of marketing process.

Ans:
The stages of the marketing process are analyzing the need for a product, deciding upon the marketing strategy, implementing the marketing strategy, and monitoring the product.

i)Analyzing the need for a product: While analyzing the need for a product, organizations need to analyze the customer's requirements and its own capabilities to manufacture a product. While planning for the marketing strategy for a product, an organization must analyze whether it has sufficient funds to be able to manufacture and get sufficient returns.
ii)Deciding upon the marketing strategy: After the analysis of the customer requirements and market trends, an organization needs to decide upon its marketing strategy. This strategy requires a decision on the marketing mix as well as a target market for which the marketing mix is prepared. The marketing mix consists of variables that marketing managers can control in order to best satisfy customers in the target market.
iii)Implementing a marketing strategy: The plan prepared at the decision stage of the marketing process is implemented at this stage. The product is launched in the market and the planned promotional strategies are implemented to ensure customer awareness and sale of the product. The launch of a product includes the following activities:
a)Product performance is evaluated through tests and quality checks.
b)Final packaging is designed and ordered.
c)Sales channels are identified and established.
d)Product feedback is updated based on market feedback and analysis.
e)Product documentation is completed and finalized.
f)User documentation, operating manuals, advertisement materials, product brochures, marketing materials, press releases, website pages, and maintenance instructions are completed and ready to be distributed at the appropriate time.
g)A Production Readiness Review document is prepared. This document confirms that all preparations are completed and the product is ready for launch.
h)The new product is launched when the service, sales, and distribution channels are ready.
iv)Monitoring the product: The task of the marketing team does not get over with the launch of the product in the market. At this stage, an organization needs to collect regular feedback from customers regarding their likes, dislikes, and suggestions for improvement of the product.  At this stage, competitors and their similar products need to be monitored closely and the marketing strategy may need to be modified accordingly.

10.What is structural modeling? List any three UML diagrams for structural modeling and explain them briefly.

AnsUML provides various modeling techniques to represent the framework of a software system. Each modeling technique contains a set of diagrams to represent the requirements and structure of the software system. The UML modeling techniques may be used for structural modeling and behavioral modeling. Structural modeling involves depicting the static features of the software system. It is used to represent how the components or elements exist in a system.

The various UML diagram for structural modeling are:

i)Class diagram: A class diagram represents a set of classes, interfaces, and their relationships. It describes the set of attributes and operations associated with each class and the relationships among the various classes.
ii)Object diagram: An object diagram represents an instance of a class diagram. It represents the properties of a particular instance of a class.
iii)Package diagram: A package diagram represents the interrelated classes and interfaces of the system in a package.  It helps in representing the various packages of a software system and the dependencies between them. It also gives a high-level impression of use case and class diagrams.
iv)Component diagram: A Component diagram combines packages or individual entities to form components. You can depict these components and their dependencies by using a component diagram.
v)Deployment diagram: A deployment diagram shows the physical placement of components in nodes over a network. A deployment diagram can be drawn by identifying nodes and components.


11.Explain the concept of production planning in brief. Discuss in detail about the MRP phase of production planning.

Ans:
Production planning is an integral part of the production process. It is the first step in the production process. Every manufacturing-based organization performs a set of operations for producing finished goods. Each operation in the production process of an organization must be systematically designed, planned, organized, and controlled.

Production planning:

i)Helps organizations to develop and implement strategies so that cost-effective goods are produced with minimum resources.
ii)Involves the systematic scheduling of workers, materials, and machines for manufacturing products efficiently, economically, and timely.

The different phases of production planning are:
1. Material requirement planning (MRP)
2. Selecting the production process

MRP is an inventory control process used to calculate the amount of raw materials required to manufacture a specific product. MRP involves reviewing the stock quantity of raw materials according to the quantity of products to be manufactured in a specific period. It then involves calculating the quantity of components and materials required to manufacture those items and identifying the supply of materials required for the scheduled production. MRP involves planning work orders and purchase requisitions and suggesting appropriate rescheduling of the current material plan by taking into account the actual delivery date of a product.
The main inputs of MRP are:
i)Master Production Schedule (MPS) shows the quantity of products to be manufactured in a specific period. It is a detailed manufacturing plan that determines the products a manufacturer has to produce within predefined timelines. During MRP, the estimated plan provided by MPS is translated into a detailed plan that specifies the schedule for material requirement and delivery.
ii)Bill of Materials (BOM) consists of the materials, parts, and components that are required to manufacture the product. During MRP, the BOM and MPS are used to calculate the amount of each material required.
The lead-time is the time between the placement of an order for a product and the actual date of delivery. Determining lead-time of raw materials is essential for a manufacturing company so that the finished goods can be delivered to the customer in a timely manner and any shortages can be handled before the production process starts.
iii)Inventory records provide a detailed list of all the items that are currently in stock. The information is stored in a tabular format. MRP uses these existing inventory records to calculate the net quantity of materials required from the supplier. The net quantity required is calculated by subtracting the existing inventory from the total materials required as per MPS.
The main outputs of MRP are:
i)Schedule for Orders: It provides guidelines to place an order depending on the lead-time.
ii)Purchase Orders: It is a buyer's document and is used to formalize a purchase transaction with a supplier. On acceptance by the supplier, it becomes a legally binding contract between the two parties and hence, it must specify all terms and conditions applicable to the contract.
iii)Reports: The information from MRP is processed to generate various reports, such as performance reports and inventory transactions.


WCD-LAB @HOME 12

In this exercise, you will use role based security to restrict access to elements of a web application.


Task - Verify the Project Prior to Adding Security
1. Open the project SL314ml21abl in the d:\labs\student\exercises directory and run it. This is essentially the same as Lab 9. but without the filter. Verify that you can get to all the pages, and can log in or not as you choose.

Task • Configure Users in the GlassFish Server
1. Select the Services tab (second tab to the right of the Projects tab. at the top left of the NetBeans window).
2. Open the Servers tree element and right click the GlassFish Domain. Select View Admin Console from the popup menu.
3. When the admin console starts in your web browser, open the Tree on the left side of the window. Find the hierarchy: Common Tasks —> Configuration — Security —*■ Realms —* file, and click the file element.
4. The right hand pane shows the page Edit Realm. Click the button Manage Users just below this title.
5. Click the New button to add a user. Add the User IDs Alice and Maverick in each case, use the User ID (with the same capitalization) as the password.

Task - Assign Users to Roles
1. In the Projects tab. open the tree SL314ml21abl —*• Web Pages —* Web Inf. Right-click the sun-web.xml file and select edit.
2. In the editor pane at the right, select the Securin’ tab and click the button at the right Add Securin’ Role Mapping.
3. Edit the field Securin’ Role Name which currently contains the text rolel and change the role name to Users.
4. Click the button Add Principal and enter the user name Alice then click OK.
5. Type Control-S to save the file.

Task - MandateLogin Before Access
1. Right click on the project, and select New — Standard Deployment Descriptor (web. xml).
2. Select the Securin’ tab. then open the Login Configuration element and select the radio button for Basic.
3. Open the Securin’ Roles element, click the Add button, and enter Users, then click OK.
4. Open the Securin’ Constraints element (click the Add Securin’ Constraint button). Enter a resource name (TheConstraint is fine).
5. Click the Add button located just under the Name column heading in the Web Resource Collection block. In the dialog box that pops up. enter a resource name (MyResource will serve), then enter the URL Pattern /ApplicationController. Ensure that All HTTP methods is selected and then click OK.
6. Check the checkbox Enable Authentication Constraint, then click the Edit button to the right of Role Name(s). Select the role Users and click the Add — button. Click OK.

Task - Run the Application and Verify Login Requirement
1. Run the program, and verify that before you can reach either the Quote or Advertisement pages, you are forced to log in as Alice. You should be rejected from the pages if you login as Maverick, since this user was not added to the Users role.

Task - Pick Up the Username from the Environment
1. Edit the Application Controller sen'let so that it does not look for a username in the parameters, and does not provide a login operation.
2. In place of the old mechanism you just removed, extract the user name from the Principal object that can be found from the request.

Task - Modify the Application to Use Form-based login
1. Edit the login, jsp form that will be used to prompt for user login. This should submit to the action j_security_check. The user name field must be called j_username. Create a password field, which must be called j_password.
2. Arrange two buttons on the form. One should be of type submit and labeled Login. The other should be of type reset and labeled Clear.
3. Edit the web.xml file. Change the Login Configuration from Basic to Form. In both the fields for Form Login Page and Form Error Page, enter login.jsp.
4. Test that the application now uses the form you created for login, and that failed logins are also directed to the same login page.

Task - Provide a Logout Mechanism
1. To this point, there has been no proper way to logout once you are logged in. To provide for this, add a new operation Logout to the ApplicationController sen'let. When invoked, this should invoke the method session.invalidateQ. and dispatch back to the index, jsp page.
2. Add another option Logout to the index, jsp page.
3. Test that the application now allows a user-controlled logout operation.

WCD-LAB @HOME 11

Create a servlet that generates delayed responses using the asynchronous servlet API and asynchronous JavaScript techniques.


Task - Create a New Project and Asynchronous Servlet
1. Create a new project named 5L31-nlll;bl. In the project create a ser.iet called Upsate in the package web.
2. Set the servlet to support asynchronous operation. Do this using the element asyncSuspor^ed = true in the gvleb Servlet annotation.
3. Delete the contents of the process Request method.

4. In the now-empty process Request method:
a. Start the asynchronous processing and keep a handle on the AsyncCootext in a final variable.
b. Consult the sample code in the "Simple Asynchronous Client Example" section in Module 11 of the student guide for more guidance on these steps.

5. Create an anommous inner class, implementing the Runnable interface. In the rur method of this class:

3. Extract the request and response objects from the -syncCc-ntext and store them m local variables.
b. Introduce a delay between 2 and 15 seconds.
c. Select a word from this list at random: wonderful, unexpected, strange, elegant
(you can add more adjectives if you choose, they will simply be used to construct a changing random remark). Return the chosen word as the entire body of the response (do not include air.- HTML tags whatsoever).
d. Call the cc<rplete method on the isyncCcntext.

6. Test the code. Run the application. To do this, build and deploy the application, and then enter the URL:
http: //localhost:8d80/SL314mlllabl/Update directly into the browser’s URL window.
Task - Create an Asynchronous Client

1. Edit the index, jsp file and the following text just after the top-level headmg
(</hl>):
<p>Oh my, that was... <span id="adjective">let me think...</span>!
<p>
2. Create a JavaScript block, after the end of the </body> tag. The script opening and closing tags are exemplified in the "Simple Asynchronous Example" section m Module 11 of the student guide.

3. In the JavaScript block, add the following elements. Refer again to the "Simple Asynchronous Client Example" section in Module 11 of the student guide if you need hints or guidance on the JavaScript syntax.
a. Add variable declarations for two variables called req and tcUpdate.
b. Use the docunent. jetElerentByld method to obtain a reference to the adjective span that was created in step one of tins task.
c. Initialize the req variable using either a new XMLHttpRequest. or a new AcciveXObject. dependmg on the browser support.
d. Declare a function called :endReque=t().
e. In the =endRequest() function, install a readystatechange handler. In the handler, when a successful response is received, update the innerHTHL element of the tcUpsate variable using the responseText of the request.
f. After the declaration of the readystatechange handler, call the open and send methods on the req object to send the HTTP request to the server. The request should send a GET request, to the URL Update.
g. Close the definition of the sendRequest method, then call the sendRequest method directly.

Task - Test the Application
1. Run the application.
2. The page should be displayed and show text that says Oh my, that was... let me think...!
3. After a few seconds, the text let ne think... should change, and continue changing at variable intervals of a few seconds.

WCD-LAB @HOME 10

You need to develop a Web page for the OniineAptitudeTest Web application. This Web page should allow the administrator of the application to add aptitude questions to the table in the database, as shown in the following figure.
As shown in the preceding figure, each aptitude question has four options. When the user clicks the SUBMIT button, the aptitude question along with its four options should be inserted in the database. How will you develop this Web page?


1. Create a database. OnlineTest. with username, app. and password, app. in the JavaDb database.
2. Create a table. AptitudeQuestions. inside the OnlineTest database using the following query:
CREATE TABLE AptitudeQuestions
(
questionID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY
(START WITH 1, INCREMENT BY 1),
questionStem varchar(1000),
optionl varchar(1000) ,
option2 varchar(1000) ,
option3 varchar(1000) ,
option4 varchar(1000) ,
answer varchar(1000)) ;
3. Open the Glassfish admin console.
4. Create a JDBC connection pool with values as shown in the following table.
Name Value
Pool Name OnlineTestPool
Resource Type javax. sql.DalaSo urce
Database Driver Vendor Derby-30
URL jdbc:derby://localhost:1527/OnlineTest
User app
DatabaseName OnlineTest
Password app
ServerName localhost
PortNumber 1527
Connection Pool Values
5. Create a JDBC resource. jdbc/OnlineTest. and map it to the connection pool. OnlineTestPool.
6. Create a Web application. OnlineTest.
7. Create a JSP page. QuestionPage.jsp. and replace the existing code with the following code:
<%6page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html charset=UTF-8">
<title>Question Page</title>
</head>
<body>
<form action="AddQuestionServlet">
<table>
<tr><td>Question stem</td></tr>
<tr><td colspan="2"><textarea name="qStem" rows="10" cols="50"></textarea></td></tr>
<tr><td><input type="radio" name="options" value="optionl">Optionl</td></tr>
<tr><td><textarea name="textOptionl" rows="4" cols="50"></textarea></td></tr>
<tr><td><input type="radio" name="options" value="option2">Option2</td></tr>
<tr><td><textarea name="textOption2" rows="4" cols="50"></textarea></td></tr>
<tr><td><input type="radio" name="options"
value="option3">Cption3</td></tr>
<tr><td><textarea name="textOption3" rows=n4" cols="50"></textarea></td></tr>
<tr><td><input type="radio" name="options" value="option4">Cption4</td></tr>
<tr><td><textarea name="textOption4" rows=n4" col3="50"></textarea></td></tr>
<tr><td colspan="2" align="center"Xinput type="submit" value="SUBMIT">
</table>
</form>
</body>
</html>
8. Create a JSP page. Success.jsp. and replace the existing code with the following code:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html charset=UTF-8">
<title>Success Page</title>
</head>
<body>
<hl>Question Updated</hl>
<a href="QuestionPage.jsp">Add more questions</a> </body>
</html>
9. Create a servlet. AddQuestionServlet.java. and replace the existing code with the following code:
import ]ava.10.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import j ava.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.naming.Context;
import j avax.naming.InitialContext;
import j avax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import j avax.servlet.annotation.WebServlet;
import j avax.servlet.http.HttpServlet;
import j avax.servlet.http.HttpServletRequest;
import j avax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
SWebServlet(name = "AddQuestionServlet", urlPatterns : {"/AddQuestionServlet"})
public class AddQuestionServlet extends HttpServlet { DataSource ds;
Context context;
Connection con;
Statement st;
ResultSet rs;
PreparedStatement ps;
String insertQuery="Insert into AptitudeQuestions
(questionStem,optionl,option2,option3,option4,answer)values
/ O O O O O O \
/ /
String
qStem,optionl,option2,option3,option4,answer,correctCption; public AddQuestionServlet() {
try {
context = new InitialContext(); if (context == null) {
throw new RuntimeException("JNDI context
not found");
}
ds = (DataSource) context.lookup ("jdbc/OnlineTest");
if (ds == null) {
throw new RuntimeException("Datasource not
found");
}
con = ds.getConnection() ; st = con.createStatement(); ps=con.prepareStatement(insertQuery);
} catch (Exception e) {
System.out.println(e);
}
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8") PrintWriter out = response.getWriter(); try {
qStem=request.getParameter("qStem"); optionl=request. getParameter ("textcjptionl") ; option2=request.getParameter("textOption2"); option3=request.getParameter("textCption3"); option4=request.getParameter("textCption4"); correctCption=request.getParameter("options"); System.out.println(qStem+" "+optionl+" +option2+" "+option3+" "+option4+" "+correctOption); if(correctOption.equals("optionl")){
answer=request.getParameter("textCptionl");
}
else if(correctOption.equals("option2")){
answer=request.getParameter("textOption2");
}
else if(correctOption.equals("option3")){
answer=request.getParameter("textOption3");
}
else if(correctOption.equals("option4")){
answer=request.getParameter("textOption4");
}
else {
System.out.println("No answer is correct");
}
System.out.println(qStem+" "+optionl+" +option2+" "+option3+" "+option4+" "+answer);
ps.setstring(1, qStem); ps.setstring(2, optionl); ps.setstring(3, option2); ps.setstring(4, option3); ps.setstring(5, option4); ps.setstring(6, answer); int i=ps.executeUpdate();
System.out.println(i);
RequestDispatcher
rd=request.getRequestDispatcher("Success.j sp"); rd.forward(request, response); ps.close(); con.close(); context.close();
} catch (Exception e) {
System.out.println(e) ;
} finally {
out.close();
}
}
©Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { processRequest(request, response);
}
©Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { processRequest(request, response);
}
©Override
public String getServletlnfo() {
return "Short description";
}
}
10. Run the QuestionPage.jsp file.

WCD-LAB @HOME 9-Ans 2

Demonstrate a problem that can arise m a concurrency situation. The project simulates a very simple bank accoimt. modeling only the balance.


Task - Witness the Failure

1. Open the project SL3i4m09labi in the d:\labs\student\exercises director}- and nin the project.
2. In your browser, select Deposit and deposit 100. then select Withdraw and withdraw 50 from the account. Satisfy yourself that the project is capable of the essential computation for this simulation.
3. Open a second tab in your browser, and load the base page of the application in that too. It should show the same balance that was left after step two.
4. Without clicking Submit yet m either tab. set one tab up to deposit 100 and the other to withdraw 200.
5. In less than five seconds, click Submit on both tabs. When the pages return, notice that each shows a balance that would have been correct if the other operation had not occurred, but is wrong for the aggregate of both operations.
6. In either of the tabs, deposit a zero amount. Notice that the balance shown is definitely wrong.
Task - Examine the Cause of the Failure

1. Open the domain.Account class in the XetBeans editor wmdow.

2. Observe that m the deposit and withdraw methods, the computation consists of:
a. Read the balance
b. Modify the balance
c. Store the new balance
This logic is correct, however, a delay has been deliberately added after step a. this means that if two threads execute these methods concurrently, each will start with the unmodified balance, and then write it back. In effect, the last one to complete wins. This is called a write-write conflict.

3. Consider how you might fix this problem. Unfortunately, the solution of removing the sleep, and of modifying the code to read this. balance += amount does not solve the problem. It greatly reduces the chance that you will see it. especially m a lab environment with one user testing the code, but it is not a correct solution. The problem remains that the execution of the += operator still involves reading the value, modifying it. and then stormg the result. Although the tune delay between the read and the write is small, it is not zero.
In effect, whenever variable data are shared between threads, this kind of problem might arise. A ftill solution may often be achieved us mg synchronization or database transactions, however, details of these are beyond the scope of the class.

4. Modify the methods deposit and withdraw by marking them synchronised. Do not remove or alter any of the existing code.

5. Rim steps 3 and 4 from Task 1 above again. Notice this time that the simulation takes longer to complete, but the answer is correct.

WCD-LAB @HOME 9-Ans 1

Add a filter to an existing servlet


Task - Examine the Starting Point
1. Open the project SL314m091ab2 in the d:\labs\student\exercises directory and run the project.
2. Select different operations and obsen-e the application's behavior.

Task - Install a Login Mechanism in the Application
1. Add code to the ApplicationController to attempt to read an attribute user from the current session. Set the value found (or null if not found) in an attribute user in the request scope.
2. Modify the quote, jsp and advertize, jsp pages to conditionally welcome the user if the user attribute is not null. Use the core JSTL tag library to provide the conditional behavior for this.
3. Create a new JSP called login, jsp. This should collect a username on a form, and submit this along with the parameter operation set to login to the ApplicationCont roller. You might need to use the following HTML tag to achieve this:
cinput type="hidden" uame="operation" value="Login"/>
4. Add a JSP called welcome, jsp. Tliis should welcome the new user and be the target of the controller's forwarding in the case that the operation is Login.
5. Modify the ApplicationController so that if the operation parameter is login it creates an HttpSession. and embeds the provided user name in that session.
6. Test that the application now addresses a logged-in user by name. You will need to navigate to the login, jsp page manually.
Task - Install a Security Filter in the Application

1. Create a Servlet Filter, called SecurityFilter:
a. Right click the project select Other —* Web — Filter.
b. Enter the name and set the domain to Web.
c. Click Next.
d. Click the New button.
e. For the URL enter /ApplicationController.
f. Check the request box for dispatch option.
g. Click Finish.

2. Edit the template-generated filter:
a. Delete the methods doBeforeProcessing and doAfterProcessing.
b. Delete everything in the doFilter method except for the call to chain.doFilter.
c. Delete the methods getFilterConfig and setFilterConfig.
d. Delete the method tostring.
e. Delete the method sendPrccessingError.
f. Delete the method log.
g. In the init method, delete everything except the Ime that stores the f ilterconf ig parameter m the instance variable of the same name.

3. In the doFilter method, before the call to chain.doFilter. add code to do the
following:
a. Determine what the operation to be performed is (use a request.getParameter("operation") call).
b. If the operation is anything other than Quote, proceed to call chain. doFilter and end processing m this doFilter method.

4. For Quote operations only, proceed as follows:
a. Determine if there is a session associated with this request, and if so. determine if the session contains an attribute called user.
b. If the user attribute exists and is not empty, processmg proceeds with the call to chain. doFilter.
c. If the session does not exist, or if the user attribute does not exist or is empty, processmg proceeds by forwarding through a RequestDispatcher configured to dispatch to the page login, jsp.

5. Rim the program and verify:
a. Any user, regardless of whether the}- are logged m or not. can log m. and can access the advertisement.
b. When an attempt is made to get a Quote, this is success fill only if the user has logged m already. Otherwise, the request results m a redirection to the logm page.

WCD-LAB @HOME 8-Ans 2

You need to enhance the Exotica Web application in such a ray that when the Inquire Nov/ hyperlink is clicked, the Inquire Nov/ Web page gets displayed. Therefore, you need to develop the Inquire Nov/ Web page, as shown in the following figure.
In addition, you need to perform the following validations when the form is submitted:
The values, such as name, address, contact number or email ID. and query, are filled by the user.
If the user has selected the option. Respond via phone, the contact number field must have a value: and if the user has selected the option. Respond via email, the email field must have a value.
If the respond via phone option is selected, you also need to ensure that the date and time is selected.
Further, if the user has submitted the form with appropriate values, the message. Thank you. Our executive will get back to you soon, should be displayed.



1. Open the Web application. ExoticaTravel.
2. Create the JSP page. InquireNowPage.jsp. and replace the cede with the following code:
<%@ taglib prefix="c"
uri="http://java.sun.com/jap/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<c:if test="S(not empty errorMessage)">
<P>
<£ont color="red">Please correct the following errors:
<ul>
<c:forEach var="message" items="${errorMessage}">
<li>${message}</li>
</c:forEach>
</ul>
</font>
</p>
</c:if>
<form action="InquireNowServlet">
<table width="100%">
<tr>
<td width="21%">Name</td>
<td width="79%"><input type="text" name="iName value="${iName}" /></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" value="S{address}"/></td>
</tr>
<tr>
<td>Contact Numfcer</td>
<tdXinput type="text" name="phone" value="${phone}"/></td>
</tr>
<tr>
<td>Email</td>
<tdxinput type="text" name="email" value="${email}" /></td>
</tr>
<tr>
<td>Query</td>
<tdxtextarea name="query" rows="5">${query} </textareaX/td>
</tr>
<tr><td><input type="radio" value="viaPhone" name=,,re3pon3eType" ${re3ponseTypePhone}>Re3pond via phone</td>
<td><input type="radio" name="responseType" value="viaEmail" S{responseTypeEmail}>Respond via email</td>
<tr><td colspan="7"> If you opt to respond via phone, specify the date and time you want our executive to contact you</td>
<tr><td>Date
<select name="day">
<option
value="3elect">3elect</option>
<c:forEach begin="l" end="31" var="day"> <option value="S{day}">${day}
</option>
</c:forEach>
</select>
<select name="month">
<option
value="select">select</option>
<c: forTokene
iteme="2011,2012,2013,2014,2015,2016,2017,2018,2019,2020" delims="," var="year">
</option> <option value="${ year} ">${ year} </c: f orTokens» </select>
</td> <td>Time <select name=wtime"> <option
value="3elect">3elect</option>
<c:£orTokens items="between 6-7 am,between 7-8 am,between 8-9 am,between 9-10 am,between 10-11 am,between 11-12 am,between 12-1 pm, between 1-2 pm, between 2-3 pm,between 3-4 pm, between 4-5 pm, between 5-6 pm, between 6-7 pm, between 7-8 pm" delims=w," var="time">
</option> <option value="${time}">${time} </c: forTokens» </select>
</td>
<trXtdXinput type="submi t" value="Submit"x/td></tr>
</table>
</form>
</body>
</html>
3. Create a servlet. InquireNowServletjava. and replace the existing code with the following code:
import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
SWebServlet(name - "InquireNowServlet", urlPatterns —
{"/InquireNowServlet"})
public class InquireNowServlet extends HttpServlet {
String iName, address, phone, email, responseType, query, responseTypePhoneVal = "unchecked",
responseTypeEmailVal — "unchecked", day, month, year, time; ArrayList errorMessage = new ArrayList();
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter();
try {
errorMessage.clear();
address = request.getParameter("address"); query = request.getParameter("query"); phone = request.getParameter("phone"); email = request.getParameter("email"); responseType = request.getParameter ("responseType");
day = request.getParameter("day"); month = request.getParameter("month"); year = request.getParameter("year"); time = request.getParameter("time");
if (errorMessage.isEmpty()) {
iNarae = request.getParameter("iNamc");
if (iName.equals("")) {
errorMessage.add("Please enter your
name");
}
if (query.equals("")) {
errorMessage.add("Please specify your
query");
)
if (phone.equals("") && email-equals("")) { errorMessage.add("Please enter the contact number or email ID");
>
if(!phone.equals("")){
if (!(phone.matches("-?\\d+(\\.\\d
+)?"))> {
errorMessage.add("Please enter a
valid contact number");
>
)
if (responseType == null) {
errorMessage.add("Please select the
response type");
} else {
if(responseType.equals("viaPhone")){ if(phone.equals("")){
errorMessage.add("Please enter
the contact number");
responseTypePhoneVal =
"checked";
responseTypeEmailVal =
"unchecked";
}
else{
\.\\d+)?")>) {
if (!(phone.matches("-?\\d+(\
responseTypePhoneVal =
"checked";
responseTypeEroailVal =
"unchecked";
}
else {
responseTypePhoneVal =
"checked";
responseTypcEmailVal =
"unchecked";
if (day.equals("select") ||
month.equals("select") || year.equals("select") || time.equals("select")) {
errorMessage.add
("Please select the date and time");
}
}
}
}
else { if
your your email ID");
"checked";
"unchecked";
}
}
(email.equals("") ) { errorMessage.add("Please enter
responseTypeEmailVal =
responseTypePhoneVal =
}
}
if (! errorMessage. isEmptyO ) {
request.setAttribute("iName", iName); request.setAttribute("address",
address);
request.setAttribute (••query", query) ; request.setAttribute("phone", phone); request.setAttribute("email", email); request.setAttribute
("responseTypePhone", responseTypePhoneVal);
request.setAttribute
("responseTypeEmail", responseTypeEmailVal);
request -setAttribute("errorMessage",
errorMessage);
RequestDispatcher rd =
request.getRequcstDispetcher("InquireNowPage.jsp");
rd.forward(request, response);
> (
System.out.println ("InquireNowDisplayPagc.jsp");
RequestDispatcher rd =
request.getRequestDispatcher("InquireNowDisplayPage.j sp");
rd.forward(request, response);
}
}
catch (Exception e) {
System.out.println(e);
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
+
* 0param request servlet request
* 8param response servlet response
* 8throws ServletException if a servlet-specific error occurs
* ©throws IOException if an I/O error occurs */
©Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* 8poram request servlet request
* 0param response servlet response
* ©throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs */
QOverride
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { processRequest(request, response);
/**
* Returns a short description of the servlet.
*
* 0return a String containing servlet description */
0Override
public String getServletlnfo() { return "Short description";
}// </editor-£old>
}
4. Open the LinksPage.jsp page and replace the following statement:
<tr><td><a href="PageUnderConstruction.jsp" target="middle">Inquire Now</aXbrX/tdX/tr>
with the following statement:
<trXtdXa href="InquireNowPage .jsp" target="middle">Inquire Now</a><brX/tdX/tr>
5. Run the HomePage.jsp file.

WCD-LAB @HOME 8-Ans 1

Investigate the use of core JSTL tags.



Task - Investigate the c:out Core Tag
1. Create a new Java Web project, called SL3l4m08labl.
2. Into the index, jsp file, add a taglib directive for the core JSTL library. Refer to the "JSTL Functional Areas" section in Module S of the student guide for details of the prefix and URI that are expected for this.
3. Create a paragraph in your JSP that contains the following literal text:
<script type='text/javascript'> alert('How annoying');
</script>
<hl this is not a heading
X > Y... is that true & is the other true too?
4. Ignore the errors for now and run the application. Notice how the text is interpreted. Some of it disappears, and some behaves strangely.
5. Surround each of these lines with a <c:out> tag. Consult the "JSTL out Tag" section in Module S of the student guide for a reminder of the syntax.
6. Run the application again and observe the behavior.
a. Right-click the web page and choose View Source.
b. Notice that the default value of escapeXml is true, and the markup symbols have been converted to character entities. You will see in Module 12 that this can be a valuable tool in protecting against crosssite scripting attacks.
Task - Investigate the c: remove Core Tag
1. Open the project SL314m081ab2 in the d:\labs\student\exercises directory. Examine the Address JavaBean (this is the same one you have seen before).
2. Into the index, jsp file, add a jsp:useBean directive to create an instance of the Address bean in the session scope.
3. Add a jsp:setProperty tag to set a literal value of 1234 Acacia Gardens for the property addressl of the bean.
4. Add a jsp:getProperty tag to output the value of the addressl property (to prove that it is present and assigned).
5. Run the application to demonstrate that the bean has been created and the value assigned.
6. Add the taglib directive to allow the use of the core tag library.
7. After the value of the property has been printed out. add a c: remove tag to remove the bean, then repeat the code you used to output the value further up the file.
S. Run the application and demonstrate that the bean was removed, and therefore the attempt to output the value of the address field fails.

WCD-LAB @HOME 7-Ans 2

Use the jsp:useBean. setProperty. and getProperty tags.


Preparation
No preparation is needed for this exercise.

Task - Investigate the jsp:useBean Tag
1. Open the project called SL314m071ab2 in the d:\labs\student\exercises directory.
2. Examine the index, jsp page. This contains a form that triggers the setAddress. jsp page and submits five parameters to that page.
3. Examine the class domain.Address. This is a simple JavaBean that holds address information. Notice that the field names declared in the form and the attribute names of the Java Bean are similar but not identical.
4. Create a new JSP. called setAddress. jsp.
5. Add code to the setAddress. jsp to use the <jsp: useBean> tag to create a JavaBean.
6. In the seLA.ddress.jsp add code using the <jsp: setProperty> tag to populate all the fields of the addressBean directly from the input properties. If you are in doubt, refer to the section under the heading "The setProperty Tag" section in Module 7 of the student guide.
7. Add an unordered list, and in it. print out each element of the bean using the <jsp:getProperty> tag.
S. Create a second unordered list, and in it. print out each element of the bean using scriptlet code. Recall from "The useBean Tag" section in Module 7 of the student guide that the <jsp: use Bean > tag creates a variable in the generated sen-let code. That variable has the name provided in the id element of the <jsp:useBean> tag.
9. Test your application and determine that the data are transferred from the form into the bean and are then displayed by the set Address, jsp page.

Task - Retrieve Session Information Using JSP Tags
1. Create a new page called showAddress .jsp.
2. Using elements of the showAddress. jsp page for assistance, create a standalone page that shows the current values of a bean called addressBean that is in the session scope. Note that this page will be loaded by typing its URL directly. The goal is to demonstrate that the bean created in the previous task is still accessible because it is in the session scope.
3. Test the page to show the values from the previous form submission.

WCD-LAB @HOME 7-Ans 1

Investigate using EL to access complex data structures.


Preparation
No preparation is needed for this exercise.

Task
1. Open the project named SL314m061ab2 in the d:\labs\student\exercises directory and look at the classes domain.Customer and domain.Address.
2. Examine the launch page index, jsp. and the servet class web.Controller, to determine the basic structure of the application. Note that the application is missing the view CustomerView. jsp to which the controller servlet forwards.
3. Create the view class Customerinfo. jsp. Arrange that it displays the name and three addresses of the customer.
4. Test your application for the customer with the ID 1 (only one exists).
5. There are two distinct ways (syntactically) that you can access the three customer addresses-using arrays or using the three distinct fields. Whichever you used in step 3. modify your view to use the other approach, and retest your application.

WCD-LAB @HOME 2-Ans 2

HTTP headers that are sent by your browser.


Preparation
No preparation is needed for this exercise.

Task • Create index, jsp and a View JSP

In this project, the MVC model will be simplified a little. The intention is that you will create a sen'let to act as controller and a JSP to act as view, but will use a String object to carry the result data directly from the sen-let to the JSP.
1. Create a new project called SL3l4m4ii.
2. Edit the automatically created index.jsp file so that it carries a single link that will lead to a relative URL. /ListHeaders. You may use an HTML anchor to do this, or if you're feeling ambitious, a submit button on an othenvise empty form.
3. Add a new JSP to the project, call this file HeadersView. jsp.
4. Add to the view introductory text such as These are the headers of your browser .
5. Add an EL expression that will output the value of a text element in the request scope called headerList.

Task • Create the Controller Servlet

1. Add a sen-let to the project. Make the fully qualified name of the sen-let sl314.m4.HeaderServlet.
2. Set the URL pattern for the sen-let to ListHeaders.
3. In the sen-let. declare a StringBuilder called result. Set the value of the result to <UL>\n .
4. Obtain the enumeration of header names from the request object.

5. For each entry in the enumeration:
a. Append <LI> to result.
b. Append the header name to result.
c. Append = to result.
d. Extract the value of the header from the request and append that value to result.
e. Append </LI>\n to the result.
6. Append </UL>\nto result.
7. Add an attribute to the request called headerList and set the value to result.
8. Forward to HeadersView.jsp.
9. Finally, run the example and verify that you see headers such as host, user-agent. accept and others.

WCD-LAB @HOME 2-Ans 1

Create an MVC-based web application. The application will allow the user to determine the material traditionally associated with a given wedding anniversary.

Task - Design a JavaBeans Compliant Model

1. Consider the attributes needed to model the wedding anniversary problem. One writable attribute will be needed to represent the year number of the anniversary. Another, read-only, attribute will be needed to allow the view to present the name of the associated material.
2. Decide what you will call these attributes, and write them in the first column
3. Decide what the necessary corresponding methods will be to support those attributes in the JavaBeans naming conventions. Write those methods. Note that because one attribute is read-only, you will require a total of three methods, so one table cell will remain blank.
4. Decide what key name you will use to store the model in the request when it is forwarded. Write that down here:
5. Decide on the name of your model class, package name, and what, if any. base class it should extend. Write those down here:

Task
Implement the Model
1. In NetBeans. create a new web application project called SL3l4m03labl. This will also be the context root for the application.
2. Create a new class for the model and provide get and set methods as you specified.
3. In the file anniversaries.txt. you will find lists of anniversary material names with the year to which they apply. These data are provided in a form intended to simplify incorporating into a Java class. Use this form if it suits you or simply extract the raw data if you prefer to use that in creating your model. The file can be found under the Files tab (just to the right of the Projects tab in NetBeans) at the root directory of the solution for this lab.
4. (Optional) Create a trivial main method in your model to test the basic functioning of the methods.

Task • Create an HTML Form to Submit the Request
1. You will need a regular HTML form to allow the user of your application to enter the anniversary year they are interested in. When you created the project. NetBeans created an index, jsp file. Delete this file and create a new HTML page called index.html instead.
2. In the index.html file, you will create a form that prompts for a number of years. Decide what you will call the parameter when it is submitted to the web application. Write this parameter name.
3. The form will invoke an action, which will be the controller servlet that you will create shortly. Decide what the context root of this application will be. and the URL that will invoke the controller. Write these too in the Table 3-4 below.
4. Create the form in the index.html file.

Task • Create a View Component Using a JSP
1. Decide what you will call your view JSP. Write this down here:
2. Create the JSP for the view. It must present the year and anniversary material name returned by the model. Recall the name of the model as in Table 3-2 above. This will be needed along with the attribute names from Table 3-1 above to construct the EL expressions.

Task • Create the Controller
1. The final step in constructing this application is to create a controller to tie it all together. Create an HttpServlet. and ensure that it responds to the URL that you selected in Table 3-4 above.
2. Modify the processRequest method so that it:
a. Extracts the year parameter named
b. Creates an instance of the model.
c. Sets the year value in the model (consider the data type-is this a String or an int? If you convert, do not try to help the user but simply swallow any exceptions and produce a clean output. Error handling is a topic of later modules.)
d. Stores the model in the request scope using the name
e. Forwards to the view, named

Task - Run the Application

1. Right-click the project and run it.
2. Your browser should be launched automatically, and should show the input form. Enter a number of years, and press the submit button.
3. You should see appropriate output in the subsequent browser page.

Core Java Subjective Question

1.Identify the features of New API (NIO).
Ans:
i)The new API works more consistently across platforms.
ii)It makes it easier to write programs that gracefully handle the failure of file system operations.
iii)It provides more efficient access to a larger set of file attributes.

2.Differentiate between checked and unchecked exceptions.
Ans:
Checked Exception:
i)Every class that is a subclass of Exception except RuntimeException and its subclasses falls into the category of checked exceptions.
ii)You must ?handle or declare? these exceptions with a try or throws statement.

Unchecked Exception:
i)java.lang.RuntimeException and java.lang.Error and their subclasses are categorized as unchecked exceptions.
ii)You may use a try-catch statement to help discover the source of these exceptions, but when an application is ready for production use, there should be little code remaining that deals with RuntimeException and its subclasses.

3.Explain public, static, and void keywords in the following statement:
public static void main(String args[])
Ans:
i)public: The public keyword indicates that the method can be accessed from anyobject in a Java program.
ii)static: The static keyword is used with the main() method that associates the method with its class. You need not create an object of the class to call the main() method.
iii)void: The void keyword signifies that the main() method returns no value.

4.Identify the limitations of the java.io.File class.
Ans:
The java.io.File class has the following limitations:
i)Many methods did not throw exceptions when they failed, so it was impossible to obtain useful error messages.
ii)Several operations were missing (file copy, move, and so on).
iii)The rename method did not work consistently across platforms.
iv)There was no real support for symbolic links.
v)More support for metadata was desired, such as file permissions, file owner, and other security attributes.
vi)Accessing file metadata was inefficient?every call for metadata resulted in a system call, which made the operations very inefficient.
vii)Many of the File methods did not scale. Requesting a large directory listing on a server could result in a hang.
viii)It was not possible to write reliable code that could recursively walk a file tree and respond appropriately if there were circular symbolic links.

5.Identify the five classes of the java.util.concurrent package and explain any two classes.
Ans:
i)Semaphore: Is a classic concurrency tool.
ii)CountDownLatch: A very simple yet very common utility for blocking until a given number of signals, events, or conditions hold.
iii)CyclicBarrier: A resettable multiway synchronization point useful in some styles of parallel programming.
iv)Phaser: Provides a more flexible form of barrier that may be used to control phased computation among multiple threads.
v)Exchanger: Allows two threads to exchange objects at a rendezvous point, and is useful in several pipeline designs.

6.Steve has been asked to automate the Library Management System either in C++ or Java. Steve has chosen to develop the project in Java. Identify the reason.
Ans:
One of the major problem areas in most of the object-oriented languages, such as C++, is to handle memory allocation. Programmers need to explicitly handle memory in the program for its optimum utilization. To handle memory allocation, they use pointers that enable a program to refer to memory location of the computer. However, Java does not support pointers and consists of the built-in functionality to manage memory.

7.You have created a class with two instance variables.You need to initialize the variables automatically when a class is initialized. Identify the method that you will use you to achieve this. In addition, describe the characteristics of this method.
Ans:
You can initialize the variable by using the constructor. The characteristics of a constructor are:
-       A constructor has the same name as the class itself.
-       There is no return type for a constructor. A constructor returns the instance of the class instead of a value.
-        A constructor is used to assign values to the data members of each objectcreated from a class

8.Differentiate between interface and abstract class.
Ans:
1.The methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behavior.
2.Variables declared in a Java interface are by default final. An abstract class may contain non-final variables.
3.Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc..
4.Java interface should be implemented using keyword, implements; A Java abstract class should be extended using keyword, extends.
5.An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.
6.A Java class can implement multiple interfaces but it can extend only one abstract class.
7.Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
8.In comparison with Java abstract classes, Java interfaces are slow as it requires extra indirection.


WCD-LAB @HOME 6-Ans 2

Invertigate the compilation of JSPs to servlets


                       INVESTIGATE THE COMPILATION OF JSPsto servlets
1.Create a new java Webproject.
 2.Add a little body text tothe JSP.
3.Run the project.
4.Right click the JSP and select View Servlet from the pop-up menu.
5.Examine the contents of thr servlet , and notice how it corresponds to ypur
   original JSP.
6.Make.the following changes to your JSP,and each change ,re-run the
  project,thenexamine the servlet source again.
      a.Add apage initalize declaration for a private int variable.
       b.Add apage dirctive to import java.util.*.
       c.Add an expression to output the result of doubling the private int
              variable you added in stepa above.
     d.Add code to iterate overthe number 1 to 10, prinating a message as a part
        of an unnumberd list each time tround.Be sure to explicit
        curly braces for the loop boudaries.
   e. Edit thenow?Exmine the generated servlet and determine what
      Went Wrong.

      Retrive sessionin information using jsp tags
1.Create a new page called shoe ADDRESS.JSP
2.Using elements of the show Address.jsp page for assistance,create a standalone
   page that shows the currrent values ofa bean called addressBean thst is in the
 session scope.Note that this page will be loaded by typing its URLd directly
  accessiable because it is in the session scope.
3.test the page to show the values from the previous from submission.

WCD-LAB @HOME 6-Ans 1

1. Investigate EL implicit objects and the JSTL forlach tag.

                       INVESTIGATE EL Implicit opjrctand the JSTL for Each tag.
1.Create a new java web project project named
2.In the resulting index.jsp page , change the titke and heading to HTTP Headers.
3.Create a taglib directive to make the core JSTL taga available with a
   prefix of c.Consult the"Tag Example"section of Module 6 student guide if
    you need a reminder of the syntax for this.
4.prepare anunumbered listin the body of the document.
5.Inside the unnumber list tags,place a :for Each tag that will enumerate the
   elements of thr HTTP headers arry.Consult"El Implicit Object"in Module
   6in the student guide if you need help in findingthe header arry.
6.Test the program.

WCD-LAB @HOME 5-Ans 2

2. In the ExoticaTravels Web application, if any changes are made to the list of hotel and cab servicers name, the application code needs to be updated to reflect these changes. Therefore, you need to enhance the functionality of the ExoticaTravels Web application such that any changes made to the hotel and cab servicers list does not affect the application.


Note: To perform this exercise, you need to use the solution created in Exercise 01 of Chapter 04.



import java.io.IOException;
impot\rtjava.io.PrintWriter;
impot javax.Servlet.ServletException;
import javax.Servlet.annotation.WebServlet;
import javax,Servler.http.HttpServlet;
import javax.servlet.http.HttpServleltRequest;
import javax.Servlet.http.HttpServletResponse;
import javax.Servlet.http.HttpSession;

 public class HotelBookingServelt extends HttpServelt
    {
       protected void ProcessRequest(HttpServletRequest
request ,HttpServeltResponse response)
            throw ServletException.IOException
            {
   response .setContentTypes("text/html;charset=UTF-8");
   printWriter out = response.getWriter();
   HttpSession session=request.getSession();
   string hotelNames=this.getInitParameter
("HotelNames");
                      String hotelNameSplit[]=hotelName.split(" , ");
      try
                  {
                      String destination=request.getParameter
  ("destionation");
                          session.setAttribute("destination",
   destination);
                     out.println("<title>Tour package Booking
page</title>");
 out.println("<div align=right'>);
                    out.println("<a
href='LogoutServlet'>Logout</a>");
                   out.println("</div");
                    out.println("<tabel>");
                   out.println("<from
action='CabBookingServlet'>");
                out.println("<tr><td><h3>Tour package
 Booking</h3></td></tr>");
                     out.println("<tr><td>Select ahotel</td>");
                     out.println("<td><select name='hotel'>");
                     for(int i=0;<hotelNameSplit.length;i++)
                     out.println("option value=' "+hotelNameSplit
[i]+" '>"+hotelNameSplit[i]+"</option");
                 
                     out.println</select></h1></td>");
                     out.println("<tr><td>Number of days</td>");
name='noofdays'></td></tr>");
                      out.println("<tr><td><input types='submit'
value='next'></td>");
               out.println("</form>");
               out.println("<from
action='Tourpackagepage.jsp'>");
                       out.println("<td><input type='submit'
value='back'></td></tr>");
                  out.println("</form>");
                   out.println("<?table>");
                }
                      finally
                                 {
                                           out.close();
                    }
    }
@Override
   protected void goGet(HttpServletRequest request,
httpServletResponse response)
       throws ServletException.IOException
         {
     processRequest(request.response);
   }
@override
    protected void doPost(HttpServletRequest request,
HttpServletResponse response)
                  throw ServletException, IOException
        {
              processRequesr(request ,response);
                   }

   @override
   public String getServletInfo()
      {
         return"short description";
       }  
}