Welcome!

Machine Learning Authors: Elizabeth White, Liz McMillan, Jack Jachner, Pat Romanski, Progress Blog

Related Topics: Machine Learning , Java IoT

Machine Learning : Article

JavaServer Faces and AJAX for Google Fans

Create your own custom components and build RIAs

This is our last article in a series of four that have been introducing the concepts of creating AJAX-enabled JavaServer Faces (JSF) components. In this article we are going to summarize and encapsulate the concepts that were introduced in the three previous JDJ articles starting with the "Rich Internet Components with JavaServer Faces" (Vol. 10, issue 11), and design a Google-like JDJ InputSuggest component.

We will show you how to use Mabon to create a simple and powerful input component with built-in suggest functionality similar to what Google Suggest provides. To make it easy for application developers to use our JDJ InputSuggest component, we are going to use the Weblets open source project to bundle external resources, such as icons and JavaScript libraries, into a Java archive (JAR) that represents our JSF component bundle.

Creating an AJAX-Enabled JSF Input Suggest Component
The JSF AJAX input suggest solution consists of four classes as shown in Figure 1.

These classes are as follows:

  • The HtmlInputSuggest is the renderer-specific subclass.
  • The HtmlRenderer superclass provides some convenient methods for encoding resources.
  • The HtmlInputSuggestRenderer is your new custom Renderer, which is in charge of the markup rendered to the client, including resources needed such as JavaScript libraries and style sheets.
  • The HtmlInputSuggestTag is the tag handler.
The part of our input suggest solution that will provide the richness is a JavaScript library - inputSuggest.js - that contains functions needed to leverage Mabon to retrieve data from the application developer's backing bean. We'll focus on the following artifacts - the inputSuggest.js file and the HtmlInputSuggestRenderer - both impacted by Mabon and provide the input field with type-ahead and suggest list functionality.

The Input Suggest JavaScript Library
Since we use Mabon, there is no need to worry about fetching data from the backing bean. We can leave this to Mabon. What we do need to be concerned about, though, is how to handle the returned data on the XMLHttpRequest object, how to populate the actual suggest list, and how to handle user interactions. The inputSuggest.js library contains a number of functions that are used to handle keyboard navigation and mouse interactions, and for space limitations we'll be focusing on the functions that have the most impact on the JSF HtmlInputSuggest component.

The doKeyPress Function
The doKeyPress function, as shown in Listing 1, handles keypress events and checks whether the user pressed the TAB key or not. The TAB key would, under normal circumstances, navigate out of the input field and raising the blur event. For an input suggest solution, a TAB key can also be used to select an active row in the list of suggestions and as such we need to trap the TAB key and select a row in the suggest list and add the value to the input field, or, if no list is available, navigate out of the input field. If navigation occurs, the doBlur() function will be invoked and close the list of suggestions.

The doKeyUp Function
This function is invoked on any keyup event, and, depending on which key was activated, it will perform certain actions. Even though the TAB key has been managed by the doKeyPress function, we still have to make sure to catch it and terminate the process.

Another aspect of key strokes is the UP and DOWN arrow keys. Normally these keys will cause the cursor to navigate left and right in a regular input field. With an input suggest component a user is expecting these keys to navigate the list of suggestions.

The doKeyUp function's most important part, for this article, is to catch all key strokes that end up with a new character entered in the input suggest field, and is not a Backspace (see Listing 2). In this case the doKeyUp function will invoke the blur() function, which evaluates the value entered by the user and if changed raise a change event. We also have to reset the focus to the input suggest field, input.focus(), so the user can continue to enter more text.

If a user enters a new value, the doChange() function is invoked (see Listing 3). The doChange() function will call the mabon.send() function, passing a Map containing information about the value entered by the user, the JSF managed bean to invoke, and the callback function for this solution - _callback().

The _callback function, as shown in Listing 4, is responsible for handling the returned result from the response object and creating a list with suggestions according to the value entered by the user. Since we asynchronously communicate with the server, there is a chance that the user has entered a new character before the response comes back. To ensure that we can handle this, we have added a timer that delays the type-ahead feature until a certain time has passed.

If the value has changed since the request was made or the value is the same as the suggested value, we do nothing (see Listing 5). If the value is the same as the initial value entered, we add the first suggested value in the list to the input field and highlight the part that is appended to the value entered by the user.

