Home > Articles > Programming > Java

Like this article? We recommend

Walkthrough

Let's step through a typical user session. We assume our real estate agent is on the road, using her mobile phone to access our Real Estate Assistant service. For ease of illustration, we use a phone simulator (available from Openwave) to show user interaction.

Authentication

The agent logs onto our system from her browser, using a bookmarked URL containing our address, and specifies a parameter OP=getQuery. The Real Estate Assistant URL is protected by the following configuration, as defined in our application's deployment descriptor:

<!-- ACL -->
<security-constraint>
 <web-resource-collection>
  <web-resource-name>MLS Application</web-resource-name>
  <url-pattern>/query</url-pattern>
 </web-resource-collection>
 <auth-constraint>
  <role-name>agent</role-name>
 </auth-constraint>
</security-constraint>

<login-config>
 <auth-method>BASIC</auth-method>
 <realm-name>Authentication Area</realm-name>
</login-config>

This XML snippet defines a security constraint that applies to the specified URL pattern (/query), the URL of our servlet. The login configuration that follows specifies HTTP Basic authentication, supplying a realm name for optional display by the client. Note that this form of authentication has a low level of security but is probably adequate for publicly accessible information such as our property data.

Servlet Controller

Once the agent has entered her username and password, the request will be sent to the HttpServlet running within our application server's servlet container. The following code handles this request:

/**
 * Parse out the operation and call the appropriate method.
 * @param request the Http request from the user agent
 * @param response where the response is to be written
 */
