Advanced Java Programming Unit 4-6 (JV5BC-07 V1.2) Instructor Guide

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 105

Advanced Java Programming

Instructors Guide
JV5BC-07 V1.2
Java 5 Instructor Guide
JV5BC-07

Compiled by Carla Labuschagne

Edited by Cameron Dalton and Jonathan Marsh

Version 1.2

 August 2007 CTI Education Group


TABLE OF CONTENTS
INTRODUCTION 1 
Unit description 1 
Summary of learning outcomes 1 
Content 2 
Learning outcomes and assessment criteria 4 
Guidance on delivery and assessment 4 
Links 5 
Resources 5 

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.

Summary of learning outcomes

To achieve this unit a learner must:

1. Create and use HTML, Servlets, and JSP.


2. Use of Objects, Actions, Scopes, Cookies, and JavaBeans.
3. Create and use Web Services.
4. Create and use JavaMail.
5. Install and Use the Java Micro Edition (J2ME).
6. Build and create a Graphical MIDlet.

© CTI Education Group


Introduction Page 2

Content

1. Create and use HTML, Servlets, and JSP.


Introduction to HTML and JavaServer pages: The World Wide Web Consortium and XML. What is
JSP, the benefits of JSP, JSP requirements, JBoss, Index.html, JSP life cycle, and installing the Java
SDK.

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.

2. Use of Objects, Actions, Scopes, Cookies, and JavaBeans


Implicit Objects, Actions, Scope, and Cookies.

JavaBeans and JDBC: Introduction to JavaBeans, JavaBean scope, JDBC.

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.

Creating a Web Application: Setting up NetBeans and creating the application.

3. Create and use Web Services


Introduction to XML and the differences between HTML and XML. Installing the Web services
package and Java packages used for Web services. Writing Web Services Using Jax-RPC and
using Ant. Using JAXP (Introduction, using the SAX API to parse XML and Using DOM to parse
XML data), introduction to SOAP with Attachments API for JAVA (SAAJ). The future of Web
Services and the ebXML architecture. Creating a Web service in NetBeans (creating the Web
Service and creating the client application).

4. Create and use JavaMail


JavaMail: Introduction to JavaMail. Understand the use of email systems and the JavaMail API.
Write your first email. Create multimedia emails with embedded images, and miscellaneous mail
operations with attachments. Use JavaMail to retrieve and delete messages.

© CTI Education Group


Introduction Page 3

5. Install and Use the Java Micro Edition (J2ME)


Install and use the J2ME development kit: Overview of the available toolkits for J2ME
development, installing the J2ME Wireless Toolkit in Windows and Linux, familiarisation with the
KToolBar.

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.

6. Build and create a Graphical MIDlet


J2ME Application Interfaces (APIs): Using the CLDC API, using the Generic Connection
Framework, using MIDP API, using Wireless Messaging API (WMA) and using Mobile Media API
(MMAPI).

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.

© CTI Education Group


Introduction Page 4

Learning outcomes and assessment criteria

Assessment for pass – A pass is awarded for the unit on the achievement of all the pass
assessment criteria.

Assessment criteria for pass


Learning outcomes To achieve each outcome a learner must
demonstrate the ability to:
1. Create and use HTML, Serv-  Create an HTML page.
lets, and JSP.  Create a JSP page using JavaScript and JSP.
 Use of JSP scripts in a JSP page.
2. Use of Objects, Actions,  Use NetBeans to create a Web application
Scopes, Cookies, and Java-  Create and use a custom tag.
Beans  Use Implicit Objects, Actions, and Scope in a JSP
page.
3. Create and use Web Ser-  Create a web service in NetBeans
vices  Parse an XML document using SAX or DOM
 Create SOAP messages
4. Create and use JavaMail  Write a simple program that sends an email.
 Create an HTML email with embedded images.
 Create email with attachments
5. Install and Use the Java  Install the J2ME development kit
Micro Edition (J2ME)  Demonstrate how to use the J2ME wireless toolkit
 Use J2ME Application Interfaces (APIs)
6. Build and create a Graphi-  Create a graphical MIDlet using GUI Components
cal MIDlet  Create a graphical MIDlet that draws shapes
 Use Optimization, I/O, and RMS

Guidance on delivery and assessment

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.

© CTI Education Group


Introduction Page 5

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

Java 5 Part 2 is a prerequisite in order to study this unit.

NOTE This unit has been developed under the BTECi customised framework for the following
BTEC Higher National Diplomas:

 Information Systems - Software Development


 Information Systems – Engineering
 Information Systems – Comprehensive Programming.

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

© CTI Education Group


Introduction Page 6

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).

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 7

Unit 4

4.1 Answers to exercises

4.1.1 Section 4.2.8


2. Create an index page for the Test example.

The index.html file is included in the study guide.

4.1.2 Section 4.3.6


1. Write a paragraph describing the differences between Servlets and JSPs.

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.

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 8

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");

/* write the HTML to the output buffer */


out.print("<HTML>");
out.print("<BODY>");
out.print("<CENTER>");
out.print(sdf.format(todaysDate));
out.print("</CENTER>");
out.print("</BODY>");
out.print("</HTML>");
}
}
Example 4.1 – DateServlet.java

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 9

3. Write the JSP equivalent of the previous Servlet.

<%@ page import="java.util.*,java.text.*" %>


<html>
<body>

<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

4.1.3 Section 4.4.7


1. Create an HTML file which uses a form to get a number from the user.

 This number will be passed as a parameter to a JSP (Chapter 7 pg. 86).

 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.

 Do the same for a random number between 0 and 10.

 Print the numbers and the answers to the screen.

 Include all three types of comments in your code.

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 10

The HTML file will look something like the following:

<HTML>
<HEAD>
<TITLE>Get number</TITLE>
</HEAD>

<BODY>
<FORM ACTION= "NumberFun.jsp">

Number: <INPUT TYPE = "text" NAME="num"


SIZE="26"><BR><BR>
<INPUT TYPE = "submit" VALUE=" Submit ">
<INPUT TYPE = "reset" VALUE="Clear form">
</FORM>
</BODY>
</HTML>
Example 4.3 – GetNum.html

The JSP should look similar to the following:

<%@ page info="The Fun number Cruncher, Copyright 2000 by


Cti" %>
<%@ page import = "java.util.Random" %>

<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 */

public float area(int num) {


float area;
area = Math.round(Math.PI*num*num);
return area;
}
%>

<P> <%= getServletInfo() %> </P>


<P> Welcome to <%=name %> 's number cruncher </P>

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 11

<%
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);
%>

<BR><BR> Random Number is <%= number %>


<BR> The square root of the random number is:
<%= Math.sqrt(number) %>
<BR> The radius of the circle is: <%= area(number) %>

</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.:

<BR><BR> Random Number is <%= number %>

could be replaced by

out.println ("<BR><BR>Random number is " + number);

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.

<%-- This file creates a table. The first column holds


numbers from 0 to 10, the second displays the list of items
in the list array, the third displays the price, and finally
the total of all the prices.
--%>
<HTML>

<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};
%>

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 12

<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

4.1.4 Section 4.5.6


1. Create a JSP called Footer.jsp that displays a short message.

<HTML>
<BODY>

<HR/>
<H3>@copy; CTI Education Group</H3>

</BODY>
</HTML>
Example 4.6 – Footer.jsp

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 13

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.

<%@ page import="java.util.*,java.text.*,java.net.*" %>

<HTML>
<BODY BGCOLOR="lightgreen">

<%
String cookieName = "DateCookie";

Cookie cookies[] = request.getCookies();


Cookie myCookie = null;

/* if there are cookies in the array */


if (cookies != null) {
for (int x = 0; x < cookies.length; x++) {

/* look for specific cookie by name */


if (cookies[x].getName().equals(cookieName)) {
myCookie = cookies[x];
break;
}
}
}
/* specific cookie was not found */
if (myCookie == null) {
out.println("<H4>FirstTime visitor I see</H4>");
} else {
if(myCookie.getValue().equals(new SimpleDateFormat(
"dd-MMMM-yyyy").format(new
Date()))){%>
<jsp:forward page="BeenHere.jsp"/>
<% } else {
out.println("Last time you accessed this site was "
+ myCookie.getValue());
}
}

String name = new SimpleDateFormat(


"dd-MMMM-yyyy").format(new Date());

Cookie cookie = new Cookie(cookieName,


URLEncoder.encode(name));

/* set info needed by cookie */


cookie.setDomain("127.0.0.1"); /*own IP address*/
cookie.setMaxAge(365*24*60*60);
cookie.setVersion(0);
cookie.setSecure(false);

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 14

/* add cookie to response object */


response.addCookie(cookie);
%>

<jsp:include page="Footer.jsp" flush="true" />