The HtmlInputSuggestRenderer
It's time to have a look at how we can leverage the client-side functionality provided by the inputSuggest.js library and encapsulate it into one single JSF component. In this sample the main player is the JSF Renderer - HtmlInputSuggestRenderer. The Renderer is responsible for making sure that the correct markup is written to the client including any references to additional resources such as JavaScript libraries, CSS, icons, etc.... As we described in our previous JDJ article - "JSF and AJAX: Introducing a new open source project" (Vol. 11, issue 1) - you can use Weblets to package these resources into the same library as your JSF components.

Using Weblets
The open source Weblets project (http://weblets.dev.java.net) aims to solve the resource-packaging problem in a generic and extensible way so that all JSF component writers can leverage it, and it places no additional installation burden on the application developer.

A Weblet acts as a mediator that intercepts requests from the client and uses short URLs to serve resources from a JAR file. Unlike the servlet or filter approach, a Weblet can be registered and configured inside a JAR file, so the component library renderers, their resource files, and the Weblet configuration file (weblets-config.xml) can all be packaged together in the same JAR file. You don't need to separately deploy additional installables when the component libraries are upgraded to new versions. For the application developer, no configuration steps are needed.

It's important to note that all resources served up by Weblets are internal resources, used only by the Renderer. Any resources, such as images, that are provided by the application are supplied as component attribute values and loaded from the context root as external resources.

The HtmlInputSuggestRenderer Class
The two most important methods in this HtmlInputSuggestRenderer are the encodeBegin() and encodeEnd() methods. The encodeBegin() method, as shown in Listing 6, is responsible for writing out the needed resources for this component. The writeScriptResource() method and writeStyleResource() method are convenience methods provided by the HtmlRenderer and provide "write-only-once" semantics, preventing the same library from being written multiple times in case the application developer adds more than one input suggest component to the page.

Using Mabon
Mabon is an open source project hosted on the http://mabon.dev.java.net Web site. Mabon offers a convenient way to hook in a specially designed life cycle that is ideal for AJAX-enabled components that need to fetch data directly from a backing bean, without the overhead of a full JSF life cycle. It also provides a Mabon protocol - mabon:/ - that is used to reference the backing bean and a JavaScript convenience function that is used to send the target URL and any arguments needed and then asynchronously receive data from the managed bean.

Mabon and JSON
As you know, the XMLHttpRequest provides two response types - responseText and responseXML - that can be used to fetch data. The question to ask is, when should I use each? Answers to this question can differ depending on whom you ask, but we can recommend one rule. Ask yourself whether you control the syntax of the response.

The responseXML type returns a complete DOM object (which gives you ample ways of walking the DOM tree), allowing you to find the information needed and apply changes to the current document. This is useful when your component will impact surrounding elements and you don't control the response (for example, when you're communicating with a Web service).

For the input suggest component, you do control the response and you are looking at only fetching data for your component, not modifying the whole page's DOM structure. The responseText type returns plain text, which allows you to leverage JSON syntax for the response. For components leveraging AJAX, JSON is an extremely useful data-interchange format, since it can be easily parsed with the eval() function.

The eval() function takes one argument, a string of JavaScript code, and parses and executes this string in one go rather than trying to process each part separately. This is significantly faster than any other type of parsing, such as XML DOM parsing.

This is the reason why Mabon implements JSON - you control the response, and JSON syntax is easy and fast to parse.

The encodeEnd() Method
The real "work" is done in the encodeEnd() method, as shown in Listing 7. In the encodeEnd() method we get the Map of attributes from the HtmlInputSuggest component. One of the attributes on this component is the doSuggest attribute. From this attribute we can get hold of the MethodBinding, if any, and from the MethodBinding object we can get hold of the actual MethodBinding expression defined by the application developer, for example, #{backingBean.doSuggest}. We then trim the #{} from the expression and concatenate the remainder of the string with the mabon:/ protocol-like syntax. The MabonViewHandler will recognize the string and return a resource URL that will be written to the client (for example, /context-root/mabon-servlet-mapping/backingBean.doSuggest).

Using the Input Suggest Component
Creating an AJAX solution is not a simple task, although there are several AJAX toolkits available, such as the Dojo Toolkit (www.dojotoolkit.org), that make it a lot easier. What JSF can offer is an even simpler programming model and one that is known by millions of developers: JSP and Java. To finish this article off in a fashion that suits a proper Ajax solution, let's look at how you can use this input suggest component in a JSF application, as shown in Listing 8.

This page contains one HtmlInputSuggest component, <jdj:inputSuggest>, that has the value attribute set to a value binding expression. This expression is pointing to a value property on the backing bean. The doSuggest attribute contains a method binding expression pointing to a doSuggest() method on the same backing bean. Let's have a look at the backing bean, as shown in Listing 9.

