Advanced Java Programming Unit 4-6 (JV5BC-07 V1.2) Instructor Guide
Advanced Java Programming Unit 4-6 (JV5BC-07 V1.2) Instructor Guide
Instructors Guide
JV5BC-07 V1.2
Java 5 Instructor Guide
JV5BC-07
Version 1.2
UNIT 4 7
4.1 Answers to exercises 7
4.2 Answers to revision questions 27
4.3 Solution to compulsory exercise 29
4.4 Answers to test your knowledge 31
UNIT 5 37
5.1 Answers to exercises 37
5.2 Answers to revision questions 61
5.3 Solution to compulsory exercise 63
5.4 Answers to test your knowledge 72
UNIT 6 75
6.1 Answers to exercises 75
6.2 Answers to revision questions 96
6.3 Answers to test your knowledge 97
Introduction Page 1
Introduction
Unit description
This unit builds on the Java Part 1 course. Learners will be introduced to two Java Enterprise
Edition technologies, namely: JavaServer pages and Web Services. Learners will also learn how
to create mobile applications for use on wireless devices such as cell phones, PDAs, etc.
In the first part of the course learners will combine a wide variety of Web-related technologies to
develop dynamic Web-based applications, using Java Servlets, JavaBeans, and JavaServer Pages.
Learners will learn all the basic techniques and elements used in JSPs, and will also learn how to
write their own JSP custom tags, and how to display records from databases to JSPs.
There has been a big move away from applications that run off one computer, with all the
components and resources on that one computer, to a distributed application environment.
With the boom of connections to the Internet these applications do not have to be local to your
network. The learner will be introduced to Web Services. The second part will guide the learner
towards creating Web Services by using technologies such as JAX-RPC, JAXP, and SOAP.
This final part will focus on using the Java Micro Edition (J2ME) to build applications for use on
wireless devices. The learner will learn how to build graphical wireless applications, implement
input and output operations, and how to enable wireless devices to access remote resources
(such as the Internet). The learner will also be introduced to animation and gaming on wireless
devices.
Content
Servlets: Introduction to Java Servlets, a comparison between Servlets and JSPs and HTTP
actions.
Programming JSP Scripts: JSP tags, JSP directives, Scripting elements, comments, JavaServer
pages and inheritance.
Custom Tag Libraries: introduction to custom tags, a comparison between custom tags and
JavaBeans, custom tag basics, directory structures, creating a simple custom tag and
components used in custom tags.
J2ME framework: Introduction to J2ME, overview of the Connected Limited Device Configuration
(CDLC) APIs, introduction to the Mobile Information Device Profile (MIDP), java applications and
MIDlets and structure of MIDlets.
J2ME wireless toolkit: Overview of the wireless toolkit, verifying a MIDlet using the bytecode
verifier and emulator, creating J2ME MIDlets using the command line, using the KToolBar and
using custom device profiles.
Building graphical MIDlets: Create Graphical User Interfaces and graphics. Using the Display
object. Differences between display displayable screen and canvas, displaying alert messages,
displaying forms, lists and textboxes, GUI components, using commands and using graphics.
Optimisation Input/Output and Record Management System (RMS): The need for optimisation,
maintainability, installing the Apache web server on Windows and Linux, Input and Output,
using the Record Management System, how to open a record store, adding, retrieving, deleting
and stepping through records.
Assessment for pass – A pass is awarded for the unit on the achievement of all the pass
assessment criteria.
Delivery
A prescribed studyguide is provided which leads learners sequentially through the items shown
in the Content section of this unit. Examples are embedded within the studyguide at
appropriate stages. Revision and compulsory exercises are also included at the end of each
section and these should be completed before moving on to the next study section.
Opportunities to discuss and reflect upon the course material should be given to assist learners
in improving their practical skills and gaining a fuller understanding of the principles and
concepts presented by this unit.
Assessment
Assessment opportunities for this unit are introduced to learners, at regular intervals, as they
progress through the associated Studyguide which leads them through a prescribed study
program.
Outcomes are assessed through individual exercises, exams, practical tasks, project work, and
computer based assessment. Details of the links between the unit assessment criteria and CTI
assessment instruments are shown on the Learner Achievement Record.
Evidence for specific criteria should be available as printed copies of learners work resulting from
Studyguide exercises/exams or Observation Records for practical activities (i.e. practical tasks,
laboratory sessions and project work). Supplementary materials should be attached to
Observation Records (e.g. copies of screenshots etc.) to support the award of criteria by
assessors/instructors.
Evidence for some Merit and Distinction criteria may require additional reports or presentations
to confirm targeted criteria (e.g. evaluation reports or Power Point presentations).
Links
NOTE This unit has been developed under the BTECi customised framework for the following
BTEC Higher National Diplomas:
Resources
Hardware
800 MHz Intel Pentium III Processor (or equivalent ) and later
Installed operating system
256 MB RAM
1024 x 768, 16 bit display
1GB available disk space
Software
Java Integrated Development Environment (IDE) and compiler
Textbooks
Prescribed reading
Study guide for Java part 1
Van der Linden, Peter. Just Java 2. 6th Edition. Prentice Hall. (ISBN 0-13-148211-4).
Suggested reading
Eckel, Bruce. Thinking in Java. 4th Edition. Prentice Hall. (ISBN 0-13-187248-6).
(This book is highly recommended and it can be downloaded for free from
www.mindview.net.)
Cadenhead, Rogers and Lemay, Laura. SAMS Teach Yourself Java 2 in 21 Days. 4th Edition.
SAMS Publishing. (ISBN 0-672-32628-0).
Sierra, Kathy and Bates, Bert. SCJP Sun Certified Programmer for Java 5 Study Guide (Exam
310-055). McGraw-Hill/Osborne. (ISBN 0-07-225360-6).
Keegan, Patrick, Champenois, Ludovic, Crawley, Gregory, Hunt, Charlie, and Webster,
Christopher. NetBeans IDE Field Guide. 2nd Edition. Prentice Hall. (ISBN 0-13-239552-5).
Unit 4
The following are a few differences between JSP and Servlet programming (mark using your
own discretion).
A. Servlets are used where a lot of dynamic content is generated, whereas JSPs are used
where little dynamic content is generated.
B. JSPs are intended for creating Web pages that require little Java coding and can
therefore be used by Web page designers, whereas servlets are intended for experienced
Java programmers who write a lot of lines of code to produce Web content.
C. JSPs are compiled into servlets by the container, whereas servlets are compiled by the
developer.
D. JSPs have pre-instantiated implicit objects such as the session object, whereas when
working with servlets, these objects need to be instantiated by the programmer.
E. Servlets do not have directives such as <%@ page.. %> like JSPs do.
F. JSPs are basically HTML/XML etc. files with embedded Java code, whereas servlets are
Java code blocks with embedded HTML/XML etc.
2. Write a simple servlet that will display the current date, centred horizontally on the Web
page. The date must be displayed in the following format: “1 January, 2003”.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.text.*;
import java.util.*;
/*
* DateServlet. Displays today’s date to the requesting
* browser in the following format 1 January, 2003 in the
* centre of the screen
*/
public class DateServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String dateFormat = "dd MMMM, yyyy";
SimpleDateFormat sdf = new
SimpleDateFormat(dateFormat);
Date todaysDate = new Date();
/* output configuration */
PrintWriter out = response.getWriter();
response.setContentType("text/html");
<center>
<%
SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM,
yyyy");
Date d = new Date();
out.println(sdf.format(d));
%>
</center>
</body>
</html>
Example 4.2 – DateServlet.jsp
In the JSP, print a greeting to you, the programmer, whose name is stored in a string, as
well as a line of information that is added using the info attribute of the page directive.
Declare a method that calculates the area of a circle. For the number passed as a
parameter, calculate the square root and the area of a circle with the radius equal to the
number.
<HTML>
<HEAD>
<TITLE>Get number</TITLE>
</HEAD>
<BODY>
<FORM ACTION= "NumberFun.jsp">
<HTML>
<HEAD>
<TITLE>Number Fun</TITLE>
</HEAD>
<BODY>
<%! String name = new String("The programmer");
int number;
Random r = new Random();
/* The area() method calculates the area of a circle with
radius passes as an argument */
<%
number = Integer.parseInt(
request.getParameter("num"));
out.println("Number is " + number);
out.println("<BR> The square root of the number is:" +
Math.sqrt(number));
out.println("<BR> The radius of the circle is: " +
area(number));
number = (int)(r.nextDouble() * 10);
%>
</BODY>
</HTML>
Example 4.4 – NumberFun.jsp
You will notice that this solution has used both a scriptlet and a combination of HTML and an
expression to display information to the screen. It is important for the students to understand
that both these methods are valid within a scriptlet. The output is the same, i.e.:
could be replaced by
2. Write a JSP which creates a table. Use a for loop to create each row. The first column in the
table holds numbers from 1 to 10, the second column displays a list of shopping items, and
the third column displays the price of the items. All the values must be stored in separate
arrays respectively. The last row of the table must display the total price of all the items.
<BODY>
<%! String list[] = {"Coffee", "Sugar", "Milk",
"Bread","Fruit Juice" , "Tea", "Butter",
"Jam", "Peanut butter", "Cheese"};
double prices[] = {2.50,5.36,1.10,2.36,4.60,3.33,5.90,
4.36,2.00, 6.66};
%>
<TABLE>
<TR>
<TH>x</TH><TH>Shopping list</TH><TH>Price</TH>
</TR>
<%
double total = 0;
for (int x = 0; x < 10; x++) { %>
<TR>
<TD><%= x %> </TD><TD><%= list[x] %></TD><TD>
<%= prices[x]%> </TD>
</TR>
<%
total += prices[x];
}
%>
<TR colspan="3">
<TD><B>Total </B><%= total %></TD>
</TR>
</TABLE>
</BODY>
</HTML>
Example 4.5 – NumberTable.jsp
<HTML>
<BODY>
<HR/>
<H3>@copy; CTI Education Group</H3>
</BODY>
</HTML>
Example 4.6 – Footer.jsp
2. Create another JSP which makes use of a cookie which displays the last date the page was
accessed. Include Footer.jsp in this page.
<HTML>
<BODY BGCOLOR="lightgreen">
<%
String cookieName = "DateCookie";
</BODY>
</HTML>
Example 4.7 – Cookie.jsp
3. If the cookie’s date and the current date are the same, forward the user to another JSP which
informs the user that he or she has already accessed the site today (remember, the cookie’s
value must be set each time the site is accessed).
<HTML>
<BODY text="white" bgcolor="black">
<H3>You have already been here today</H3>
</BODY>
</HTML>
Example 4.8 – BeenHere.jsp
The JavaBean for Exercise 1 should look similar to the example below:
package unit4;
import java.io.*;
A simple HTML form will input the value in inches, as in the example below:
<HTML>
<HEAD>
<TITLE>Enter value in inches</TITLE>
</HEAD>
<BODY>
<FORM ACTION="MyFirstJSP.jsp">
<H1>Input value in inches</H1>
<INPUT TYPE="text" name="inches" value="0"><BR>
<INPUT TYPE="submit" value="Convert to Centimeters">
</FORM>
</BODY>
</HTML>
Example 4.10 – MyFirstHTML.html
<HTML>
<HEAD>
<TITLE>Converts Inches to Centimeters</TITLE>
</HEAD>
<BODY>
<jsp:useBean id="convert" class="unit4.MyBean" />
<jsp:setProperty name="convert" property="inches"
param="inches" />
<H1>Value in centimeters is:</H1>
<jsp:getProperty name="convert" property="centimeters" />
</BODY>
</HTML>
Example 4.11 - MyFirstJSP.jsp
Should either display a welcome message such as “Hello Jill” or the message “I don’t
know you”.
Provide an HTML page with a form to enter the initial name. Draw a property sheet for the
bean.
package unit4;
import java.io.*;
public MySecondBean () {
isValidUser = false;
names = new String[5];
names[0] = "Jack";
names[1] = "John";
names[2] = "Jill";
names[3] = "James";
names[4] = "Jennifer";
}
<HTML>
<HEAD>
<TITLE>Enter your name</TITLE>
</HEAD>
<BODY>
<FORM ACTION="MySecondJSP.jsp">
<H1>Input your name</H1>
<INPUT TYPE="text" name="userName" value=""><BR>
<INPUT TYPE="submit" value="Submit Name">
</FORM>
</BODY>
</HTML>
Example 4.13 – MySecondHTML.html
<HTML>
<HEAD>
<TITLE>Checks User Name</TITLE>
</HEAD>
<BODY>
<%
Unit4.MySecondBean checker = new unit4.MySecondBean();
checker.setUserName(request.getParameter("userName"));
if (checker.getIsValidUser()) {
out.println("Welcome back " +
request.getParameter("userName"));
} else {
out.println("I do not know you");
}
%>
</BODY>
</HTML>
Example 4.14 - MySecondJSP.jsp
3. Study the property sheet below. Write a JSP (on paper), using tags, that will use all the
bean’s get() and set() methods.
<HTML>
<HEAD>
<TITLE>Exercise 3</TITLE>
</HEAD>
<BODY>
<jsp:useBean id="add" class="unit5.AddBean" />
<jsp:setProperty name="add" property="firstNumber"
value="5" />
<jsp:setProperty name="add" property="secondNumber"
value="10" />
<jsp:getProperty name="add" property="sum" />
<jsp:getProperty name="add" property="dateString" />
</BODY>
</HTML>
Example 4.15 – Propertysheet.jsp
4. Create a JSP that will utilize the Bakery database. The user should be able to enter just the
name of the product he or she is trying to find. The parameters of the HTML form must be
sent to the JSP, which must, in turn, search the database for a match (hint: Search the
description column of the Products table). Ensure that the user can type in a partial item
description, such as Loaf, which returns all items with “loaf” in the description.
<HTML>
<HEAD>
<TITLE>Bakery Query Form</TITLE>
</HEAD>
<BODY BGCOLOR="pink">
<CENTER>
<H1>Bakery</H1>
</CENTER>
<CENTER>
<!-- basic form used to retrieve a SQL select
statement and submit it to an action page -->
<FORM action="PartialQueryResult.jsp">
<FONT color="white">Enter product name:</FONT>
<INPUT type="text" name="sql">
<INPUT type="submit" value="Search">
</FORM>
</CENTER>
</BODY>
</HTML>
Example 4.16 - BakeryQuery.html
<HTML>
<HEAD>
<TITLE>SQL Results Table</TITLE>
</HEAD>
<BODY BGCOLOR="pink">
<CENTER>
<H1>Results of query</H1>
</CENTER>
<%
/* get the text typed in the textbox on the previous page */
String sql = request.getParameter("sql");
Statement statement;
ResultSet result;
try {
statement = connection.getConnection().
createStatement();
result = statement.executeQuery("SELECT * FROM
products WHERE
description LIKE
'%" + sql + "%'");
%>
<CENTER>
<TABLE border="1" bgcolor="white">
<TR>
<TD>
<B>ID</B>
</TD>
<TD>
<B>Description</B>
</TD>
<TD>
<B>Price</B>
</TD>
</TR>
<%
<% }
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>mt</shortname>
<info>
Mixed Example Tags
for CTI JSP course
</info>
<tag>
<name>first</name>
<tagclass>bakery.mt.BakeryTag</tagclass>
<bodycontent>EMPTY</bodycontent>
</tag>
<tag>
<name>changeFont</name>
<tagclass>unit4.mt.ChangeFontTag</tagclass>
<bodycontent>JSP</bodycontent>
</tag>
</taglib>
Example 4.18 – TagLib.tld
package unit4.mt;
import javax.servlet.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
try{
JspWriter out = pageContext.getOut();
out.println("<FONT COLOR = \"red\"
SIZE=\"5\"><B><I>");
} catch(IOException ioe) {
throw new JspTagException("I/O exception " +
ioe.getMessage());
}
return EVAL_BODY_INCLUDE;
}
<HTML>
<HEAD>
<TITLE>Change Font</TITLE>
</HEAD>
<BODY>
<mt:changeFont>
This text will be changed because it’s in the body of the tag
</mt:changeFont>
<BR>
This text is not in the body of the tag!
</BODY>
</HTML>
Example 4.20 - ChangeFont.jsp
2. Create a JSP custom tag to display the current date to the browser. This tag must take the
format attribute to set the date. The tag must not include any body content. For example:
<mt:date format=”dd/MM/yyyy”/>
<tag>
<name>date</name>
<tagclass>unit4.mt.DateTag</tagclass>
<bodycontent>EMPTY</bodycontent>
<attribute>
<name>format</name>
</attribute>
</tag>
package unit4.mt;
import javax.servlet.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import java.text.*;
import java.util.*;
<HTML>
<BODY BGCOLOR="red">
3. Include an extra page in the last example so that the user can enter the Select statement in
an input box. You will need to change the TLD so that the body content is JSP and not
tagdependent.
<tag>
<name>bakeryResults</name>
<tagclass>unit4.mt.BakeryResultsTag</tagclass>
<bodycontent>JSP</bodycontent>
<info>Uses the body to execute a select statement and
return the results.
</info>
</tag>
<HTML>
<BODY>
<FORM ACTION="BakeryResults.jsp">
Enter query:
<INPUT TYPE="text" NAME="product"/>
<INPUT TYPE="submit" VALUE="Search"/>
</FORM>
</BODY>
</HTML>
Example 4.23 – Bakery.html
<HTML>
<HEAD>
<TITLE>Bakery Results</TITLE>
</HEAD>
<BODY bgcolor="lightyellow">
<%@ taglib uri="//WEB-INF/tlds/TagLib.tld" prefix="mt" %>
<CENTER><H2>Bakery Results</H2></CENTER>
<CENTER>
<mt:bakeryResults>
<%= request.getParameter("product") %>
</mt:bakeryResults>
</CENTER>
</BODY>
</HTML>
Example 4.24 - BakeryResults.jsp
package unit4.mt;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import java.sql.*;
out.println("<TD>" + rs.getFloat("Price") +
"</TD>");
out.println("</TR>");
}
out.println("</TABLE>");
}catch(Exception e){
System.out.println("Error " + e);
} finally{
/* closes the statement, resultset and the connection */
try{
if(rs != null)
rs.close();
if(st != null)
st.close();
if(con != null)
con.close();
}catch(SQLException sqle){
System.out.println("Error " + sqle);
}
}
}
}
Example 4.25 - BakertResultsTag.java
3. True/False: JSP has inherited Java’s ‘write once, run anywhere’ capability.
4. True/False: Java servlets do not allow an HTML page designer to change the layout of a
page, unless the associated source code is changed.
2. True/False: Java servlets can be run on any platform or any operating system where there is
a running JVM.
3. True/False: JSP technology is based on the original servlet specification, but is focused on
separating presentation from implementation.
A. page
B. include
C. session
D. taglib
A. language
B. request
C. contentType
D. autoflush
4. True/False? In order to control the scope of a variable, you should use open code blocks
within a scriptlet.
The container will close the session if the user has not interacted with the browser for a
certain length of time.
Properties should be private so that they can only be accessed from their get() and
set() methods in a controlled way.
3. True/False: If you are accessing the following set() method of a bean, void setAge(int
age) {...} , using scripting, you do not need to explicitly cast the parameter you pass it.
2. How many components do you need to define in order to create and use custom tags?
Answer: Three
3. True/False: You can use a custom tag in a JSP before the taglib directive.
4. True/False: The Tag interface and corresponding TagSupport class are used for the
implementation of tags that need to process their body content.
1. Write a Web application which will act as a database of videos. The application should
consist of the following:
A database to store the video details. Include a table with columns for the video id,
name, and description. The database should also have a table for categories which has
a one-to-many relationship with the video table (add a category id column to the video
table). The categories table should have columns for an id and description.
One JSP page which includes a table which lists all the videos in the database. Include
the video name, description, and category.
Provide functionality to add videos. When a user adds a video, a cookie must be saved
on his or her machine with the date and the name of the video added.
When the user adds a video, retrieve all the categories from the database and display
them as a list of radio buttons. The selected radio button should be used to store the
category of the new video.
Include an error page for your application.
Make use of custom tags to style the video names in the table in bold and italic.
Provide functionality for the user to add and delete videos to a cart and display the total
amount of videos in the cart.
NOTE The Compulsory Exercise is created. Locate Compulsory Exercise Unit 4 file on the
CD.
3. True/False: Tomcat is a JSP container that provides an environment for creating, running,
and testing JavaServer Pages.
4. True/False: A JSP page looks like a standard html or XML page, with additional elements
that the JSP container processes and strips out.
5. True/False: When the Web server receives a request corresponding to a JSP page, that
request is forwarded to the JSP container for processing.
6. True/False: The JSP container reads and interprets the code in the corresponding file to
generate the dynamic content, inserts the results into the static content already on the
page, and displays the completed page to the Web browser.
8. True/False: If no HTTP method is explicitly specified, then POST is the default method.
9. Which one of the following is not a sub-element of the TLD’s <taglib> element?
A. <tlibversion>
B. <jspversion>
C. <classname>
D. <shortname>
10. True/False: Only <name> and <tagclass> are essential sub-elements of the <tag>
element of the TLD file.
11. True/False: When defining an attribute of a JSP custom tag, only the <name> sub-element
must be specified.
12. Which one of the following is legal JSP syntax to print the value of i?
13. A JSP page called test.jsp is passed a parameter name in the URL using
http://localhost/test.jsp?name="John". The test.jsp contains the following code:
14. Which one of the following correctly represents the following JSP statement?
<%=x%>
A. <jsp:expression=x/>
B. <jsp:expression>x</jsp:expression>
C. <jsp:statement>x</jsp:statement>
D. <jsp:declaration>x</jsp:declaration>
15. Which one of the following correctly represents the following JSP statement?
<%x=1;%>
A. <jsp:expression x=1;/>
B. <jsp:expression>x=1;</jsp:expression>
C. <jsp:statement>x=1;</jsp:statement>
D. <jsp:scriptlet>x=1;</jsp:scriptlet>
16. Which one of the following is printed when the following JSP code is invoked in a browser?
A. The browser will print either hello or hi based on the return value of random().
B. The string hello will always be printed.
C. The string hi will always be printed.
D. The JSP file will not compile.
A. JSP scriptlets and declarations result in code that is inserted inside the _jspService
method.
B. The JSP statement <%! int x;%> is equivalent to the statement
<jsp:scriptlet>int x;</jsp:scriptlet%>.
C. The following are some of the predefined variables that may be used in a JSP
expression: httpSession, context.
D. Instead of using the character %> inside a scriptlet, you may use %\>.
18. Which one of the following is printed when the following section of code is compiled?
A. 1
B. 2
C. 3
D. The program generates a compilation error.
19. Which one of the following JSP variables is not available within a JSP expression?
A. session
B. request
C. httpsession
D. page
20. A bean with a property color is loaded using the following statement:
Which one of the following statements may be used to set the color property of the bean?
A. <jsp:setColor id="fruit"
property="color" value="white"/>
B. <jsp:setProperty name="fruit"
property="color" value="white">
C. <jsp:setProperty name="fruit"
property="color" value="white"/>
D. <jsp:setProperty id="fruit"
property="color" value="white">
21. A bean with a property color is loaded using the following statement:
What happens when the following statement is executed? Select one answer.
22. True/False: If the isThreadSafe attribute of the page directive is false, then the
generated servlet implements the SingleThreadModel interface.
23. Which two of the following represent the correct syntax for usebean?
24. Which two of the following statements with regard to <jsp:usebean> are true?
25. Which one of the following is a legal attribute of the page directive?
A. include
B. scope
C. errorPage
D. debug
Unit 5
package timeservice;
import java.rmi.Remote;
import java.rmi.RemoteException;
package timeservice;
import java.util.Date;
import java.text.SimpleDateFormat;
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.
//DTD Web Application 2.3//EN"
"C:\web-app_2_3.dtd">
<web-app>
<display-name>JAX-RPC TimeService Web Application
</display-name>
<description>Sends system time</description>
<session-config>
<session-timeout>60</session-timeout>
</session-config>
</web-app>
Example 5.3 – Web.xml
<webServices
xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/dd"
version="1.0"
targetNamespaceBase="urn:Foo"
typeNamespaceBase="urn:Foo"
urlPatternBase="/ws">
<endpoint
name="Time"
displayName="Time service"
description="A simple web service"
interface="timeservice.TimeIF"
model="/WEB-INF/model.gz"
implementation="timeservice.TimeImpl" />
<endpointMapping
endpointName="Time"
urlPattern="/time"/>
</webServices>
Example 5.4 - jaxrpc-ri.xml
2. Write a client for the service written in the previous question, and create an Ant build file
that uses a build.properties file to automate the building and running of the client.
package timeclient;
import javax.xml.rpc.Stub;
import java.util.*;
<?xml version="1.0"?>
<project name="timeservice" default="compile-client"
basedir=".">
<property file="build.properties"/>
<!--Path imports for all packages needed for the client-->
<path id="classpath">
<pathelement location="build" />
<fileset dir="${jwsdp.home}\jaxrpc\lib\">
<include name="*.jar" />
</fileset>
<fileset dir="${jwsdp.home}\jwsdp-shared\lib\">
<include name="*.jar" />
</fileset>
<fileset dir="${jwsdp.home}\saaj\lib\">
<include name="*.jar" />
</fileset>
<fileset dir="${jwsdp.home}\fastinfoset\lib\">
<include name="*.jar" />
</fileset>
<fileset dir="${jwsdp.home}\sjsxp\lib\">
<include name="*.jar" />
</fileset>
</path>
<!--Target creates necessary directories for
greetingservice-->
<target name="build">
<mkdir dir="build" />
<mkdir dir="build\dist" />
<mkdir dir="build\WEB-INF" />
<mkdir dir="build\WEB-INF\classes" />
<mkdir dir="build\WEB-INF\classes\greetingservice" />
</target>
</project>
Example 5.8 – build.xml
jwsdp_home=c:/jwsdp-2.0
jwsdpshared=${jwsdp_home}/jwsdp-shared
jaxphome=${jwsdp_home}/jaxp
dom.jar=${jwsdp_home}/jaxp/lib/endorsed/dom.jar
xercesImpl.jar=${jwsdp_home}/jaxp/lib/endorsed/xercesImpl.jar
jaxrpc-api.jar=${jwsdp_home}/jaxrpc/lib/jaxrpc-api.jar
jaxrpc-impl.jar=${jwsdp_home}/jaxrpc/lib/jaxrpc-impl.jar
jax-qname.jar=${jwsdp_home}/jwsdp-shared/lib/jax-qname.jar
activation.jar=${jwsdp_home}/jwsdp-shared/lib/activation.jar
mail.jar=${jwsdp_home}/jwsdp-shared/lib/mail.jar
xsdlib.jar=${jwsdp_home}/jwsdp-shared/lib/xsdlib.jar
saaj-api.jar=${jwsdp_home}/saaj/lib/saaj-api.jar
saaj-impl.jar=${jwsdp_home}/saaj/lib/saaj-impl.jar
commons-logging.jar=${jwsdp_home}/jwsdp-shared/lib/
commons-logging.jar
ant.jar=${jwsdp_home}/apache-ant/lib/ant.jar
jaf.jar=${jwsdpshared}/lib/activation.jar
sax.jar=${jaxphome}/lib/endorsed/sax.jar
jaxp-api.jar=${jaxphome}/lib/jaxp-api.jar
xalan.jar=${jaxphome}/lib/endorsed/xalan.jar
relaxngDatatype.jar=${jwsdpshared}/lib/relaxngDatatype.jar
fastInfoset.jar=${jwsdp_home}/fastinfoset/lib/FastInfoset.jar
Example 5.9 – build.properties
<order>
<orderItem>
<name>apples</name>
<quantity>3</quantity>
</orderItem>
<orderItem>
<name>pears</name>
<quantity>2</quantity>
</orderItem>
<orderItem>
<name>oranges</name>
<quantity>7</quantity>
</orderItem>
<orderItem>
<name>grapes</name>
<quantity>4</quantity>
</orderItem>
</order>
Example 5.10 – order.xml
import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse( new File(argv[0]) );
} catch (Exception e) {
Example 5.12 - DomParser.java – DOM
2. Include the CDATA section in the program that was created in the previous question to
display an invoice.
<order>
<orderItem>
<name>apples</name>
<quantity>3</quantity>
</orderItem>
<orderItem>
<name>pears</name>
<quantity>2</quantity>
</orderItem>
<orderItem>
<name>oranges</name>
<quantity>7</quantity>
</orderItem>
<orderItem>
<name>grapes</name>
<quantity>4</quantity>
</orderItem>
<![CDATA[
This is my order!!
Deliver as soon as possible and you may live!
Mwhahahahahaha!!!
-----------------------------------------------
]]>
</order>
Example 5.13 – CDATA entered into order.xml
3. Write a DTD document with which you can validate the XML file. Include a copyright entity
and insert it into the XML file.
<order>
<orderItem>
<name>apples</name>
<quantity>3</quantity>
</orderItem>
<orderItem>
<name>pears</name>
<quantity>2</quantity>
</orderItem>
<orderItem>
<name>oranges</name>
<quantity>7</quantity>
</orderItem>
<orderItem>
<name>grapes</name>
<quantity>4</quantity>
<copyright>©</copyright>
</orderItem>
<![CDATA[
This is my order!!
Deliver as soon as possible and you may live!
Mwhahahahahaha!!!
-----------------------------------------------
]]>
</order>
Example 5.15 – order.xml
<order>
<orderItem id="">
<quantity bulkDiscount="no">10</quantity>
</orderItem>
<orderItem id="">
<quantity bulkDiscount="no">20</quantity>
</orderItem>
<orderItem id="">
<quantity bulkDiscount="yes">10</quantity>
</orderItem>
</order>
Example 5.16 – order.xml
import javax.xml.soap.*;
import java.net.*;
import java.util.*;
import java.io.*;
SOAPConnectionFactory soapConnectionFactory =
SOAPConnectionFactory.newInstance();
SOAPConnection connection =
soapConnectionFactory.createConnection();
MessageFactory messageFactory =
MessageFactory.newInstance();
// Create a message
SOAPMessage message =
messageFactory.createMessage();
// Get the SOAP header and body from the message
// and remove the header
SOAPHeader header = message.getSOAPHeader();
SOAPBody body = message.getSOAPBody();
header.detachNode();
// Get envelope!
SOAPPart sp = message.getSOAPPart();
SOAPEnvelope env = sp.getEnvelope();
message.writeTo(System.out);
// Close the connection
connection.close();
<?xml version="1.0"?>
<path id="classpath">
<fileset dir="${jwsdp.home}/saaj/lib">
<include name="*.jar" />
</fileset>
<fileset dir="${jwsdp.home}/jwsdp-shared/lib">
<include name="*.jar" />
</fileset>
<fileset dir="${jwsdp.home}/jaxp/lib/endorsed">
<include name="*.jar" />
</fileset>
<pathelement location="build" />
</path>
jwsdp.home=/jwsdp-2.0/
build=build
src=src
Example 5.19 - build.properties
2. Create a DOM object based on the above XML file, and use the object to set the content of a
SOAP message.
import javax.xml.soap.*;
import java.net.*;
import java.util.*;
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
SOAPConnectionFactory soapConnectionFactory =
SOAPConnectionFactory.newInstance();
SOAPConnection connection =
soapConnectionFactory.createConnection();
MessageFactory messageFactory =
MessageFactory.newInstance();
// Create a message
SOAPMessage message =
messageFactory.createMessage();
// Add children!
Element root = (Element)
document.createElement("order");
document.appendChild(root);
Element orderItem = null;
Element quantity = null;
String [] quantityList = {"10","20","10"};
for (int i = 0; i < quantityList.length; i++) {
orderItem = (Element)
document.createElement("orderItem");
quantity = (Element)
document.createElement("quantity");
quantity.appendChild(document.createTextNode(
quantityList[i]));
orderItem.appendChild(quantity);
root.appendChild(orderItem);
}
// Add the document to the SOAPBody!
SOAPBodyElement docElement =
body.addDocument(document);
<?xml version="1.0"?>
<fileset dir="${jwsdp.home}/saaj/lib">
<include name="*.jar" />
</fileset>
<fileset dir="${jwsdp.home}/jwsdp-shared/lib">
<include name="*.jar" />
</fileset>
<fileset dir="${jwsdp.home}/jaxp/lib/endorsed">
<include name="*.jar" />
</fileset>
<pathelement location="build" />
</path>
The build.properties file is the same as the one that was created in the Question 1.
import javax.xml.soap.*;
import java.net.*;
import java.util.*;
import java.io.*;
import javax.activation.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
// Create a message
SOAPMessage message =
messageFactory.createMessage();
// Add children!
Element root = (Element)
document.createElement("order");
document.appendChild(root);
Element orderItem = null;
Element quantity = null;
String [] quantityList = {"10","20","10"};
for (int i = 0; i < quantityList.length; i++) {
orderItem = (Element)
document.createElement("orderItem");
quantity = (Element)
document.createElement("quantity");
quantity.appendChild(document.createTextNode(
quantityList[i]));
orderItem.appendChild(quantity);
root.appendChild(orderItem);
}
attachment1.setContent("Hello World!!",
"text/plain");
attachment1.setContentId("attached_text");
message.addAttachmentPart(attachment1);
AttachmentPart attachment2 =
message.createAttachmentPart(dataHandler);
attachment2.setContentId("attached_image");
message.addAttachmentPart(attachment2);
message.saveChanges();
The build.xml file remains the same except for the name of the Java class file to run. The
build.properties file remains the same.
4. Write a simple SOAP fault message indicating that the server is unable to deal with orders
and to please try again later.
import javax.xml.soap.*;
import java.net.*;
import java.util.*;
import java.io.*;
import javax.activation.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
// Create a message
SOAPMessage message =
messageFactory.createMessage();
// Add children!
Element root = (Element)
document.createElement("order");
document.appendChild(root);
Element orderItem = null;
Element quantity = null;
String [] quantityList = {"10","20","10"};
for (int i = 0; i < quantityList.length; i++) {
orderItem = (Element)
document.createElement("orderItem");
quantity = (Element)
document.createElement("quantity");
quantity.appendChild(document.createTextNode(
quantityList[i]));
orderItem.appendChild(quantity);
root.appendChild(orderItem);
}
attachment1.setContent("Hello World!!",
"text/plain");
attachment1.setContentId("attached_text");
message.addAttachmentPart(attachment1);
message.saveChanges();
The build.xml file remains the same except for the name of the Java class file to run. The
build.properties file remains the same.
The WSDL file will be downloaded from the provided URL and the client will be created under
the Web Service References node in the Projects window.
Expand the Web Service References node until the sayHello node is exposed.
@WebServiceRef(wsdlLocation =
"http://localhost:8080/Hello/HelloService?wsdl")
out.close();
}
HTTPServlet Methods
}
Select the sayHello node from the Projects window and drag it onto the servlet page inside the
out.println("<body>") tags.
out.println("<body>");
out.println("<h1>Servlet HelloServlet </h1>");
out.println("</body>");
out.println("<body>");
out.println("<h1>Servlet HelloServlet </h1>");
out.println("</body>");
Answer: c, d, a, b
A. The first line of the build file specifies that it is an XML file.
B. The target tags are used as a wrapper for a series of commands.
C. Ant compiles all the Java files – even the Java files that have an older time stamp
than class files.
D. The name attribute specifies the name of the project.
A. SAX
B. JAXB
C. DOM
D. XSLT
5. True/False: SAX can be used to create modifiable object representation of XML data.
6. Which one of the following is the correct syntax for importing an entity?
A. *entityName
B. &entityName
C. %entityName;
D. &entityName;
7. True/False: DOM objects can be written as XML files using DTD definitions.
A. Messaging
B. Business process modelling
C. Registries and repositories
D. UDDI
A. It is expensive.
B. It is a standard owned by IBM.
C. Its data types are inconsistent.
D. It is suitable for big corporations, not small ones.
A. SMTP
B. IMAP
C. POP3
D. MIME
4. True/False: The SMTP host and the POP3 host are always the same.
1. Write an application that uses SAAJ and servlets to process an order for a pet shop. An order
submitted on the website should be sent to the servlet which generates an XML file
showing the details of the order. You may use Javamail to send the XML file to the user, or
display the XML file in the browser.
Create a build.xml file which compiles, packages, and deploys the application.
2. Write a JAX-RPC Web service which provides conversion services. A client application
should read in an XML file using JAXP (SAX or DOM may be used) and convert the data in
the XML document into metric units using the Web service. The data should then be written
out as a new XML document.
Include a build.xml file which compiles and packages the Web service, and runs the client
using Ant. No user interface is necessary for the client application.
WebServices\
conversionservice\
webservice\
build.xml
conversionFile.xml
src\
Client\
ConversionClient.java
config-wsdl.xml
Service\
ConversionIF.java
ConversionImpl.java
configuration.xml
Jar\
jaxrpc-ri.xml
web.xml
package conversionservice;
import java.rmi.Remote;
import java.rmi.RemoteException;
package conversionservice;
<endpoint
name="MyConversion"
displayName="Conversion Service"
description="converts miles to km's"
interface="conversionservice.ConversionIF"
model="/WEB-INF/model.gz"
implementation="conversionservice.ConversionImpl" />
<endpointMapping
endpointName="MyConversion"
urlPattern="/conversion" />
/webServices>
Example 5.27 – jaxrpc-ri.xml
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.
//DTD Web Application 2.3//EN"
"C:\web-app_2_3.dtd">
<web-app>
<display-name>Conversion Application</display-name>
<description>A web application containing a simple JAX-RPC
endpoint
</description>
<session-config>
<session-timeout>60</session-timeout>
</session-config>
</web-app>
Example 5.28 – web.xml
package conversionclient;
import javax.xml.rpc.Stub;
import java.util.*;
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.rmi.RemoteException;
import org.xml.sax.SAXException;
public ConversionClient(){
try{
Stub stub = createProxy();
stub._setProperty(javax.xml.rpc.Stub.
ENDPOINT_ADDRESS_PROPERTY, http://localhost:8080/
conversion-jaxrpc/conversion");
conversion = (ConversionIF)stub;
createDocs();
processData(); //methods called to complete
client tasks
writeToFile();
}catch(Exception ex){
ex.printStackTrace();
}
}
outDoc = builder.newDocument();
inDoc = builder.parse("conversionFile.xml");
}catch(ParserConfigurationException pce){
pce.printStackTrace();
}catch(SAXException e){
e.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
//document
if(node.getNodeName().equals("distance")){
//Gets value in "data" tags
String data =
node.getChildNodes().item(0).getNodeValue();
Element convert =
(Element)outDoc.createElement("conversion");
//Creates elements for output file
Element meter =
(Element)outDoc.createElement("meter");
Element kms = (Element)outDoc.createElement("kms");
try{
kms.appendChild(outDoc.createTextNode(
conversion.convert(data)));
}catch(RemoteException re){
re.printStackTrace();
}
convert.appendChild(meter); //Values added to
//another element
convert.appendChild(kms);
outRoot.appendChild(convert); //Element added to
//root element
}
}
}
//Main method
public static void main (String [] args){
System.out.println("Program Running");
new ConversionClient(); //Instance of class created
System.out.println("Program Finished - Note the
Results.xml file");
}
}
Example 5.29 – ConversionClient.java
<configuration
xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config">
<wsdl location="http://localhost:8080/
conversion-jaxrpc/conversion?WSDL"
packageName="conversionclient" />
</configuration>
Example 5.30 – config-wsdl.xml
<?xml version="1.0"?>
<project name="ConversionService" default="compile-client"
basedir=".">
<!--Default does all up till compiling client-->
<property name="jwsdp.home" value="C:\Sun\jwsdp-2.0" />
<!--Property for default jwsdp directory-->
<exec executable="${jwsdp.home}\jaxrpc\bin\wscompile.bat"
dir=".">
<arg line="-gen:client" />
<arg line="-d" />
<arg line="build" />
<!--arguments for wscompile command-->
<arg line="-classpath" />
<arg line="build" />
<arg line="config-wsdl.xml" />
</exec>
<javac srcDir="src\Client" destdir="build">
<classpath refid="classpath" />
<!--client is compiled normally-->
</javac>
<delete file="config-wsdl.xml" />
<!--delete unneeded file-->
<delete file="ConversionClient.java" />
</target>
<sysproperty key="endpoint"
value="http://localhost:8080/
conversion-jaxrpc/conversion"/>
<arg value="http://localhost:8080/
conversion-jaxrpc/conversion"/>
</java>
</target>
</project>
Example 5.32 – build.xml
A. JAXP offers three ways of parsing data – SAX, DOM, and XSLT.
B. The Java Web Services Developer Pack includes JAXP.
C. JAXP enables the programmer to easily parse XML data.
D. SAX is event-based.
A. The SAX reader is made up of the ContentHandler, the ErrorHandler, the DTDHandler,
and the EntityResolver.
B. To be able to parse an XML file, a SAX parser object needs to be created as follows:
SAXParserFactory fac =
new SAXParserFactory.newInstance();
SAXParser parser = fac.newSAXParser();
7. Which one of the following statements regarding SAX and DOM is incorrect?
8. Which one of the following statements regarding additional event handlers is false?
10. Which one of the following is not an operation which can be achieved using SAAJ?
A. Fault code
B. Fault string
C. Fault actor
D. Fault originator
C. ebXML includes proprietary contributions from big companies such as IBM and
Microsoft.
D. ebXML is modular and allows gradual change.
A. Web services use the request/response model, but ebXML uses the collaboration model.
B. The UDDI registry is only for current Web services, not ebXML.
C. CPP and CPA are used in ebXML, while WSDL is used in current Web services.
D. CPP is a new standard replacing WSDL.
Unit 6
javax.microedition.lcdui.game.*;
javax.microedition.media.*;
NOTE If you do not use the setTime() method, the get() method will return the current
time and not the time that you have set.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.*;
public StudySchedule(){
display = Display.getDisplay(this);
form.append(df);
form.append(tf);
form.addCommand(exitCommand);
list.addCommand(exitCommand);
form.addCommand(enterCommand);
form.setCommandListener(this);
list.setCommandListener(this);
display.setCurrent(form);
}
2. Create a MIDlet that includes four shapes, with the names next to each shape. Include an
Exit command.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.*;
public ShapeName(){
display = Display.getDisplay(this);
shapeCanvas.addCommand(exitCommand);
shapeCanvas.setCommandListener(this);
display.setCurrent(shapeCanvas);
}
ShapeCanvas(){
}
public void paint(Graphics g){
g.setColor(200,200,200); //gray color
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(255,0,0); //red
g.fillArc(10,10,30,30,0,360);
g.drawString("Circle", 60, 10,
Graphics.LEFT|Graphics.TOP);
g.setColor(0,255,0); //green
g.fillRect(10,50,30,20);
g.drawString("Rectangle", 60, 50,
Graphics.LEFT|Graphics.TOP);
g.setColor(0,0,255); //blue
g.drawLine(10,80,20,100);
g.drawLine(20,80,10,100);
g.drawString("Cross", 60, 80,
Graphics.LEFT|Graphics.TOP);
g.setColor(0,255,255); //light blue
g.drawRoundRect(10,120,40,30,7,9);
g.drawString("Round Rectangle", 60, 120,
Graphics.LEFT|Graphics.TOP);
}
}
Example 6.2 – ShapeName.java
3. Create a MIDlet that has three text fields on a form. The text fields must be able to accept
numeric values between 0 and 255. These values will be used to set the RGB (red, green and
blue) values of a separate canvas’ background colour. If any of the numbers are not in this
range, display an error to the user and clear all the text fields. If the numbers are in the
correct range, set the display to the canvas with the background colour being set by the text
field values specified by the user. Include an Exit command.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.*;
public ColorChooser(){
display = Display.getDisplay(this);
form.addCommand(exitCommand);
form.addCommand(okCommand);
form.setCommandListener(this);
display.setCurrent(form);
}
} else {
/*sends the textfields values to the
ColorCanvas class*/
ColorCanvas cc = new ColorCanvas(red,green,blue);
cc.addCommand(exitCommand);
cc.setCommandListener(this);
display.setCurrent(cc);
}
}
}
}
int r;
int gr;
int b;
}
}
Example 6.3 – ColorChooser.java
The code for this exercise could differ drastically, depending on the structure of the
HTML file.
<html>
<head>
<title>Games Page</title>
</head>
<body bgcolor="lightgrey">
<h1>Games Top 10</h1>
<table border="1">
<tr>
<th>Position</th>
<th>Game</th>
</tr>
<tr>
<td>1</td>
<td>Quake</td>
</tr>
<tr>
<td>2</td>
<td>Unreal Tournament</td>
</tr>
<tr>
<td>3</td>
<td>The Sims</td>
</tr>
<tr>
<td>4</td>
<td>Diablo III</td>
</tr>
<tr>
<td>5</td>
<td>Tomb Raider</td>
</tr>
</table>
</body>
</html>
Example 6.4 – HTML file
import javax.microedition.midlet.*;
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
int pos;
Thread runner;
public GamesWeb(){
display = Display.getDisplay(this);
form1.append(positionField);
form1.addCommand(exitCommand);
form1.addCommand(getGameCommand);
form1.setCommandListener(this);
form2.addCommand(exitCommand);
form2.setCommandListener(this);
}
try{
/*creates a connection to the text file on the Web
server*/
conn = StreamConnection)Connector.open(
"http://127.0.0.1/Games.html");
in = conn.openInputStream();
int ch;
boolean isData = false;
2. Add onto the MyPhoneBook example so that the user can also delete a selected name and
number from the record store.
import javax.microedition.rms.*;
import java.util.*;
try{
recordStore.addRecord(bytes, 0 ,bytes.length);
}catch(RecordStoreException rse){
System.err.println("Error " + rse);
}
}
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import java.util.*;
import java.io.*;
PhoneBookDB pb;
Vector vec;
Vector idVec;
public MyPhoneBook(){
display = Display.getDisplay(this);
/* commands */
okCommand = new Command("OK", Command.OK, 1);
exitCommand = new Command("Exit", Command.EXIT, 2);
saveCommand = new Command("Save", Command.OK, 2);
deleteCommand = new Command("Delete", Command.OK, 3);
//delete
backCommand = new Command("Back", Command.BACK, 3);
getNumberCommand = new Command("Get Number",
Command.OK, 2);
/* different screens */
firstScreen = new List("Make a selection",
List.IMPLICIT);
form = new Form("Phone Book");
list = new List("All phone number", List.IMPLICIT);
form.append(nameField);
form.append(numField);
firstScreen.addCommand(okCommand);
firstScreen.addCommand(exitCommand);
form.addCommand(backCommand);
form.addCommand(saveCommand);
list.addCommand(getNumberCommand);
list.addCommand(deleteCommand);
list.addCommand(backCommand);
form2.append(numberItem);
form2.addCommand(backCommand);
firstScreen.setCommandListener(this);
form.setCommandListener(this);
list.setCommandListener(this);
form2.setCommandListener(this);
/* creates an image */
try{
phoneImage = Image.createImage("/phone.png");
}catch(IOException ioe){
System.err.println("Image Error " + ioe);
}
if(c == okCommand){
int select = firstScreen.getSelectedIndex();
if(select == 0){ //option to add a name to the
//phone book
nameField.setString(""); //clears the name and
// number fields
numField.setString("");
display.setCurrent(form);
}else{ //option to display the list of names
listOfNames();
display.setCurrent(list);
}
if(select == 0){
nameField.setString(""); //clears the name
numField.setString(""); //and number fields
display.setCurrent(form);
}else{
listOfNames();
display.setCurrent(list);
}
}
numberItem.setText(number);
form2.setTitle(name);
display.setCurrent(form2); //displays the form with
// the number
3. Create a MIDlet that could be used as a booking system for a restaurant. You must be able to
enter the time of the booking, the number of people, and a name. It only needs to work on a
daily basis, so the date is not important. Add a “View bookings” option that must display all
the bookings for the current hour. For example, if two bookings are made for 19:30 and four
for 20:00, and the time is 19:15, only the two bookings must be displayed.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import java.util.*;
import java.io.*;
public BookingSystem(){
display = Display.getDisplay(this);
/* commands */
insertCommand = new Command("Insert Booking",
Command.OK, 1);
exitCommand = new Command("Exit", Command.EXIT, 2);
backCommand = new Command("Back", Command.BACK, 3);
viewCommand = new Command("View Bookings", Command.OK,
2);
/* different screens */
insertForm = new Form("Please enter your Booking");
viewForm = new Form("The time is: ");
insertForm.append(timeField);
insertForm.append(nameField);
insertForm.append(numField);
insertForm.addCommand(exitCommand);
insertForm.addCommand(insertCommand);
insertForm.addCommand(viewCommand);
insertForm.setCommandListener(this);
viewForm.addCommand(backCommand);
viewForm.setCommandListener(this);
if(c == insertCommand){
if((nameField.getString().equals(""))||
(numField.getString().equals(""))){
/* displays error if user doesnt enter values */
Alert al = new Alert("Please enter a value",
"Please enter a value",
null, AlertType.ERROR);
display.setCurrent(al);
} else{
/* forms the time string */
time = timeField.getDate();
cal = Calendar.getInstance();
cal.setTime(time);
String timeString = cal.get(Calendar.HOUR_OF_DAY)
+ ":" +
cal.get(Calendar.MINUTE);
String record = timeString + ";" +
nameField.getString() +";" +
numField.getString();
try{
while(en.hasNextElement()){ //loops through each
// record
String rec = new String(en.nextRecord());
/* check the hours of the current time against
the hours of the bookings */
if(rec.substring(0,rec.indexOf(":")).equals(
getCurrentTime().substring(0,
currTime.indexOf(":")))){
rec = rec.replace(';','\n');
viewForm.append(new StringItem("", rec));
viewForm.append(new Spacer(1,1));
/* record is added to form to be displayed */
}
}
}catch(RecordStoreException rse){
System.err.println("Error " + rse);
}
}
}
Example 6.8 – BookingSystem.java
import javax.microedition.rms.*;
import java.util.*;
A. startApp()
B. initApp()
C. pauseApp()
D. destoyApp()
E. repaintApp()
2. True/False: The CLDC describes a more specific level of functionality than the MIDP.
A. lib
B. src
C. res
D. sound
2. True/False: The emulator in the J2ME Wireless Toolkit can emulate any mobile device that
exists.
A. javax.microedition.midlet.*;
B. javax.microedition.swing.*;
C. javax.microedition.rms.*;
D. javax.micoredition.pki.*;
3. True/False: The java.io package in standard Java contains the same classes as the
javax.micoredition.io package.
A. setComponent()
B. add()
C. include()
D. append()
A. Size
B. Speed
C. Maintainability
D. Functionality
2. True/False: Setting an object to null will help the garbage collector to free its memory
space.
3. True/False: You can use a FileInputStream to read data from a text file when using a
MIDlet.
1. True/False: The Micro Edition was created for wireless mobile devices which have more
computing power and smaller screens compared to laptops and PCs.
2. True/False: When a wireless device supports Java, it means that the device includes a
smaller version of the Java Virtual Machine, known as the KVM.
A. WAP
B. SMS
C. Blue tooth
D. USB
4. True/False: Due to the size of wireless devices, it is only logical not to include all the Java
programming language features, and therefore only a subset of the language is defined
under the CLDC.
5. Which one of the following is not a security issue regarding the CLDC?
A. The user is not allowed to access built-in functions of the mobile device.
6. True/False: The Wireless Toolkit contains two command-line tools – the bytecode verifier
and the J2ME emulator.
8. Which one of the following devices is not included in the J2ME Wireless Toolkit?
A. Qwerty device
B. Media control skin
C. Default black and white phone
D. Default colour phone
9. True/False: With custom device profiles you can create new emulator devices.
10. Which three of the following attributes must be included in the manifest file when
packaging a MIDP application?
A. MIDlet-Name
B. MIDlet-Description
C. MIDlet-Configuration
D. MIDlet-Version
E. MIDlet-0
F. MIDlet-Vendor
11. True/False: Only two packages have been included in the CLDC API from the standard Java
API.
12. True/False: The purpose of the GCF is to define an I/O architecture that supports
extremely flexible file input and output.
13. Which one of the following classes is not included in the java.util package?
A. Hashtable
B. Calendar
C. ArrayList
D. Random
14. True/False: The MIDP API inherited only two classes directly from the the Standard Java API;
namely the Timer and TimerTask classes.
15. True/False: The MIDlet class is an abstract class and provides the basic functional
requirements of a MIDlet for execution on a mobile device.
16. Which one of the following classes does not extend the Screen class?
A. Panel
B. Alert
C. Form
D. List
A. IMPLICIT
B. MULTIPLE
C. EXCLUSIVE
D. SINGLE
18. True/False: To get the selected elements in a multiple list you can use the
getSelectedIndex() method.
A. StringItem
B. DateField
C. TextBox
D. ImageItem
20. True/False: Only components that extend the Screen class can be used within a form.
21. True/False: Maintainability can be achieved by keeping the structure and organization of
your code relatively simple and neat.
22. True/False: When using a loop, you should not include calculations and method calls inside
the loop that can be done once before the loop.
23. Which one of the following does not minimize the amount of memory that is required by a
MIDlet?
24. True/False: The HTTPConnection interface from the MIDP API is a request-response
protocol which supports HTTP.