</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

4.1.5 Section 4.6.6


1. Create a simple JSP which uses tags to access a bean which:

 Accepts a measurement in inches.


 Converts the inches to centimetres (1 inch = 2.54 cm).
 Returns the measurement in centimetres.

Provide an HTML page with a form to enter the initial measurement.


Draw the property sheet for the bean.

The JavaBean for Exercise 1 should look similar to the example below:

package unit4;
import java.io.*;

public class MyBean implements Serializable {

private float inches = 0;


private float centimeters;

public void setInches (float inches) {


this.inches = inches;
}

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 15

public float getCentimeters () {


this.centimeters = this.inches * 2.54f;
return this.centimeters;
}
}
Example 4.9 - MyBean.java

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

The JSP for the exercise looks as follows:

<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

The property sheet for the bean looks as follows:

Name Access Java type Example


Inches Write-only Float 1.5
Centimetres Read-only Float 3.44

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 16

2. Write a JSP that uses scripting to access a bean which:

 Checks a user’s name against five approved users:


o Jack
o John
o Jill
o James
o Jennifer

 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.

The JavaBean looks as follows:

package unit4;
import java.io.*;

public class MySecondBean implements Serializable {

private String names[];


private String userName;
private boolean isValidUser;

public MySecondBean () {
isValidUser = false;
names = new String[5];
names[0] = "Jack";
names[1] = "John";
names[2] = "Jill";
names[3] = "James";
names[4] = "Jennifer";
}

public void setUserName(String userName){


this.userName = userName;
checkUser();
}

public boolean getIsValidUser (){


return this.isValidUser;
}

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 17

private void checkUser() {


for (int x = 0; x < names.length; x++) {
if (names[x].equals(userName)) {
isValidUser = true;
}
}
}
}
Example 4.12 - MySecondBean.java

The HTML form looks as follows:

<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

The JSP file looks as follows:

<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

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 18

The property sheet for the bean looks as follows:

Name Access Java type Example


userName write-only String Tim
isValidUser read-only boolean true

3. Study the property sheet below. Write a JSP (on paper), using tags, that will use all the
bean’s get() and set() methods.

Name Access Java type Example


firstNumber write-only double 12.34
secondNumber write-only double 15.77
sum read-only double 25.01
dateString read-only String 25/01/2000

<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.

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 19

The HTML file will look as follows:

<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

The JSP will look as follows:

<%@ page import="java.sql.*" %>

<!-- use the ConnectionBean made earlier and store it in the


user’s session -->
<jsp:useBean id="connection" class="unit5.ConnectionBean"
scope="session"/>

<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;

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 20

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>
<%

/* iterate through search results and display results


in table format */
while (result.next()) {
out.println("<TR>");
out.println("<TD>"+result.getInt("ID")+"</TD>");
out.println("<TD>" +
result.getString("DESCRIPTION") +
"</TD>");
out.println("<TD>" + result.getFloat("PRICE") +
"</TD>");
out.println("</TR>");
}
%>
</TABLE>
</CENTER>

<% }

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 21

catch (SQLException sqle) {


out.println("<CENTER>Bad SQL statement" + sqle
+ "</CENTER>");
}
%>
<!-- link back to the query page -->
<BR>
<CENTER>
<A href="SimpleExample.html"><FONT color="white">
Write another query</FONT></A>
</CENTER>
</BODY>
</HTML>
Example 4.17 - PartialQueryResult.jsp

4.1.6 Section 4.7.9


1. Create a JSP custom tag that takes no attribute and simply changes all text included in the
tag’s body to a red, bold, italics font with a size of 5.

The TLD file:

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.


//DTD JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/Web-jsptaglib_1_1.dtd">

<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>

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 22

<tag>
<name>changeFont</name>
<tagclass>unit4.mt.ChangeFontTag</tagclass>
<bodycontent>JSP</bodycontent>
</tag>
</taglib>
Example 4.18 – TagLib.tld

The Java class will look as follows:

package unit4.mt;

import javax.servlet.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;

public class ChangeFontTag extends TagSupport {


private int importance = 0;

public int doStartTag() throws JspException{


ServletRequest request = pageContext.getRequest();

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;
}

public int doEndTag() {


try {
JspWriter out = pageContext.getOut();
out.print("</I></B></FONT>");
} catch (IOException ioe) {
System.out.println("Error");
}
return (EVAL_PAGE);
}
}
Example 4.19 - ChangeFontTag.java

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 23

The JSP file will look as follows:

<HTML>
<HEAD>

<%@ taglib uri="//WEB-INF/tlds/TagLib.tld" prefix="mt" %>

<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”/>

The following needs to be included in the TLD file:

<tag>
<name>date</name>
<tagclass>unit4.mt.DateTag</tagclass>
<bodycontent>EMPTY</bodycontent>
<attribute>
<name>format</name>
</attribute>
</tag>

The Java file will look as follows:

package unit4.mt;

import javax.servlet.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import java.text.*;
import java.util.*;

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 24

public class DateTag extends TagSupport {


private String format = "";

public void setFormat(String format) {


this.format = format;
}
public int doStartTag () throws JspException {
try {
JspWriter out = pageContext.getOut();
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(format);
out.print(sdf.format(d));
} catch (IOException ioe) {
System.out.println("Error in FirstTag:"+
ioe.getMessage());
}
return (SKIP_BODY);
}
}
Example 4.21 - DateTag.java

The JSP file will look as follows:

<HTML>
<BODY BGCOLOR="red">

<%@ taglib uri="//WEB-INF/tlds/TagLib.tld" prefix="mt" %>

<B>The date today is: <mt:date format="dd MMMM yyyy"/> <BR/>


Or: <mt:date format="yyyy-MM-dd"/></B>
</BODY>
</HTML>
Example 4.22 - TheDate.jsp

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.

The following must be included in the TLD file:

<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>

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 25

The HTML file will look as follows:

<HTML>
<BODY>

<H2>Search for product:</H2>

<FORM ACTION="BakeryResults.jsp">
Enter query:
<INPUT TYPE="text" NAME="product"/>
<INPUT TYPE="submit" VALUE="Search"/>

</FORM>
</BODY>
</HTML>
Example 4.23 – Bakery.html

The JSP file will look as follows:

<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

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 26

The Java file will look as follows:

package unit4.mt;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import java.sql.*;