The value property is just a plain old JavaBean property. The doSuggest() method, as shown in Listing 10, is a bit more interesting. This method takes the initial value entered by the user and passed to it via Mabon from the doChange() function (see Listing 3). The doSuggest() method then returns an Array filtered based on the users initial value to the client. It is important that the returned value conforms to the supported JSON syntax.

The end result of this HtmlInputSuggest component looks like Figure 2.

Conclusion
From this article, we hope you have gained an understanding of how to Ajax-enable data fetch for your JSF components using Mabon, and how you can package external resources needed for your JSF component into the same archive as your Java classes leveraging the Weblets project.

Finally, now that you know how to create reusable rich Internet components with JSF and AJAX, we hope you will apply the techniques you have learned in this article series to create your own custom components and build Rich Internet Applications (RIAs) with JSF.

THIS ARTICLE IS BASED ON, AND CONTAINS EXCERPTS FROM, THE BOOK PRO JSF AND AJAX: BUILDING RICH INTERNET COMPONENTS BY JONAS JACOBI AND JOHN FALLOWS, PUBLISHED BY APRESS.

More Stories By Kaazing Blog

Kaazing is helping define the future of the event-driven enterprise by accelerating the Web for the Internet of Things.

More Stories By John Fallows

John brings to Kaazing his 17 years’ experience in technology development and software design, and is considered a pioneer in the field of rich and highly interactive user interfaces. As CTO he formulates Kaazing Corporation’s vision of enabling mobile users, marketplaces and machines to connect and communicate in real-time, more reliably and at unprecedented scale. He defines the architecture of the Kaazing product suite and oversees its development. Prior to co-founding Kaazing, John served as Architect for Brane Corporation, a startup company based in Redwood City, California. Before joining Brane, he was a Consulting Member of Technical Staff for Server Technologies at Oracle Corporation. During his last five years at Oracle, he focused on designing, developing, and evolving Oracle ADF Faces to fully integrate Ajax technologies. Originally from Northern Ireland, he received his MA in Computer Science from Cambridge University in the United Kingdom and has written several articles for leading IT magazines such as Java Developer’s Journal, AjaxWorld Magazine, and JavaMagazine (DE), and is a popular speaker at international conferences. He is co-author of the bestselling book Pro JSF and Ajax: Building Rich Internet Components (Apress).

Comments (3) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Hardik Tank's Weblog 05/05/06 02:23:23 AM EDT

Trackback Added: JavaServer Faces and AJAX for Google Fans; JavaServer Faces and AJAX for Google Fans
? This is our last article in a series of four that have been introducing the concepts of creating AJAX -enabled JavaServer Faces (JSF) components. In this article we are going to summarize and encapsulate the

SYS-CON Italy News Desk 04/18/06 10:22:28 AM EDT

This is our last article in a series of four that have been introducing the concepts of creating AJAX-enabled JavaServer Faces (JSF) components. In this article we are going to summarize and encapsulate the concepts that were introduced in the three previous JDJ articles starting with the 'Rich Internet Components with JavaServer Faces' (Vol. 10, issue 11), and design a Google-like JDJ InputSuggest component.

AJAX News Desk 04/18/06 10:08:29 AM EDT

This is our last article in a series of four that have been introducing the concepts of creating AJAX-enabled JavaServer Faces (JSF) components. In this article we are going to summarize and encapsulate the concepts that were introduced in the three previous JDJ articles starting with the 'Rich Internet Components with JavaServer Faces' (Vol. 10, issue 11), and design a Google-like JDJ InputSuggest component.

