Welcome!

Machine Learning Authors: Elizabeth White, Leon Adato, Jack Jachner, Pat Romanski, Progress Blog

Related Topics: Machine Learning , Java IoT

Machine Learning : Article

Super-Charge JSF AJAX Data Fetch

Harnessing managed beans

In our last article - "JSF and AJAX" (JDJ, Vol. 11, issue 1) - we discussed how JavaServer Faces component writers can take advantage of the new Weblets Open Source project (http://weblets.dev.java.net) to serve resources such as JavaScript libraries, icons, and CSS files directly from a Java Archive (JAR) without impacting the application developer.

In this article we'll address the need to fetch data using AJAX with JavaServer Faces (JSF) components. The most common use cases for fetching data with AJAX are to populate dropdown lists and add type-ahead functionality in text fields. In contrast to using AJAX postbacks for events, fetching data shouldn't affect the surrounding components on the page. And if fetching data isn't affecting other parts of the DOM tree, then you don't have to go through the full JSF lifecycle just to get the data, right?

This article introduces for the first time a new Open Source project called Mabon hosted on the Java.net Web site (http://mabon.dev.java.net). Mabon stands for Managed Bean Object Notation and its goal is to provide component writers of AJAX-enabled JSF components to access JSF managed beans outside the scope of the standard JSF lifecycle by using a JSON-syntax communication channel.

In essence, Mabon provides application developers with a standard and easy way to provide data to AJAX-enabled components using the managed bean facility provided by the JSF specification.

Fetching Data with AJAX
Fetching data the conventional way versus using AJAX follows the same basic concept - it shouldn't have the side effect of changing the state of surrounding components.

Figure 1 shows an AJAX sequence diagram using the HTTP GET method. The W3C recommends that you use the HTTP GET method to fetch data when there are no side effects requested by the user (for example, Google Suggest).

Different JSF AJAX Approaches
If you get no side effects, then there's no change to the JSF component hierarchy; so there's no need to go through the JSF lifecycle. But, if you want to reuse a managed bean method, the easiest way to get to it is via the JSF MethodBinding facility. Three solutions exist to support this - adding functionality to the Renderer, using a PhaseListener, and providing a new JSF Lifecycle.

The Renderer Approach
The Renderer approach adds functionality to the Renderer to detect the AJAX request. The JSF default lifecycle first restores the component hierarchy during the Restore View phase and the Renderer takes control during the Apply Request Values phase. After the AJAX request has been processed, the Renderer calls responseComplete() on the FacesContext to terminate processing of remaining phases of the Lifecycle. On the surface this may seem like the preferred approach, but it has some severe drawbacks.

A component hierarchy is required, which can incur additional overhead for each request, especially when client-side state saving is used. Calling the response-Complete() method will take effect only after this phase is done processing. The Apply Request Values phase calls the decode() method on all Renderers in the view, which can cause undesired side effects that are out of your control, such as a <h:commandButton> set to immediate="true" by the application developer. This causes the application logic to be called before the Apply Request Values phase is complete.

This approach also usually requires HTTP POST to send the state string back to the server.

The PhaseListener Approach
The PhaseListener approach adds a PhaseListener (PhaseId.RESTORE_VIEW) that short-circuits the Lifecycle and does all the processing in the PhaseListener itself. When it's done, it calls responseComplete() on the FacesContext.

For this approach to work, it has to render a reference containing information about the managed bean used in the initial request. The PhaseListener uses this information during postback to create a MethodBinding that can then be used to invoke a method on the managed bean and return data to the client. Since no component hierarchy is created, and thus no Renderers, there's no risk that command components with immediate set to true will cause any side effects.

But this approach has one issue; there's no way to prevent application developers from attaching additional PhaseListeners at the same phase, which can cause undesirable side effects. You also have no way of knowing in which order these PhaseListeners will be executed.

The Lifecycle Approach
This Lifecycle approach adds a new Lifecycle that's mapped to an AJAX request and contains only the lifecycle phases needed to process the request, invokes the application logic defined by a MethodBinding, and renders the response. This eliminates the overhead of creating and restoring the component tree, and so no Renderers are required. You also won't encounter any issues with immediate="true".

Another positive side effect of using a custom Lifecycle is that any PhaseListener added by the application developer will have no impact on this solution; application developers can even add PhaseListeners to this custom Lifecycle. However, if a custom PhaseListener is used to put additional managed beans on the request, you can run into issues, unless they're registered for the custom Lifecycle as well.

Select a JSF AJAX Approach
Here we use the Lifecycle approach, since it has no application logic side effects and low overhead. It's here that the Mabon Open Source project can help you focus on the design of your AJAX-enabled component.

Let us explain in a little about what Mabon is and what it can provide component writers interested in AJAX data fetch (Figure 2).

What Is Mabon?
Mabon offers a convenient way to hook in a specially designed lifecycle that's ideal for AJAX-enabled components that have to fetch data directly from a backing bean, without the overhead of a full JSF lifecycle. It also provides a Mabon protocol - mabon:/ - used to reference the backing bean and a JavaScript convenience function used to send the target URL and any arguments needed and then get data asynchronously 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 which? Answers to this question can differ depending on whom you ask, but we can recommend one guideline. Ask yourself if 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), letting you 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).

The MabonLifecycle Class
The MabonLifecycle consists of three phases - ApplyRequestValuesPhase, InvokeApplicationPhase, and RenderResponsePhase. The MabonLifecycle is responsible for executing these three phases. It's also responsible for handling any PhaseListeners attached to the MabonLifecycle.

The LifecyclePhase Class
The Mabon LifecyclePhase is the base class for all lifecycle phases.

  • The ApplyRequestValuesPhase, InvokeApplicationPhase, and RenderResponsePhase Classes - Since you're only fetching data and not modifying the component hierarchy or the underlying model in any way, you don't need to include the Restore View, Process Validations, and Update Model phases. The Mabon phases are performing similar operations to the default lifecycle equivalents, such as decoding an incoming request, invoking application logic, and rendering the response.
  • The FacesLifecycleServlet Class - This is a reusable servlet that will initialize the FacesContextFactory and look up the MabonLifecycle in its first request. It will create the FacesContext then invoke the three lifecycle phases that are part of the MabonLifecycle. The servlet mapping defined by the Web application will direct Mabon requests to this FacesLifecycleServlet.
  • The LifecycleFactoryImpl Class - The only purpose of this class is to add a second lifecycle - the MabonLifecycle.
  • The MabonViewHandler Class - During the initial rendering, a custom Renderer has to provide a path to the backing bean that can be intercepted by the FacesLifecycleServlet and used during InvokeApplicationPhase to call the referenced backing bean. By using the Mabon protocol, a component author can get a unique path from the MabonViewHandler that can be rendered to the client. If the component writer passes the string shown in Code Sample 1 with the path argument of the ViewHandler.getResourceURL() method, the MabonViewHandler will return the string shown in Code Sample 2 that can be written to the client.

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
SYS-CON Italy News Desk 04/20/06 11:59:58 AM EDT

In our last article - 'JSF and AJAX' (JDJ, Vol. 11, issue 1) - we discussed how JavaServer Faces component writers can take advantage of the new Weblets Open Source project (http://weblets.dev.java.net) to serve resources such as JavaScript libraries, icons, and CSS files directly from a Java Archive (JAR) without impacting the application developer.

SYS-CON India News Desk 04/20/06 10:44:08 AM EDT

In our last article - 'JSF and AJAX' (JDJ, Vol. 11, issue 1) - we discussed how JavaServer Faces component writers can take advantage of the new Weblets Open Source project (http://weblets.dev.java.net) to serve resources such as JavaScript libraries, icons, and CSS files directly from a Java Archive (JAR) without impacting the application developer.

AJAX News Desk 04/20/06 08:37:43 AM EDT

In our last article - 'JSF and AJAX' (JDJ, Vol. 11, issue 1) - we discussed how JavaServer Faces component writers can take advantage of the new Weblets Open Source project (http://weblets.dev.java.net) to serve resources such as JavaScript libraries, icons, and CSS files directly from a Java Archive (JAR) without impacting the application developer.

@CloudExpo Stories
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...
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...
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 CA Technologies has been named “Platinum Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business – from apparel to energy – is being rewritten by software. From planning to development to management to security, CA creates software that fuels transformation for companies in the applic...
Cloud adoption is often driven by a desire to increase efficiency, boost agility and save money. All too often, however, the reality involves unpredictable cost spikes and lack of oversight due to resource limitations. In his session at 20th Cloud Expo, Joe Kinsella, CTO and Founder of CloudHealth Technologies, tackled the question: “How do you build a fully optimized cloud?” He will examine: Why TCO is critical to achieving cloud success – and why attendees should be thinking holistically ab...
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...
As more and more companies are making the shift from on-premises to public cloud, the standard approach to DevOps is evolving. From encryption, compliance and regulations like GDPR, security in the cloud has become a hot topic. Many DevOps-focused companies have hired dedicated staff to fulfill these requirements, often creating further siloes, complexity and cost. This session aims to highlight existing DevOps cultural approaches, tooling and how security can be wrapped in every facet of the bu...
WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, will introduce two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a...
yperConvergence came to market with the objective of being simple, flexible and to help drive down operating expenses. It reduced the footprint by bundling the compute/storage/network into one box. This brought a new set of challenges as the HyperConverged vendors are very focused on their own proprietary building blocks. If you want to scale in a certain way, let’s say you identified a need for more storage and want to add a device that is not sold by the HyperConverged vendor, forget about it....
SYS-CON Events announced today that Calligo has been named “Bronze 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. Calligo is an innovative cloud service provider offering mid-sized companies the highest levels of data privacy. Calligo offers unparalleled application performance guarantees, commercial flexibility and a personalized support service from its globally located cloud platform...
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?
SYS-CON Events announced today that Cloudistics, an on-premises cloud computing company, has been named “Bronze 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. Launched in 2016, Cloudistics helps anyone bring the power of the cloud to the data center in an easy-to-use, on- premises cloud platform that automatically provides high performance resources for all types of applications: Docke...
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...
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 ...
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...
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 Secure Channels, a cybersecurity firm, 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. Secure Channels, Inc. offers several products and solutions to its many clients, helping them protect critical data from being compromised and access to computer networks from the unauthorized. The company develops comprehensive data encryption security strategie...
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...