public class BakeryResultsTag extends BodyTagSupport {

public int doEndTag() throws JspException{


try {
/* gets the body text between the start and end tag */
BodyContent body = getBodyContent();
String bodyString = body.getString();
bodyContent.clearBody();
//sends the tag's body to the getSelection method
getSelection(bodyString);
} catch (Exception e) {
System.out.println("Error " + e);
}
return EVAL_PAGE;
}

public void getSelection(String bodyString){


Connection con = null;
Statement st = null;
ResultSet rs = null;
try{
JspWriter out = pageContext.getOut();
/* Connects to the database */
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(
"jdbc:odbc:Bakery");
st = con.createStatement();

/* uses the tags body to execute the query */


rs = st.executeQuery(bodyString);

/* displays the results in a table */


out.println("<TABLE BORDER=\"1\">");
out.println("<TR><TH>Id</TH> <TH>Name</TH>" +
" <TH>Price</TH></TR>");
while(rs.next()){
out.println("<TR>");
out.println("<TD>" +
rs.getString("Id")+"</TD>");
out.println("<TD>"+ rs.getString("Name") +
"</TD>");

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 27

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

4.2 Answers to revision questions

4.2.1 Section 4.2.9


1. True/False: The most important characteristic of JSP is that it separates page design from
implementation.

2. True/False: JSP offers a high degree of platform independence and cross-platform


portability.

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.

5. True/False: JSP does not support the use of reusable components.

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 28

4.2.2 Section 4.3.7


1. True/False: There is a separate servlet running on the server for every user request in a Web-
based application.

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.

4. True/False: A thorough knowledge of Java is necessary to code a simple JSP page.

5. True/False: It is not necessary to compile a .jsp page.

4.2.3 Section 4.4.7


1. True/False: It is possible to use both scripting-oriented tags and XML-based tags in the same
JSP.

2. Which one of the following is not a JSP directive?

A. page
B. include
C. session
D. taglib

3. Which one of the following is not a page directive?

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.

4.2.4 Section 4.5.7


1. True/False: A major difference between using the include directive and the include
action tag is that, using the include directive, any changes made in the included file are
not automatically reflected in the output.

2. True/False: A session will continue as long as the user’s browser is open.

 The container will close the session if the user has not interacted with the browser for a
certain length of time.

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 29

4.2.5 Section 4.6.7


1. In order to qualify as a JavaBean, a class must have which two attributes?

 It must implement java.io.Serializable, and it must use get() and set()


accessors to set and retrieve its properties.

2. Why should properties of a bean be private?

 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.

 You do not need to cast if accessing from tags.

4.2.6 Section 4.7.10


1. True/False: If the needs of your application cannot be met using the standard JSP bean tags,
you are forced to use scripting elements.

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.

5. True/False: The doAfterBody() returns either SKIP_BODY or EVAL_BODY_TAG.

4.3 Solution to compulsory exercise

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.

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 30

 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.

The one-to-many relationship database:

The Category table:

The Video table:

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 31

NOTE The Compulsory Exercise is created. Locate Compulsory Exercise Unit 4 file on the
CD.

4.4 Answers to test your knowledge

1. True/False: JSP is platform-independent and vendor-neutral.

2. True/False: JSP technology’s emphasis on components over scripting makes it easier to


revise content without affecting logic, or revise logic without changing content.

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.

7. True/False: It is easier to modify a servlet than to modify an equivalent JSP.

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?

A. <%int i = 1;%> <%= i; %>


B. <%int i = 1%> <%= i %>
C. <%int i = 1;%> <%= i %>
D. <%int i = 1%> <%= i; %>

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 32

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:

<%! String myName=request.getParameter();%>


<% String test= "welcome" + myName; %>
<%= test%>

A. The program prints "Welcome John".


B. The program gives a syntax error because of line 1.
C. The program gives a syntax error because of line 2.
D. The program gives a syntax error because of line 3.

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?

<%= if(Math.random() < 0.5) %>


hello
<%= } else { %>
hi
<%= } %>

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.

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 33

17. Which one of the following is correct?

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?

<% int y = 0; %>


<% int z = 0; %>

<% for(int x=0;x<3;x++) { %>


<% z++;++y;%>
<% }%>

<% if(z<y) {%>


<%= z%>
<% } else {%>
<%= z - 1%>
<% }%>

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

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 34

20. A bean with a property color is loaded using the following statement:

<jsp:usebean id="fruit" class="Fruit"/>.

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:

<jsp:usebean id="fruit" class="Fruit"/>

What happens when the following statement is executed? Select one answer.

<jsp:setProperty name="fruit" property="*"/>

A. This is the incorrect syntax of <jsp:setProperty/> and will generate a


compilation error. Either value or param must be defined.
B. All the properties of the fruit bean are initialized to a value of null.
C. All the properties of the fruit bean are assigned the values of input parameters of the
JSP page that has the same name.
D. All the properties of the fruit bean are initialized to a value of *.

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?

A. <jsp:usebean id="fruit scope ="page"/>


B. <jsp:usebean id="fruit type ="String"/>
C. <jsp:usebean id="fruit type ="String" beanName="Fruit"/>
D. <jsp:usebean id="fruit class="Fruit" beanName="Fruit"/>

24. Which two of the following statements with regard to <jsp:usebean> are true?

A. The id attribute must be defined for <jsp:usebean>.


B. The scope attribute must be defined for
<jsp:usebean>.
C. The class attribute must be defined for <jsp:usebean>.
D. The <jsp:usebean> must include either a type or class attribute or both.

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 35

25. Which one of the following is a legal attribute of the page directive?

A. include
B. scope
C. errorPage
D. debug

© CTI Education Group


Java 5 B – Instructor Guide: Unit 4 Page 36

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 37

Unit 5

5.1 Answers to exercises

5.1.1 Section 5.3.5


1. Write a simple JAX-RPC-based timing Web service program. When a client queries the
service, it should return the current system time.

package timeservice;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface TimeIF extends Remote {


public String sendTime() throws RemoteException;
}
Example 5.1 – TimeIF.java

package timeservice;

import java.util.Date;
import java.text.SimpleDateFormat;

public class TimeImpl implements TimeIF {


public String time;

public String sendTime() {


SimpleDateFormat time = new
SimpleDateFormat("HH:mm:ss");
Date d = new Date();
return time.format(d);
}
}
Example 5.2 – TimeImpl.java

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 38

<?xml version="1.0" encoding="UTF-8"?>

<!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

<?xml version="1.0" encoding="UTF-8"?>

<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

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 39

<?xml version="1.0" encoding="UTF-8"?>


<configuration
xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config">
<service
name="MyTimeService"
targetNamespace="urn:Foo"
typeNamespace="urn:Foo"
packageName="timeservice">
<interface name="timeservice.TimeIF"/>
</service>
</configuration>
Example 5.5 – configuration.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.*;

public class TimeClient {

private String endpointAddress;

public static void main(String[] args) {

System.out.println("Endpoint address = " + args[0]);


try {
Stub stub = createProxy();
stub._setProperty(javax.xml.rpc.Stub.
ENDPOINT_ADDRESS_PROPERTY,
args[0]);
TimeIF time = (TimeIF)stub;

System.out.println("Current time is: " +


time.sendTime());
} catch (Exception ex) {
ex.printStackTrace();
}
}

private static Stub createProxy() {


return (Stub)(new
MyTimeService_Impl().getTimeIFPort());
}
}
Example 5.6 – Timeclient.java

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 40

<?xml version="1.0" encoding="UTF-8"?>


<configuration
xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config">
<wsdl location="http://localhost:8080/time-jaxrpc/
time?WSDL" packageName="timeclient"/>
</configuration>
Example 5.7 - config-wsdl.xml

<?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>

<!--Target compiles service-->


<target name="compile-service" depends="build">
<!--compiles into build folder-->
<javac srcdir="src\Service" destdir="build" />
</target>

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 41

<!--Target compiles service creating a model.gz file-->


<target name="wscompile-service"
depends="compile-service">
<exec executable="${jwsdp.home}\jaxrpc\bin\wscompile.bat"
dir =".">
<arg line="-define" />
<arg line="-d" />
<arg line="build" />
<arg line="-nd" />
<arg line="build" />
<arg line="-classpath" />
<arg line="build" />
<arg line="src\Service\configuration.xml" />
<arg line="-model" />
<arg line="build\model.gz" />
</exec>
</target>

<!--Target copies files to WEB-INf directory and runs the


jar command-->
<target name="jar" depends="wscompile-service">
<copy todir="build\WEB-INF\classes\timeservice">
<fileset dir="build\timeservice" />
</copy>
<copy todir="build\WEB-INF">
<!--copies web.xml and jaxrpc-ri.xml-->
<fileset dir="src\jar" />
</copy>
<!--copies model.gz to WEB-INF-->
<copy todir="build\WEB-INF" file="build\model.gz" />
<exec executable="C:\Program Files\Java\jdk1.5.0_09\
bin\jar.exe" dir="build">
<!--arguments for build command-->
<arg line="cvf" />
<arg line="dist\time-jaxrpc-portable.war" />
<arg line="WEB-INF/" />
</exec>
</target>

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 42

<!-- Create .war file and copies it to the default


Autodeploy folder-->
<target name="deploy-service" depends="jar">
<exec executable="${jwsdp.home}\jaxrpc\bin\
wsdeploy.bat" dir="build\dist">
<!--command executed from dist folder-->
<arg line="-o" />
<!--arguments for wsdeploy command-->
<arg line="time-jaxrpc.war" />
<arg line="time-jaxrpc-portable.war" />
</exec>
<copy todir="C:\Sun\AppServer\domains\domain1\autodeploy"
file="build\dist\time-jaxrpc.war" />
</target>

<!--Target compiles client and copies files to current


directory-->
<target name="compile-client">
<copy todir=".">
<fileset dir="src\Client" />
</copy>
<exec executable="${jwsdp.home}\jaxrpc\bin\wscompile.bat"
dir=".">
<!--arguments for wscompile command-->
<arg line="-gen:client" />
<arg line="-d" />
<arg line="build" />
<arg line="-classpath" />
<arg line="build" />
<arg line="config-wsdl.xml" />
</exec>
<javac srcDir="src\Client" destdir="build">
<!--Client is compiled normally-->
<classpath refid="classpath" />
</javac>
<delete file="config-wsdl.xml" />
<!--delete unneeded file-->
<delete file="TimeClient.java" />
</target>

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 43

<!-- runs the client -->


<target name="run-client"> <!--depends="compile-client"-->
<waitfor>
<http url="http://localhost:8080/time-jaxrpc"/>
</waitfor>
<java classname="timeclient.TimeClient"
classpathref="classpath" fork="true">
<sysproperty key="endpoint"
value="http://localhost:8080/time-jaxrpc/time"/>
<arg value="http://localhost:8080/time-jaxrpc/time"/>
</java>
</target>

<!--Target removes all files created by the build file-->


<target name="clear">
<!--created during build target-->
<delete dir="build" />
</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

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 44

5.1.2 Section 5.4.5


1. Create an XML file which describes an order, and write two programs parse the file using
SAX and DOM to respectively. Print out the elements and values of the 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>
</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;

public class Parser {


public static void main(String args[]) {
Example 5.11 - Parser.java – SAX

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 45

import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;

public class DomParser{

public static void main(String argv[]) {


if (argv.length != 1) {
System.err.println("Enter filename to be parsed: ");
System.exit(1);
}

DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();

try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse( new File(argv[0]) );

// Get the root element


Element rootElement = document.getDocumentElement();
System.out.println("Root element : " +
rootElement.getTagName());

// Does the root element have children?


NodeList children = rootElement.getChildNodes();
Node node =null;
Node childNode = null;
for (int i = 0; i < children.getLength(); i++) {
node = children.item(i);
System.out.println("Node number: "+i+",
Name: "+node.getNodeName());

NodeList childrenChild = node.getChildNodes();


for (int j = 0; j < childrenChild.getLength(); j++)
{
childNode = childrenChild.item(j);
System.out.println("Child node number " + j +
",Name: "+
childNode.getNodeName());
if (childNode.getNodeType() ==
Node.ELEMENT_NODE) {
System.out.println(" value: " +
childNode.getFirstChild().getNodeValue());
}
}
}

} catch (Exception e) {
Example 5.12 - DomParser.java – DOM

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 46

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.

<!ELEMENT order (copyright, orderItam*, name*, quantity*)>


<!ELEMENT orderItem (#PCDATA)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT quantity (#PCDATA)>
<!ELEMENT copyright (#PCDATA)>
<!ENTITY copy "Copyright information: don't copy!!">
Example 5.14 – order.dtd

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 47

<?xml version="1.0" encoding="utf-8" ?>


<!DOCTYPE order SYSTEM "order.dtd">

<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>&copy;</copyright>
</orderItem>

<![CDATA[
This is my order!!
Deliver as soon as possible and you may live!
Mwhahahahahaha!!!
-----------------------------------------------
]]>

</order>
Example 5.15 – order.xml

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 48

5.1.3 Section 5.5.3


1. Write a SOAP message which simulates an order from a customer to a clothing store:

<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.*;

public class SoapMessageMaker {

public static void main(String[] args) {


try {

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();

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 49

// Create a SOAP factory


SOAPFactory soapFactory = SOAPFactory.newInstance();

SOAPBodyElement bodyEl = body.addBodyElement(


soapFactory.createName("order",
"","urn:uddi-org:api_v2"));
SOAPElement orderItem = null;
SOAPElement quantity = null;
String [] quantityList = {"10","20","10"};
String [] discountList= {"no", "no","yes"};

for (int i = 0; i <3; i++) {


orderItem = bodyEl.addChildElement(
soapFactory.createName("orderItem"));
orderItem.addAttribute(soapFactory.createName
("id"),"");
quantity = orderItem.addChildElement(
soapFactory.createName("quantity"));
quantity.addTextNode(quantityList[i]);
quantity.addAttribute(
soapFactory.createName("bulkDiscount"),
discountList[i]);
}

// Create connection and message factory


message.saveChanges();

// Display the message you are sending


System.out.println("\n--- Request Message ---\n");

message.writeTo(System.out);
// Close the connection
connection.close();

} catch (Exception ex) {


ex.printStackTrace();
}
}
}
Example 5.17 - SoapMessageMaker

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 50

<?xml version="1.0"?>

<!-- Project name tag! -->


<project name="SoapMessageMaker" default="build" basedir=".">

<!-- First target (command) is init -->


<target name="init">
<!-- Used to create time-stamped filenames! Usually done
within init targets -->
<tstamp/>
</target>

<!-- Includes a properties file which defines a few


variables -->
<property file="build.properties"/>

<!-- Used to build the “build” directory -->


<target name="prepare" depends="init" description="Creates
build directory.">
<mkdir dir="${build}" />
</target>

<target name="build" depends="prepare" description="Compiles


Java file and puts the resulting class file in the
build directory." >
<javac srcdir="${src}" destdir="${build}">
<classpath refid="classpath"/>
<include name="*.java"/>
</javac>
</target>

<target name="info" depends="init">


<!-- echoing prints the message to the user -->
<echo message="Java WSDP Home: ${jwsdp.home}"/>
<echo message="Build Home: ${build}"/>
</target>

<target name="clean" >


<delete dir="${build}" />
</target>

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 51

<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>

<target name="run" depends="build" description="Runs the


program, prints the XML message to the screen!">
<echo message="Runs the program, prints the XML message to
the screen!"/>
<java classname="SoapMessageMaker" fork="yes">
<classpath refid="classpath" />
</java>
</target>
</project>
Example 5.18 - build.xml

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.*;

public class SoapMessageMakerDom {

public static void main(String[] args) {


try {

SOAPConnectionFactory soapConnectionFactory =
SOAPConnectionFactory.newInstance();
SOAPConnection connection =
soapConnectionFactory.createConnection();
MessageFactory messageFactory =
MessageFactory.newInstance();

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 52

// 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();

// Create a new document


DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder =
factory.newDocumentBuilder();
Document document = builder.newDocument();

// 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);

// Create connection and message factory


message.saveChanges();

// Display the message you are sending


System.out.println("\n--- Request Message ---\n");
message.writeTo(System.out);

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 53

// Close the connection


connection.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Example 5.20 - SoapMessageMakerDom

<?xml version="1.0"?>

<!-- Project name tag! -->


<project name="SoapMessageMakerDom" default="build"
basedir=".">

<!-- First target (command) is init -->


<target name="init">
<!-- Used to create time-stamped filenames!
Usually done within init targets -->
<tstamp/>
</target>

<!-- Includes a properties file which defines a few


variables -->
<property file="build.properties"/>

<!-- Used to build the “build” directory -->


<target name="prepare" depends="init" description="Creates
build directory.">
<mkdir dir="${build}" />
</target>

<target name="build" depends="prepare" description="Compiles


Java file and puts the resulting class file in the
build directory." >
<javac srcdir="${src}" destdir="${build}">
<classpath refid="classpath"/>
<include name="*.java"/>
</javac>
</target>

<target name="info" depends="init">


<!-- echoing prints the message to the user -->
<echo message="Java WSDP Home: ${jwsdp.home}"/>
<echo message="Build Home: ${build}"/>
</target>

<target name="clean" >


<delete dir="${build}" />
</target>
<path id="classpath">

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 54

<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>

<target name="run" depends="build" description="Runs the


program, prints the XML message to the screen!">
<echo message="Runs the program, prints the XML message to
the screen!"/>
<java classname="SoapMessageMakerDom" fork="yes">
<classpath refid="classpath" />
</java>
</target>
</project>
Example 5.21 - build.xml

The build.properties file is the same as the one that was created in the Question 1.

3. Attach a graphics file to the SOAP message created in Question 1 or Question 2.

import javax.xml.soap.*;
import java.net.*;
import java.util.*;
import java.io.*;
import javax.activation.*;

import javax.xml.parsers.*;
import org.w3c.dom.*;

public class ImageAttachedSoap {

public static void main(String[] args) {


try {

// Create connection and message factory


SOAPConnectionFactory soapConnectionFactory =
SOAPConnectionFactory.newInstance();
SOAPConnection connection =
soapConnectionFactory.createConnection();
MessageFactory messageFactory =
MessageFactory.newInstance();

// Create a message

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 55

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();

// Create a new document


DocumentBuilderFactory factory=
DocumentBuilderFactory.newInstance();
DocumentBuilder builder =
factory.newDocumentBuilder();
Document document = builder.newDocument();

// 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);

// Create attachment part for text


AttachmentPart attachment1 =
message.createAttachmentPart();

attachment1.setContent("Hello World!!",
"text/plain");
attachment1.setContentId("attached_text");

message.addAttachmentPart(attachment1);

// Create attachment part for image


URL url = new URL("file:///c:/mypic.jpg");
DataHandler dataHandler = new DataHandler(url);

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 56

AttachmentPart attachment2 =
message.createAttachmentPart(dataHandler);
attachment2.setContentId("attached_image");
message.addAttachmentPart(attachment2);

message.saveChanges();

// Display the message you are sending


System.out.println("\n--- Request Message ---\n");
message.writeTo(System.out);

// Close the connection


connection.close();

} catch (Exception ex) {


ex.printStackTrace();
}
}
}
Example 5.22 - ImageAttachedSoap

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.*;

public class ImageAttachedSoap {

public static void main(String[] args) {


try {

// Create connection and message factory


SOAPConnectionFactory soapConnectionFactory =
SOAPConnectionFactory.newInstance();
SOAPConnection connection =
soapConnectionFactory.createConnection();
MessageFactory messageFactory =
MessageFactory.newInstance();

// Create a message

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 57

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();

// Create a new document


DocumentBuilderFactory factory=
DocumentBuilderFactory.newInstance();
DocumentBuilder builder =
factory.newDocumentBuilder();
Document document = builder.newDocument();

// 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);

// Create attachment part for text


AttachmentPart attachment1 =
message.createAttachmentPart();

attachment1.setContent("Hello World!!",
"text/plain");
attachment1.setContentId("attached_text");

message.addAttachmentPart(attachment1);

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 58

// Create attachment part for image


URL url = new URL("file:///c:/mypic.jpg");
DataHandler dataHandler = new DataHandler(url);
AttachmentPart attachment2 =
message.createAttachmentPart(dataHandler);
attachment2.setContentId("attached_image");
message.addAttachmentPart(attachment2);

message.saveChanges();

// Display the message you are sending


System.out.println("\n--- Request Message ---\n");
message.writeTo(System.out);

// Close the connection


connection.close();

} catch (Exception ex) {


ex.printStackTrace();
}
}
}
Example 5.23 - SOAPServerFault

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.

5.1.4 Section 5.8.4


1. Write a simple Web application to consume the Web service created in this chapter. After
you have created Hello Service do the following when creating the Client application:

 Click on File > New Project.


 In the Categories section, select Web and Web Application from the Projects section.
 Enter HelloClientWeb as the Project Name.
 Click Finish.
 Right-click on the HelloClientWeb node and select New > Servlet.
 Insert HelloServlet for the Class Name.
 Click Finish.

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.

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 59

The HelloServlet will look similar to the following:

public class HelloServlet extends HttpServlet {

@WebServiceRef(wsdlLocation =
"http://localhost:8080/Hello/HelloService?wsdl")

private helloclientweb.HelloService service;

protected void processRequest(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

// TODO output your page here


out.println("<html>");
out.println("<head>");
out.println("<title>Servlet HelloServlet</title>");
out.println("</head>");
out.println("<body>");

out.println("<h1>Servlet HelloServlet </h1>");


out.println("</body>");
out.println("</html>");

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.

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 60

 The following code will be inserted:

out.println("<body>");
out.println("<h1>Servlet HelloServlet </h1>");

try { // Call Web Service Operation


helloclientweb.HelloServiceSEI port =
service.getHelloServiceSEIPort();

// TODO initialize WS operation arguments here


java.lang.String string1 = "";

// TODO process result here


java.lang.String result = port.sayHello(string1);
out.println("Result = "+result);
} catch (Exception ex) {
// TODO handle custom exceptions here
}

out.println("</body>");

 Update the code to look as follows (in bold):

out.println("<body>");
out.println("<h1>Servlet HelloServlet </h1>");

try { // Call Web Service Operation


helloclientweb.HelloServiceSEI port =
service.getHelloServiceSEIPort();

// TODO initialize WS operation arguments here


java.lang.String string1 = "Carla";

// TODO process result here


java.lang.String result = port.sayHello(string1);
out.println("Result = "+result);
} catch (Exception ex) {
// TODO handle custom exceptions here
}

out.println("</body>");

 Right-click the HelloClientWeb node and select Properties.


 Select the Run node.
 Insert /HelloServlet into the Relative URL field.
 Click OK.
 Right-click the HelloClientWeb node and select Run Project.

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 61

The output will be displayed as follows:

5.2 Answers to revision questions

5.2.1 Section 5.3.6


1. True/False: The mechanics of JAX-RPC are similar to RMI.

2. Arrange the following steps in the correct order:

a) Create a client application.


b) Run your application.
c) Define an interface which lists all the methods that are available, and another file which
implements the methods.
d) Create a configuration file that will be used to run the wscompile command.

Answer: c, d, a, b

3. Which one of the following regarding Ant is not true?

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.

5.2.2 Section 5.4.8


1. Which one of the following is not a part of JAXP?

A. SAX
B. JAXB
C. DOM
D. XSLT

2. True/False: JAXP provides two ways of parsing data.

3. True/False: SAX is event-driven.

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 62

4. Which one of the following is not true regarding JAXP?

A. SAXParser wraps a SAXReader.


B. The DefaultHandler implements the ContentHandler.
C. The “>” sign calls the endElement event.
D. ErrorHandler objects are used to deal with errors.

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.

5.2.3 Section 5.5.4


1. True/False: SAAJ must be used when there is an existing XML document.

2. True/False: SAAJ can be used in asynchronous interactions.

5.2.4 Section 5.6.6


1. Which one of the following is not a part of the ebXML architecture?

A. Messaging
B. Business process modelling
C. Registries and repositories
D. UDDI

2. Which one of the following is not a disadvantage of EDI?

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.

3. True/False: ebXML will slowly be replaced by Web services.

4. True/False: CPP and CPA replace WSDL in ebXML.

5.2.5 Section 5.7.7


1. True/False: MIME enables you to send messages which are not simple ASCII text messages.

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 63

2. Which one of the following is a protocol used to transfer emails?

A. SMTP
B. IMAP
C. POP3
D. MIME

3. True/False: Emails are made of two parts – header and body.

4. True/False: The SMTP host and the POP3 host are always the same.

5.3 Solution to compulsory exercise

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.

Your directory structure will look as follows:

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;

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 64

import java.rmi.Remote;
import java.rmi.RemoteException;

//Interface for the service


public interface ConversionIF extends Remote{
public String convert(String num) throws RemoteException;
}
Example 5.24 – ConversionIF.java

package conversionservice;

//Implementation of the interface


public class ConversionImpl implements ConversionIF{

//Method converts miles value to km's


public String convert(String num){
if(num.indexOf('.') == -1){ //if num is an integer
int temp = Integer.parseInt(num);
/*convert to integer for calculation*/
temp = (temp * 8) / 5;
return String.valueOf(temp); //return answer
}else{ //if num is a double
double temp = Double.parseDouble(num);
temp = (temp * 8) / 5;
String tempString = String.valueOf(temp);
int numDecimal = num.length() - num.indexOf('.');
return tempString.substring(0,
tempString.indexOf('.') + numDecimal);
}
}
}
Example 5.25 – ConversionImpl.java

<?xml version="1.0" encoding="UTF-8"?>


<configuration
xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config">
<service
name="MyConversionService"
targetNamespace="urn:Foo"
typeNamespace="urn:Foo"
packageName="conversionservice">
<interface name="conversionservice.ConversionIF" />
</service>
</configuration>
Example 5.26 – configuration.xml

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 65

<?xml version="1.0" encoding="UTF-8"?>


<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="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

<?xml version="1.0" encoding="UTF-8"?>

<!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.*;

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 66

import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.rmi.RemoteException;
import org.xml.sax.SAXException;

public class ConversionClient {


Document inDoc, outDoc;
ConversionIF conversion;
Element convert;

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();
}
}

//Method creates new Document for Results and Parses input


//file
public void createDocs(){
try {
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();

outDoc = builder.newDocument();
inDoc = builder.parse("conversionFile.xml");
}catch(ParserConfigurationException pce){
pce.printStackTrace();
}catch(SAXException e){
e.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}
}

//Method processes parsed file and creates elements for new


//file
public void processData(){
Element outRoot =
(Element)outDoc.createElement("Results");
outDoc.appendChild(outRoot); //root element for new

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 67

//document

Element inRoot = inDoc.getDocumentElement();


NodeList children = inRoot.getChildNodes();
//children in data file
for(int i = 0 ; i < children.getLength() ; i++){
Node node = children.item(i);

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
}
}
}

//Method transforms data to an xml file


public void writeToFile(){
try{
TransformerFactory tFactory =
TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(outDoc);
//Document used
StreamResult result = new StreamResult(new
File("Results.xml"));
//Transforms to Results.xml
transformer.transform(source, result);
//actually transform
}catch(TransformerException te){
te.printStackTrace();
}
}

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 68

//Method checks that a string is a valid positive number(int


//or double)
public boolean checkNum(String test){
int dot = 0;
for(int i = 0 ; i < test.length() ; i++){
//loops through characters
char check = test.charAt(i);
if (check == '.')
dot++;
else if (Character.isDigit(check) == false)
return false;
}
}

private static Stub createProxy(){ //Method for getting


//Web service
return (Stub)(new MyConversionService_Impl().
getConversionIFPort());
}

//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

<?xml version="1.0" encoding="UTF-8"?>

<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" encoding="UTF-8"?>


<data>
<distance>200</distance>
<distance>40.34</distance>
</data>
Example 5.31 – conversionFile.xml

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 69

<?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-->

<!--Path imports all needed packages 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 creating


service-->
<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\conversionservice" />
</target>

<!--Target compiles service-->


<target name="compile-service" depends="build">
<javac srcdir="src\Service" destdir="build" />
</target>

<!--Target compiles service with Wscompile command creating


model.gz file-->
<target name="wscompile-service" depends="compile-service">
<exec executable="${jwsdp.home}\jaxrpc\bin\wscompile.bat"
dir=".">
<arg line="-define" />
<arg line="-d" />
<arg line="build" />
<arg line="-nd" /> <!--arguments for command-->

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 70

<arg line="build" />


<arg line="-classpath" />
<arg line="build" />
<arg line="src\Service\configuration.xml" />
<arg line="-model" />
<arg line="build\model.gz" />
</exec>
</target>

<!--Target copies files to WEB-INf directory and runs the jar


command-->
<target name="jar" depends="wscompile-service">
<copy todir="build\WEB-INF\classes\conversionservice">
<fileset dir="build\conversionservice" />
</copy>
<copy todir="build\WEB-INF">
<fileset dir="src\jar" />
<!--copies web.xml and jaxrpc-ri.xml-->
</copy>
<copy todir="build\WEB-INF" file="build\model.gz" />
<!--copies model.gz to WEB-INF-->
<exec executable="C:\Program Files\Java\jdk1.5.0_09\bin\
jar.exe" dir="build">
<arg line="cvf" /> <!--arguments for build command-->
<arg line="dist\conversion-jaxrpc-portable.war" />
<arg line="WEB-INF/" />
</exec>
</target>

<!--Target runs deploy command to create .war file and copies


it to the default Autodeploy folder-->
<target name="deploy-service" depends="jar">
<exec executable="${jwsdp.home}\jaxrpc\bin\wsdeploy.bat"
dir="build\dist">
<!--command executed from dist folder-->
<arg line="-o" />
<arg line="conversion-jaxrpc.war" />
<!--arguments for wsdeploy command-->
<arg line="conversion-jaxrpc-portable.war" />
</exec>
<copy todir="C:\Sun\AppServer\domains\domain1\autodeploy"
file="build\dist\conversion-jaxrpc.war" />
</target>

<!--Target compiles client source file and copies files to


current directory ready for running client-->
<target name="compile-client" depends="deploy-service">
<copy todir=".">
<fileset dir="src\Client" />
</copy>

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 71

<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>

<target name="run-client"> <!--depends="compile-client"-->


<waitfor>
<http url="http://localhost:8080/conversion-jaxrpc"/>
</waitfor>
<java classname="conversionclient.ConversionClient"
classpathref="classpath" fork="true">

<sysproperty key="endpoint"
value="http://localhost:8080/
conversion-jaxrpc/conversion"/>
<arg value="http://localhost:8080/
conversion-jaxrpc/conversion"/>
</java>
</target>

<!--Target removes all files created by the build file-->


<target name="clear">
<delete dir="build" /> <!--created during build target-->
<delete file="Results.xml" />
<!--created when client is run-->
<delete file="Data.xml" />
<!--copied for use by client-->
</target>

</project>
Example 5.32 – build.xml

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 72

5.4 Answers to test your knowledge

1. Which one of the following statements is correct?

A. Ant was written as a make tool for Java.


B. Ant can be used to code Java.
C. Ant uses an XML document file called the configuration file.
D. Ant is written in C, and works only in Windows and Linux.

2. Which one of the following statements is incorrect?

A. <project> is the root element.


B. <project> has three elements – name, default, and basedir.
C. <project> can be omitted.
D. <target> tags signify a command.

3. Which one of the following statements is incorrect?

A. <property> tags can be used to declare variables.


B. <target name=”compile” depends=”firstTarget”> signifies that the target can only be
executed when firstTarget is executed successfully.
C. Ant only compiles the Java files which have an older timestamp than the class files.
D. If the verbose option is used, more details will be printed to the screen.

4. Which one of the following statements is incorrect?

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.

5. Which one of the following statements regarding SAX is incorrect?

A. SAX stands for Simple API for XML.


B. The “<” sign calls the startElement event.
C. The “</” sign calls the endElement event.
D. When there is text between the tags, the element event is called.

6. Which one of the following statements regarding SAX is incorrect?

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();

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 73

C. The ContentHandler must be extended to perform tasks when documents are


being parsed.
D. The SAXParser object wraps a SAXReader. Usually, you will be dealing with a SAXParser
object, not the underlying SAXReader object.

7. Which one of the following statements regarding SAX and DOM is incorrect?

A. SAX is more efficient.


B. SAX can be used to add or delete nodes.
C. DOM can be used to create an object which represents a whole XML document.
D. A DOM object must stay in memory as one object.

8. Which one of the following statements regarding additional event handlers is false?

A. Additional event handlers such as setDocumentLocator and processingInstruction can


be added.
B. The Locator class encapsulates a system ID, and this information can be used to find
other documents from their current location.
C. The setDocumentLocator will be printed after the startDocument method.
D. The processingInstruction event handler can be used to specify application-specific
data.

9. Which one of the following statements is false?

A. SAAJ stands for SOAP with Attachments API for Java.


B. SAAJ allows you to construct SOAP messages without having to create an XML
document directly.
C. JAX-RPC requires that either the client or the server is active.
D. SAAJ provides generic handling of a SOAP message.

10. Which one of the following is not an operation which can be achieved using SAAJ?

A. Creating a SOAP message.


B. Adding attributes to tags.
C. Adding attachments to SOAP messages.
D. Contacting the registry.

11. Which one of the following is not part of a SOAPFault object?

A. Fault code
B. Fault string
C. Fault actor
D. Fault originator

12. Which one of the following statements is false?

A. ebXML is an initiative undertaken by the UN.


B. ebXML is a standard enabling electronic business at a reduced deployment cost.

© CTI Education Group


Java 5 B – Instructor Guide: Unit 5 Page 74

C. ebXML includes proprietary contributions from big companies such as IBM and
Microsoft.
D. ebXML is modular and allows gradual change.

13. Which one of the following is not a disadvantage of EDI?

A. It is expensive and uses proprietary networks.


B. Data types are not consistent.
C. It is not practical for big companies.
D. Remote procurement is not possible from the outside.

14. Which one of the following statements is false?

A. SOAP is used as the protocol for message passing.


B. SOAP’s functionality is extended with security and reliable delivery.
C. ebXML is widely adopted as the industry standard.
D. ebXML’s registry is more advanced than UDDI’s.

15. Which one of the following statements is false?

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.

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 75

Unit 6

6.1 Answers to exercises

6.1.1 Section 6.2.6


1. Write (on paper) the code for a MIDlet that would be able to support games and sound.

javax.microedition.lcdui.game.*;
javax.microedition.media.*;

2. What is the function of the JAD file?

 Java Application Descriptor – provides additional information about the MIDlets


contained in the JAR file. The JAD file contains information about the installation and
access of the MIDlet so that the KVM knows which particular MIDlet to run at a particular
time.

6.1.2 Section 6.5.8


1. Create a MIDlet that could be used as a study scheduler. It must be able to accept a date and
a description. Include a command that uses the two values entered and displays them to the
user in a List. Include an exit command as well. Hint: you will need to use the following to
format the date to use it in the List:

Date date = dateField.getDate();


Calendar cal = Calendar.getInstance();
cal.setTime(date); //sets date to selected date
String dateString = cal.get(Calendar.DAY_OF_MONTH)+
"/" + cal.get(Calendar.MONTH);

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.

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 76

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.*;

public class StudySchedule extends MIDlet implements


CommandListener{

private Display display;


private Command exitCommand;
private Command enterCommand;

private Form form;


private List list;
private DateField df;
private TextField tf;

public StudySchedule(){
display = Display.getDisplay(this);

form = new Form("Study Schedule");


list = new List("Study Schedule", List.IMPLICIT);

exitCommand = new Command("Exit", Command.EXIT, 2);


enterCommand = new Command("Enter", Command.OK,1);

df = new DateField("Date", DateField.DATE);


tf = new TextField("Description", "", 40,
TextField.ANY);

form.append(df);
form.append(tf);

form.addCommand(exitCommand);
list.addCommand(exitCommand);
form.addCommand(enterCommand);

form.setCommandListener(this);
list.setCommandListener(this);

display.setCurrent(form);
}

public void startApp() throws MIDletStateChangeException{


}

public void pauseApp(){


}

public void destroyApp(boolean uncondition) throws


MIDletStateChangeException{
}

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 77

public void commandAction(Command c, Displayable d){


if(c == exitCommand){
try{
destroyApp(false);
}catch(MIDletStateChangeException msce){
System.out.println(msce);
}
notifyDestroyed();

}else if(c == enterCommand){


/* format the date */
Date date = df.getDate();
Calendar cal = Calendar.getInstance();
cal.setTime(date);

/* append the date and description value to the List */


list.append(cal.get(Calendar.DAY_OF_MONTH) + "/" +
cal.get(Calendar.MONTH), null);
list.append(tf.getString(), null);
display.setCurrent(list);
}
}
}
Example 6.1 – StudySchedule.java

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 class ShapeName extends MIDlet implements


CommandListener{

private Display display;


private Command exitCommand;
private ShapeCanvas shapeCanvas;

public ShapeName(){
display = Display.getDisplay(this);

shapeCanvas = new ShapeCanvas();


exitCommand = new Command("Exit", Command.EXIT, 2);

shapeCanvas.addCommand(exitCommand);
shapeCanvas.setCommandListener(this);

display.setCurrent(shapeCanvas);
}

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 78

public void startApp() throws MIDletStateChangeException{


}

public void pauseApp(){


}

public void destroyApp(boolean uncondition) throws


MIDletStateChangeException{
}

public void commandAction(Command c, Displayable d){


if(c == exitCommand){
try{
destroyApp(false);
}catch(MIDletStateChangeException msce){
System.out.println(msce);
}
notifyDestroyed();
}
}
}

class ShapeCanvas extends Canvas{

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

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 79

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 class ColorChooser extends MIDlet implements


CommandListener{

private Display display;


private Command exitCommand;
private Command okCommand;

private Form form;

private TextField tRed;


private TextField tGreen;
private TextField tBlue;

public ColorChooser(){
display = Display.getDisplay(this);

form = new Form("Color chooser");

tRed = new TextField("Red","",5,TextField.NUMERIC);


tGreen = new TextField("Green","",5,TextField.NUMERIC);
tBlue = new TextField("Blue","",5,TextField.NUMERIC);

exitCommand = new Command("Exit", Command.EXIT, 2);


okCommand = new Command("Ok", Command.OK,2);
form.append(tRed);
form.append(tGreen);
form.append(tBlue);

form.addCommand(exitCommand);
form.addCommand(okCommand);

form.setCommandListener(this);

display.setCurrent(form);
}

public void startApp() throws MIDletStateChangeException{


}

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 80

public void pauseApp(){


}

public void destroyApp(boolean uncondition) throws


MIDletStateChangeException{
}

public void commandAction(Command c, Displayable d){


if(c == exitCommand){
try{
destroyApp(false);
}catch(MIDletStateChangeException msce){
System.out.println(msce);
}
notifyDestroyed();
} else if(c == okCommand){
/* changes the text values into integers */
int red = Integer.parseInt(tRed.getString());
int green = Integer.parseInt(tGreen.getString());
int blue = Integer.parseInt(tBlue.getString());

/* checks that the user only enters a value between


0 and 255 else displays an alert */
if((red > 255) || (green > 255) || (blue > 255)){
Alert al = new Alert("Incorrect info", "Please
enter a number between 0
and 255", null,
AlertType.ERROR);
display.setCurrent(al);

tRed.setString(""); //clears the textfields


tGreen.setString("");
tBlue.setString("");

} 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);
}
}
}
}

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 81

class ColorCanvas extends Canvas{

int r;
int gr;
int b;

/* passes the colours as arguments */


ColorCanvas(int r, int gr, int b){
this.r = r;
this.gr = gr;
this.b = b;
}

public void paint(Graphics g){


g.setColor(r,gr,b); //sets the background colour
g.fillRect(0,0,getWidth(),getHeight());

}
}
Example 6.3 – ColorChooser.java

6.1.3 Section 6.6.5


1. Create a small Web page that has a list of the top five computer games. Create a MIDlet that
allows the user to enter a number from 1 to 5. Then retrieve the game at that position and
display the position and the game to the user.

 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>

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 82

<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.*;

public class GamesWeb extends MIDlet


implements CommandListener, Runnable{

private Display display;


private Command exitCommand;
private Command getGameCommand;
private Form form1;
private Form form2;

private TextField positionField;

private StringItem name;


private StringItem position;

int pos;

Thread runner;

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 83

public GamesWeb(){
display = Display.getDisplay(this);

form1 = new Form("Top 5 games");


form2 = new Form("Game");

exitCommand = new Command("Exit", Command.EXIT, 2);


getGameCommand = new Command("Get Game", Command.EXIT, 2);

positionField = new TextField("Games Position", "", 5,


TextField.NUMERIC);

form1.append(positionField);
form1.addCommand(exitCommand);
form1.addCommand(getGameCommand);
form1.setCommandListener(this);
form2.addCommand(exitCommand);
form2.setCommandListener(this);
}

public void startApp() throws MIDletStateChangeException{


display.setCurrent(form1);
}

public void pauseApp(){


}

public void destroyApp(boolean uncondition) throws


MIDletStateChangeException{
runner = null; //stops the thread
}

public void commandAction(Command c, Displayable d){


if(c == exitCommand){
try{
destroyApp(false);
}catch(MIDletStateChangeException msce){
System.out.println(msce);
}
notifyDestroyed();
} else if(c == getGameCommand){
/* creates a new Thread and starts it. */
pos = Integer.parseInt(positionField.getString());
runner = new Thread(this);
runner.start();
}
}

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 84

public void run(){


while(runner == Thread.currentThread()){
StreamConnection conn = null;
InputStream in = null;
StringBuffer buff = new StringBuffer();
StringBuffer data = new StringBuffer();

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;

/* goes through each character on the web page */


while((ch = in.read()) != -1){
if(ch != '\n'){ //not the end of the line
buff.append((char)ch);
//appends the characters
}else{
/* trims white space from the buffer */
String buffy = buff.toString().trim();
/* if the string read is data add it to
the List */
if(isData){
buffy = buffy.substring(4,
buff.length()-7);
name = new StringItem("",buffy);
position = new StringItem("","" + pos);
form2.append(position);
form2.append(name);
isData = false;
runner = null;
/* the thread is stopped here because only
one piece of data needs to be found. */
display.setCurrent(form2);
break;
}

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 85

/* finds the <td> tag with the position


inbetween */
if(buffy.equals("<td>" + pos +
"</td>")){
isData = true;
/* finds the </html> tag, and stops the
thread if the position number does not
exist */
} else if(buffy.equals("</html>")){
System.out.println("No such
position");
runner = null;
}

buff = new StringBuffer();


//clears the buffer
}
}
conn.close();
} catch(IOException ioe){
System.err.println("Error " + ioe);
}
}
try{
Thread.sleep(1000);
}catch(InterruptedException ie){}
}
}
Example 6.5 - GamesWeb

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.*;

public class PhoneBookDB{

RecordStore recordStore = null;

/* creates a record store named PhoneBook */


public PhoneBookDB(){
try{
recordStore =
RecordStore.openRecordStore("PhoneBook",true);
} catch(RecordStoreException rse){
System.err.println("Error " + rse);
}
}

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 86

/* adds the record that was passed as the recordData


argument to the record store */
public void addRecord(String recordData){
byte[] bytes = recordData.getBytes();

try{
recordStore.addRecord(bytes, 0 ,bytes.length);
}catch(RecordStoreException rse){
System.err.println("Error " + rse);
}
}

/* enumerates the records; returns a RecordEnumeration */


public RecordEnumeration listNumbers(){
try{
return recordStore.enumerateRecords(null, null,
false);
}catch(RecordStoreNotOpenException rsnoe){
System.err.println("Error " + rsnoe);
return null;
}
}

/* closes the database */


public void closeDB(){
try{
recordStore.closeRecordStore();
}catch(RecordStoreException rse){
System.err.println("Error " + rse);
}
}
/* get a specific record */
public String getRec(int id){
try{
return new String(recordStore.getRecord(id));
}catch(RecordStoreException rse){
System.out.println("Error " + rse);
return null;
}
}
/* delete a specific record */
public void deleteRec(int id){
try{
recordStore.deleteRecord(id);
}catch(RecordStoreException rse){
System.out.println("Error "+ rse);
}
}
}
Example 6.6 – PhoneBookDB.java

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 87

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import java.util.*;
import java.io.*;

public class MyPhoneBook extends MIDlet implements


CommandListener{

private Display display;

private List firstScreen;


private Form form;
private List list;
private Form form2;
private Command okCommand;
private Command exitCommand;
private Command saveCommand;
private Command deleteCommand; //delete
private Command backCommand;
private Command getNumberCommand;

private TextField nameField;


private TextField numField;

private StringItem numberItem;


Image phoneImage;

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);

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 88

form2 = new Form("Number");

firstScreen.append("Add new Number", null);


firstScreen.append("View Numbers", null);

nameField = new TextField("Name: ", "", 25 ,


TextField.ANY);
numField = new TextField("Number: ", "", 15,
TextField.PHONENUMBER);

numberItem = new StringItem("","");

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);
}

/* instantiates the PhoneBookDB class */


pb = new PhoneBookDB();
}

/* display the first screen to the user */


public void startApp() throws MIDletStateChangeException{
display.setCurrent(firstScreen);
}

public void pauseApp(){


}

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 89

public void destroyApp(boolean unconditional) throws


MIDletStateChangeException{
}

public void commandAction(Command c, Displayable d){

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);
}

} else if(c == exitCommand){


pb.closeDB(); //close the database
try{
destroyApp(false);
}catch(MIDletStateChangeException msce){}
notifyDestroyed();
} else if(c == saveCommand){
/* gets the data from the two text field,
concatenate them into one string with a semi-
colon between */
String data =
nameField.getString() + ";" +
numField.getString();

/* passes the concatenated string to the


PhoneBookDB's addRecord method */
pb.addRecord(data);
listOfNames(); //gets the list of names

display.setCurrent(list);//displays the list


// with all the names

} else if(c == backCommand){


display.setCurrent(firstScreen);
//displays the first screen

} else if(c == List.SELECT_COMMAND){


if(display.getCurrent() == firstScreen){
//list on the first screen
/* if the select button is used instead of the
soft keys it will use this code */
int select = firstScreen.getSelectedIndex();

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 90

if(select == 0){
nameField.setString(""); //clears the name
numField.setString(""); //and number fields
display.setCurrent(form);
}else{
listOfNames();
display.setCurrent(list);
}
}

} else if(c == getNumberCommand){


int recordId = Integer.parseInt("" +
idVec.elementAt(list.getSelectedIndex()));

String sRec = pb.getRec(recordId);//gets record at


// specific id
int index = sRec.indexOf(";"); //gets the index of
// the semi colon
/* uses the index value to break up the string */
String name = sRec.substring(0,index);
String number = sRec.substring(index + 1,
sRec.length());

numberItem.setText(number);
form2.setTitle(name);
display.setCurrent(form2); //displays the form with
// the number

}else if(c == deleteCommand){


int recordId = Integer.parseInt("" +
idVec.elementAt(list.getSelectedIndex()));
pb.deleteRec(recordId);//send the id to PhoneBookDB
// to be deleted
listOfNames();
}
}
public void listOfNames(){

/* gets the RecordEnumeration from the PhoneBookDB


class */
RecordEnumeration en = pb.listNumbers();
list.deleteAll(); // clears the list screen
try{

vec = new Vector(); //creates a new Vector for names


idVec = new Vector();//creates a vector for indexes
Vector temp = new Vector(); //a temporary vector

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 91

/* loops through each record; adds them to vector */


while(en.hasNextElement()){
vec.addElement(new String(en.nextRecord()));
}
en.reset(); //reset the enumeration to the beginning

/* loops through the record ids and adds them to a


temporary vector */
while(en.hasNextElement()){
temp.addElement("" +en.nextRecordId());
}

/* inverts the records and record ids */


for(int i = vec.size() - 1;i >= 0; i--){
idVec.addElement(temp.elementAt(i));
String record = vec.elementAt(i).toString();
int index = record.indexOf(";");
String name = record.substring(0,index);
String number = record.substring(index+1,
record.length());
list.append(name, phoneImage);
}
}catch(RecordStoreException rse){
System.err.println("Error " + rse);
}
}
}
Example 6.7 – MyPhoneBook

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 class BookingSystem extends MIDlet implements


CommandListener{

private Display display;

private Form insertForm;


private Form viewForm;
private Command insertCommand;
private Command exitCommand;

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 92

private Command backCommand;


private Command viewCommand;

private DateField timeField;


private TextField nameField;
private TextField numField;

private Date time;


Calendar cal;
BookingSystemDB bsDB;

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: ");

timeField = new DateField("Time: ", DateField.TIME);


nameField = new TextField("Name: ", "", 25 ,
TextField.ANY);
numField = new TextField("Number: ", "", 15,
TextField.PHONENUMBER);

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);

/* instantiates the BookingSystemDB class */


bsDB = new BookingSystemDB();
}

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 93