@CloudExpo Stories
Blockchain is a shared, secure record of exchange that establishes trust, accountability and transparency across business networks. Supported by the Linux Foundation's open source, open-standards based Hyperledger Project, Blockchain has the potential to improve regulatory compliance, reduce cost as well as advance trade. Are you curious about how Blockchain is built for business? In her session at 21st Cloud Expo, René Bostic, Technical VP of the IBM Cloud Unit in North America, will discuss th...
The question before companies today is not whether to become intelligent, it’s a question of how and how fast. The key is to adopt and deploy an intelligent application strategy while simultaneously preparing to scale that intelligence. In her session at 21st Cloud Expo, Sangeeta Chakraborty, Chief Customer Officer at Ayasdi, will provide a tactical framework to become a truly intelligent enterprise, including how to identify the right applications for AI, how to build a Center of Excellence to ...
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
While some vendors scramble to create and sell you a fancy solution for monitoring your spanking new Amazon Lambdas, hear how you can do it on the cheap using just built-in Java APIs yourself. By exploiting a little-known fact that Lambdas aren’t exactly single-threaded, you can effectively identify hot spots in your serverless code. In his session at @DevOpsSummit at 21st Cloud Expo, Dave Martin, Product owner at CA Technologies, will give a live demonstration and code walkthrough, showing how ...
SYS-CON Events announced today that Elastifile will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Elastifile Cloud File System (ECFS) is software-defined data infrastructure designed for seamless and efficient management of dynamic workloads across heterogeneous environments. Elastifile provides the architecture needed to optimize your hybrid cloud environment, by facilitating efficient...
As DevOps methodologies expand their reach across the enterprise, organizations face the daunting challenge of adapting related cloud strategies to ensure optimal alignment, from managing complexity to ensuring proper governance. How can culture, automation, legacy apps and even budget be reexamined to enable this ongoing shift within the modern software factory?
There is only one world-class Cloud event on earth, and that is Cloud Expo – which returns to Silicon Valley for the 21st Cloud Expo at the Santa Clara Convention Center, October 31 - November 2, 2017. Every Global 2000 enterprise in the world is now integrating cloud computing in some form into its IT development and operations. Midsize and small businesses are also migrating to the cloud in increasing numbers. Companies are each developing their unique mix of cloud technologies and service...
SYS-CON Events announced today that Golden Gate University will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Since 1901, non-profit Golden Gate University (GGU) has been helping adults achieve their professional goals by providing high quality, practice-based undergraduate and graduate educational programs in law, taxation, business and related professions. Many of its courses are taug...
@DevOpsSummit at Cloud Expo taking place Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center, Santa Clara, CA, is co-located with the 21st International Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is ...
DevOps at Cloud Expo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to w...
SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
SYS-CON Events announced today that Grape Up will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct. 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Grape Up is a software company specializing in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market across the U.S. and Europe, Grape Up works with a variety of customers from emergi...
With Cloud Foundry you can easily deploy and use apps utilizing websocket technology, but not everybody realizes that scaling them out is not that trivial. In his session at 21st Cloud Expo, Roman Swoszowski, CTO and VP, Cloud Foundry Services, at Grape Up, will show you an example of how to deal with this issue. He will demonstrate a cloud-native Spring Boot app running in Cloud Foundry and communicating with clients over websocket protocol that can be easily scaled horizontally and coordinate...
From 2013, NTT Communications has been providing cPaaS service, SkyWay. Its customer’s expectations for leveraging WebRTC technology are not only typical real-time communication use cases such as Web conference, remote education, but also IoT use cases such as remote camera monitoring, smart-glass, and robotic. Because of this, NTT Communications has numerous IoT business use-cases that its customers are developing on top of PaaS. WebRTC will lead IoT businesses to be more innovative and address...
21st International Cloud Expo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy. Me...
In his session at 20th Cloud Expo, Scott Davis, CTO of Embotics, discussed how automation can provide the dynamic management required to cost-effectively deliver microservices and container solutions at scale. He also discussed how flexible automation is the key to effectively bridging and seamlessly coordinating both IT and developer needs for component orchestration across disparate clouds – an increasingly important requirement at today’s multi-cloud enterprise.
DevOps at Cloud Expo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to w...
Vulnerability management is vital for large companies that need to secure containers across thousands of hosts, but many struggle to understand how exposed they are when they discover a new high security vulnerability. In his session at 21st Cloud Expo, John Morello, CTO of Twistlock, will address this pressing concern by introducing the concept of the “Vulnerability Risk Tree API,” which brings all the data together in a simple REST endpoint, allowing companies to easily grasp the severity of t...
Recently, WebRTC has a lot of eyes from market. The use cases of WebRTC are expanding - video chat, online education, online health care etc. Not only for human-to-human communication, but also IoT use cases such as machine to human use cases can be seen recently. One of the typical use-case is remote camera monitoring. With WebRTC, people can have interoperability and flexibility for deploying monitoring service. However, the benefit of WebRTC for IoT is not only its convenience and interopera...
Any startup has to have a clear go –to-market strategy from the beginning. Similarly, any data science project has to have a go to production strategy from its first days, so it could go beyond proof-of-concept. Machine learning and artificial intelligence in production would result in hundreds of training pipelines and machine learning models that are continuously revised by teams of data scientists and seamlessly connected with web applications for tenants and users.