public void doGet(HttpServletRequest request,
 HttpServletResponse response) throws IOException, ServletException {

 // Select viewer based on request headers
 Viewer viewer = htmlViewer;
 if (isWapUser(request))
  viewer = wmlViewer;

 /* ensure we have an authenticated user */
 String user = request.getRemoteUser();
 if (null == user) {
   /* encode a redirect to the "unauthorised access" deck,
    N.B. this could be caused by the authentication header not
    being passed to us, or incorrect web server - servlet engine
    integration */
   viewer.viewError(request, response, Errors.UNAUTHORISED_USER);
   return;
 }
 ...

The doGet operation first selects the right viewer for this agent by calling a method that returns true if this is a WAP user. The isWapUser method is very simple and assumes that "WML" will be present in the HTTP Accept header for all WAP users:

/**
 * Return true if this request is from a WAP user agent
 * @param request the Http request from the user agent
 * @return true if this request is from a WAP user agent
 */
private boolean isWapUser(HttpServletRequest request) {
 String acceptHeader = request.getHeader("Accept").toUpperCase();
 return acceptHeader.indexOf("WML") >= 0;
}

Next, the method makes sure that this agent has been properly authenticated by the "built-in" HTTP Basic authentication, by checking the getRemoteUser parameter in the agent's request.

To satisfy the agent's request, the servlet must determine which workflow operation has been requested. It does this by retrieving the parameter from the request:

String operation = request.getParameter("OP");

If an operation was not specified, an error message is displayed:

viewer.viewError(request, response, Errors.BAD_OPERATION);

Viewing Errors

The viewer object (either an HTML or WML viewer) has overloaded viewError methods that display simple text error messages. The following code from the Viewer parent class shows one of these methods:

/**
 * Display an error page containing the specified error message and
 * error (throwable) information
 * @param request the Http request from the user agent
 * @param response where the response is to be written
 * @param error an error message to display
 * @param throwable An error from which additional info will be
 * displayed
 */
public void viewError(HttpServletRequest request,
           HttpServletResponse response,
           String error,
           Throwable throwable) throws IOException {
 setType(response);
 String msg = ERROR + error;
 if (throwable != null)
  msg += ": " + throwable.toString();
 viewFixed(response, msg);
}

This method (defined in the WmlViewer child class) sets the type (in our case, to Wireless Markup Language):

response.setContentType("text/vnd.wap.wml");

It then builds an error message with and calls viewFixed (defined in the WmlViewer class) to display this:

/**
 * View a canned page
 * @param response where the response is to be written
 * @param textToDisplay the text to display
 */
protected void viewFixed(HttpServletResponse response,
             String textToDisplay) throws IOException {

 PrintWriter out = response.getWriter();
 printPrologue(out);
 out.println("<wml><card><p>");
 out.println(textToDisplay);
 out.println("</p></card></wml>");
}

Operation Processing

Assuming all is well with our request and it specified an OP parameter, doGet attempts to locate a method by this name in the workflow object. It uses Java's reflection capabilities to invoke this method, allowing us to alter the workflow without breaking the servlet:

// invoke operation method using reflection
try {
 // set parameters for operation method
 java.lang.Class[] parameterTypes
  = {Class.forName("javax.servlet.http.HttpServletRequest"),
    Class.forName("javax.servlet.http.HttpServletResponse"),
    Class.forName("mls.view.Viewer")};
 java.lang.reflect.Method operationMethod
  = workflow.getClass().getMethod(operation, parameterTypes);

 if (null == operationMethod)
  viewer.viewError(request, response, Errors.BAD_OPERATION);
 else {
  java.lang.Object[] args = {request, response, viewer};
  operationMethod.invoke(workflow, args);
 }
} catch (java.lang.reflect.InvocationTargetException it) {
  viewer.viewError(request, response, Errors.ERROR_PERFORMING_OP,
          it.getTargetException());
} catch (Exception e) {
  viewer.viewError(request, response, Errors.ERROR_PERFORMING_OP, e);
}

The operationMethod.invoke call will execute the getQuery method in Workflow:

/**
 * Operation method to display a query entry page
 * @param request the Http request from the user agent
 * @param response where the response is to be written
 * @param viewer a viewer to display the output
 */
public boolean getQuery(HttpServletRequest request,
            HttpServletResponse response,
            Viewer viewer) throws IOException {
 try {
  viewer.viewPage(request, response, QUERY_PAGE,
          QUERY_CLASS, Viewer.NO_CACHE);
 }
 catch (Exception e) {
  viewer.viewError(request, response, Errors.ERROR_MAKING_QUERY, e);
 }
 return true;
}

Viewing the Query Page

The getQuery operation displays a new Wireless Markup Language query page via a call to the WmlViewer. WmlViewer creates an empty query object and merges this object with a query template:

/** Display the specified page containing the specified object
 * @param request the Http request from the user agent
 * @param response where the response is to be written
 * @param templateName the name of the XML template
 * @param object the object to view
 */
public void viewPage(HttpServletRequest request,
           HttpServletResponse response,
           String templateName,
           java.lang.Object object,
           String cachePage) throws Exception {
 setType(response);
 setCache(cachePage, response);
 PrintWriter out = response.getWriter();

 printPrologue(out);

 try {
  merge(object, TEMPLATE_DIR + templateName, out);
 } catch (Exception e) {
  viewError(request, response, Errors.MERGE_ERROR, e);
 }
}

This method is actually called by a thin wrapper of the same name that accepts a class name and builds a new instance of the class as the object parameter. ViewPage sets the response type (discussed earlier) and the cache header:

  if (cachePage.equals(NO_CACHE)) {
   response.setHeader("Cache-Control", "no-cache, must-revalidate");
   response.setHeader("Pragma", "no-cache");
  }
  ...
  response.setHeader("forua", "true");

A WML prologue is generated:
  out.println(XML_PROLOGUE);
  out.println(mls.common.Config.WML_PROLOGUE);

Finally, merge is called to do the actual XSLT processing of the new query object:

/**
 * Generate XML from the specified data and XSL style sheet
 * @param xml a Java object containing data
 * @param xsl an XSL style sheet file which will generate
 * appropriate markup
 * @param out an output print writer
 */
private void merge(java.lang.Object data, String xsl, PrintWriter out)
throws Exception {
 merge(parseString(TranslatingXmlObject.object2Xml(data)), 
          parse(xsl), out);
}

Merging XSL and XML

merge is an overloaded method, and the one that we call translates the specified object into an XML document before calling the general-purpose merge:

/**
 * Generate XML from the specified XML data and XSL style sheet
 * @param xml a DOM document containing data as XML
 * @param xsl an XSL style sheet which will generate 
 * appropriate markup
 * @param out an output print writer
 */
private void merge(Document xml, Document xsl, PrintWriter out)
throws Exception{
 XSLTProcessor processor =
  XSLTProcessorFactory.getProcessor(
   new org.apache.xalan.xpath.xdom.XercesLiaison());
 XSLTInputSource data = new XSLTInputSource(xml);
 XSLTInputSource layout = new XSLTInputSource(xsl);
 XSLTResultTarget target = new XSLTResultTarget(out);
 processor.process(data, layout, target);
}

This method uses the Apache project's XSLT processor, Xerces, to process a query XSL style sheet as defined in Listing 1 (click here to download the listing files for this article). Listing 1 defines a single XSL template with a root rule that generates a WML deck with a single card. If you're unfamiliar with either WML or XSL syntax, see the InformIT articles Wireless Markup Language, Wireless Markup Language - Beyond the Basics, and XSL Transformations.

Post field tags ensure that the correct operation (doQuery) and the required user inputs will be passed to our servlet. The servlet URL is specified (in our test system, this is running on a WebLogic server at port 7001 of the fictional URL http://www.mls123).

Three drop-down select lists are defined, and their values are pulled out of the specified query data structure. For example, the minimum price selection list is defined by an xsl:element element that will result in the generation of a <select> element with its value attribute set from the minPrice field of a Query object:

<!-- Minimum price input field -->
Min Price:
<xsl:element name="select">
 <xsl:attribute name="name">min</xsl:attribute>
 <xsl:attribute name="value">
  <xsl:value-of select="Query/minPrice"/>
 </xsl:attribute>
 <option value="0">No Limit</option>
 <option value="10000">$$10,000</option>
  ...
 <option value="300000">$$300,000</option>
</xsl:element>

Similarly, we define a maximum price drop-down list and a property type list. Note the use of $$, as $ is a reserved character in WML and must be escaped. The merge method processes this style sheet against the empty query object and produces a WML deck, as shown in Figure 1. The deck is presented as a series of screens—one for each select list. Once the final item has been selected, the agent submits this query for processing.

Figure 1 Mobile interface query.

Processing the Query

As in our agent's initial request, HttpServlet and Workflow objects control the query processing. This time, the doQuery method is called:

 /**
  * Operation method to do a query. If the returned results are
  * larger than the resultsPerPage, these results are saved in the
  * user's session for later use - see #fetchNext()
  * @param request the Http request from the user agent
  * @param response where the response is to be written
  * @param viewer a viewer to display the output
  * @return true
  */ public boolean doQuery(HttpServletRequest request,
             HttpServletResponse response,
             Viewer viewer) throws IOException {
  try {
   Query query = new Query();
   query.setMinPrice(request.getParameter("min"));
   query.setMaxPrice(request.getParameter("max"));
   query.type = request.getParameter("type");

   // Get number of results to display per page
   int resultsPerPage = getNewResultsPerPage(request);

   if (query.isValid()) {
    Results results = MlsBusinessObject.doQuery(query);
    if (results.properties.length > resultsPerPage) { // save
     request.getSession().setAttribute(LAST_RESULTS, results);
     Results subset = results.getSubset(0, resultsPerPage);
     viewer.viewPage(request, response, RESULTS_PAGE,
      subset, Viewer.CACHE);
    }
    else
     viewer.viewPage(request, response, RESULTS_PAGE,
      results, Viewer.CACHE);
   }
   else {
    viewer.viewError(request, response, 
             Errors.ERROR_IN_QUERY_PARAMS);
   }
  }
  catch (Exception e) {
   viewer.viewError(request, response, 
            Errors.ERROR_DOING_QUERY, e);
  }
  return true;
 }

doQuery creates a query object and initializes this from the submitted parameters in the request object. If applicable, the number of properties to display per page is also set (this is only set by a web user). Next, the query parameters are validated and the Multiple Listing Service is called to do the query. If too many results are returned to fit on one page, a subset of the results is displayed by a call to the viewer.

Displaying the Results

The results style sheet is shown in Listing 2 in the listing files for this article. Note that the link definition around line 30 has been split across two lines to make it readable; this would need to be "reassembled" for actual XSLT processing. Once again, this style sheet has only a single root template that produces a WML deck. This time, however, we may produce multiple cards, if there are any results to display.

We begin by defining a results variable that contains a complete list of all properties. Next, we declare a results card; if there are no results (<xsl:when test="count($matches)=0">), we let the agent know this. If there are results, the style sheet iterates over the matches and builds a link that displays the property's address and links to a details card within this WML deck. The unique MLS identifier from the property data identifies the detail card.

Next, the style sheet tests whether there are more results by checking a flag set in the results XML; it then builds a Next link if required. (The next article discusses the function of this link.) The last element added to this card is a Requery link that goes back to the getQuery operation.

The detail cards are generated by looping over all matched properties and displaying either land or property details, depending on the property type. Each of these cards displays a street and price and contains a navigation widget to return to the summary Results card. Figure 2 illustrates the results of an MLS query.

Figure 2 Mobile interface results screens.

The Test XML Data

As mentioned above, the prototype for this system uses an XML test file as its MLS "database." A test set of real estate properties is shown in Listing 3 in the listing files for this article. Results.xml declares two land-only properties and six single-family dwellings, all in the same geographic area. Note that these XML elements map directly to the Java domain classes, Results, Property, Address, and Lot.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020