/* display the first screen to the user */


public void startApp() throws MIDletStateChangeException{
display.setCurrent(insertForm);
}

public void pauseApp(){


}

public void destroyApp(boolean unconditional) throws


MIDletStateChangeException{}
public void commandAction(Command c, Displayable d){

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();

bsDB.insertRecord(record); //adds record to


// recordstore
getBookings();
viewForm.setTitle("The time is " +
getCurrentTime());
display.setCurrent(viewForm);
}

} else if(c == exitCommand){


bsDB.closeDB(); //close the database
try{
destroyApp(false);
}catch(MIDletStateChangeException msce){}
notifyDestroyed();

} else if(c == backCommand){

nameField.setString(""); //clear the fields


numField.setString("");

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 94

display.setCurrent(insertForm); //displays the


// first screen

} else if(c == viewCommand){


getBookings();
viewForm.setTitle("The time is " +
getCurrentTime());
display.setCurrent(viewForm);
}
}

/* method to get the current time and put it in the format


HH:MM */
public String getCurrentTime(){
cal = Calendar.getInstance();
return cal.get(Calendar.HOUR) + ":" +
cal.get(Calendar.MINUTE);
}

/* gets the booking for the current hour */


public void getBookings(){
/* gets the RecordEnumeration from the BookingSystem
class */
RecordEnumeration en = bsDB.listBookings();
viewForm.deleteAll(); // clears the form
viewForm.append(new StringItem("Bookings for this hour
are:",""));
String currTime = getCurrentTime();
//gets the current time

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

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 95

import javax.microedition.rms.*;
import java.util.*;

public class BookingSystemDB{


RecordStore recordStore = null;

/* creates a record store named PhoneBook */


public BookingSystemDB(){
try{
recordStore = RecordStore.openRecordStore(
"Bookings",true);
}catch(RecordStoreException rse){
System.err.println("Error " + rse);
}
}
/* adds the record that was passed as the recordData
argument to the record store */
public void insertRecord(String recordData){
byte[] bytes = recordData.getBytes();
try{
recordStore.addRecord(bytes, 0 ,bytes.length);
}catch(RecordStoreException rse){
System.err.println("Error " + rse);
}
}

/* enumerates the records; returns a RecordEnumeration */


public RecordEnumeration listBookings(){
try{
return recordStore.enumerateRecords(null, null,
false);
}catch(RecordStoreNotOpenException rsnoe){
System.err.println("Error " + rsnoe);
return null;
}
}

/* closes the database */


public void closeDB(){
try{
recordStore.closeRecordStore();
}catch(RecordStoreException rse){
System.err.println("Error " + rse);
}
}
}
Example 6.9 – BookingSystemDB.java

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 96

6.2 Answers to revision questions

6.2.1 Section 6.2.7


1. Which of the following are the life cycle methods of a MIDlet?

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.

3. True/False: Pre-verification takes place in the KVM.

6.2.2 Section 6.3.8


1. In which directory should sounds be saved for a MIDlet created in KToolBar?

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.

3. True/False: To emulate a device in KToolBar you do not need to package it first.

6.2.3 Section 6.4.8


1. Which one of the following is not found in the MIDP API?

A. javax.microedition.midlet.*;
B. javax.microedition.swing.*;
C. javax.microedition.rms.*;
D. javax.micoredition.pki.*;

2. True/False: The MIDlet class is an abstract class.

3. True/False: The java.io package in standard Java contains the same classes as the
javax.micoredition.io package.

6.2.4 Section 6.5.8


1. Which one of the following methods do you use to include items on a form?

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 97

A. setComponent()
B. add()
C. include()
D. append()

2. True/False: You can draw shapes on a Screen object.

3. True/False: Multiple values can be selected in a List.

6.2.5 Section 6.6.6


1. The most import type of optimization is:

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.

6.3 Answers to test your knowledge

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.

3. Which one of the following is not a wireless technology?

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.

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 98

B. Only predefined CLDC Java APIs can be used.


C. No user-defined class loaders are allowed to be used.
D. Only native features that are described by the CLDC can be accessed.

6. True/False: The Wireless Toolkit contains two command-line tools – the bytecode verifier
and the J2ME emulator.

7. True/False: The following code will compile.

form = new Form("HelloJava");


StringItem si = new StringItem("","Hello Java");
form.add(si);

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.

© CTI Education Group


Java 5 B – Instructor Guide: Unit 6 Page 99

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

17. Which one of the following is not a List type?

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.

19. Which one of the following components cannot be used on a form?

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?

A. Avoid using objects whenever possible.


B. Rather use arrays than vectors.
C. Recycle objects when using them.
D. Clean up objects that are no longer in use.

24. True/False: The HTTPConnection interface from the MIDP API is a request-response
protocol which supports HTTP.

© CTI Education Group

You might also like