Welcome!

Java IoT Authors: Liz McMillan, Pat Romanski, Zakia Bouachraoui, Elizabeth White, Yeshim Deniz

Related Topics: Java IoT

Java IoT: Article

Writing Classpath-less J2EE Clients...

...using a simple technique

Developing lightweight J2EE client applications that interoperate with multiple application servers can be difficult to do. Having to include an application server-specific JAR file along with a thin client application can significantly increase the size of the deployed application and make it too big to be practical.

In addition, client-side execution is tightly coupled using proprietary app-server extensions. This is especially true when mixing and matching multiple J2EE vendors together (such as a Tomcat servlet container communicating with a WebLogic EJB tier). Standard protocols, such as RMI/IIOP, are supposed to alleviate this problem. However, there is still no standard API or library that can be used across application servers without sacrificing native features, such as:

  • Clustering and high availability (including load balancing and failover)
  • Native communication protocols for optimal performance, such as socket multiplexing and efficient serialization (as opposed to standard RMI/IIOP)
  • Transaction management (including distributed transactions)
  • Security (JAAS, SSL transports)
  • Interoperability with previous and future versions of the application server
  • Lack of support for other J2EE features such as JDBC, and JMX
  • Specific JDK version requirements
This article presents a simple technique using URL classloading and reflection to build portable, ultra-thin Java client applications without adding anything in the classpath, while preserving all of the application servers' native features. (The source code for this article can be downloaded from www.sys-con.com/java/sourcec.cfm.) Specifically, this article demonstrates how to:
  • Use the java.net.URLClassLoader to obtain Java resources from an HTTP connection to achieve dynamic class loading and automatic software distribution while maintaining a zero client footprint.
  • Invoke methods reflectively with the URLClassLoader and understand that the code is dynamically bound at runtime versus compile time.
  • Create high-bandwidth and small-memory footprint JVM applications deployed as thick-client applications and utilize this technique to obtain J2EE, XML, rich client libraries, and business rules from the server.
Listing 1 is an example of an ultra-thin J2EE client application invoking an HelloWorld EJB. It obtains an InitialContext from JNDI, looks up a home interface, creates the remote object, and invokes a method. Notice that there are no Java imports to J2EE APIs or dependent classes (HelloWorld objects) for compilation and execution. A URLClassLoader is utilized to retrieve the necessary class files via HTTP on demand. All of the application servers' functionality, such as the internal communication mechanism, security, transaction management, etc., are automatically downloaded and executed. This also applies to the user-defined application code, such as the HelloWorld client stubs and home interfaces.

High-Level Overview
One of the greatest features of the Java platform is the ability to dynamically download and execute Java code from a set of URLs to a Java Virtual Machine (JVM). The result is that a remote system can run a program, for example, a thin J2EE client, which has never been installed on its disk. Using the java.net.URLClassLoader and reflection APIs, any JVM can download any Java resource, including RMI stubs, which enables the execution of method calls on a remote server using the server system's resources.

How It Works
The ThinClient.java program does not contain any imports other than the core J2SE APIs. It uses a URLClassLoader to load its Java resources (see Figure 1). The URL is a servlet (see Listing 2) that's deployed on an application server as part of an .ear file.

1.  The application server binds the HelloWorld EJB into JNDI. The ClassLoader servlet and Web application (see Listing 2) is deployed on the server and includes the HelloWorld_ejb.jar as part of the classpath. When resources are accessed from this servlet, it will serve classes from its .war, EJB classes, .ear, and System classpath. (Listings 2-5 can be downloaded from www.sys-con.com/java/sourcec.cfm.)
2.  The thin J2EE client application uses the URL ClassLoader to load Java resources. The particular example in Listing 1 loads all classes using this classloader.


// set the context class loader to a URL ClassLoader
ClassLoader classLoader;
Thread.currentThread().setContextClassLoader(
classLoader = new URLClassLoader(
new URL[] {
new

URL("http://localhost:7001/classloader/ClassLoaderServlet/")
}
)
);

3.  The thin J2EE client application uses reflection to instantiate a hashtable to set up the InitialContext and performs a JNDI lookup operation reflectively. The URLClassLoader is used to download the application server's required classes for the lookup operation. The HelloWorld stubs are returned and executed on the thin client (see Listing 3).
4.  The thin J2EE client performs method calls via reflection to the server (see Listing 4).

Listing 2 contains the servlet code that loads the Java resources. In this particular example, the servlet is colocated with the application in the same J2EE container.

Java resources are accessed using the following syntax:

http://<servername>:<port>/classloader/ClassLoaderServlet/test/Example.c...

The extra path information:

/test/Example.class

is a hypothetical class called test.Example in the system classpath or part of the .war or .ear files.

Alternative Technologies
A client can access an application service several ways. For example, a client may use a proprietary protocol, RMI/IIOP, JMS, or Web services. Several advantages and disadvantages exist with each of these communication technologies, and choosing the most "optimal" client application design can be challenging.

Interoperability is one factor that comes to mind when choosing a communication mechanism. Both thin J2EE clients and Web services fit well in this model. Web services give clients the ability to interoperate with almost any type of system and application, regardless of the platform on which the system or application runs. The thin J2EE client approach is limited to Java, but allows conversational state, asynchrony, transactions, security, and high-availability performance.

Web services use HTTP as the transport protocol, enabling clients to operate with systems through firewalls. The service's WSDL document enables clients and services that use very different technologies to map and convert their respective data objects. For services and clients that are based on JAX-RPC, the JAX-RPC runtime handles this mapping transparently.

Listing 5 illustrates how to create a dynamic Web service using WSDL. Notice that there are only J2EE imports. It's very similar to the ThinClient.java example, in that the operation and service definitions are dynamically obtained.

More Stories By Bahar Limaye

Bahar Limaye is a system architect at The College Board. He has extensive experience building distributed object-oriented systems.

Comments (3)

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.


IoT & Smart Cities Stories
If a machine can invent, does this mean the end of the patent system as we know it? The patent system, both in the US and Europe, allows companies to protect their inventions and helps foster innovation. However, Artificial Intelligence (AI) could be set to disrupt the patent system as we know it. This talk will examine how AI may change the patent landscape in the years to come. Furthermore, ways in which companies can best protect their AI related inventions will be examined from both a US and...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
DXWorldEXPO LLC, the producer of the world's most influential technology conferences and trade shows has announced the 22nd International CloudEXPO | DXWorldEXPO "Early Bird Registration" is now open. Register for Full Conference "Gold Pass" ▸ Here (Expo Hall ▸ Here)
CloudEXPO New York 2018, colocated with DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering Cloud Expo and @ThingsExpo will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at Cloud Expo. Product announcements during our show provide your company with the most reach through our targeted audiences.
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO 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 t...
Contextual Analytics of various threat data provides a deeper understanding of a given threat and enables identification of unknown threat vectors. In his session at @ThingsExpo, David Dufour, Head of Security Architecture, IoT, Webroot, Inc., discussed how through the use of Big Data analytics and deep data correlation across different threat types, it is possible to gain a better understanding of where, how and to what level of danger a malicious actor poses to an organization, and to determin...
The hierarchical architecture that distributes "compute" within the network specially at the edge can enable new services by harnessing emerging technologies. But Edge-Compute comes at increased cost that needs to be managed and potentially augmented by creative architecture solutions as there will always a catching-up with the capacity demands. Processing power in smartphones has enhanced YoY and there is increasingly spare compute capacity that can be potentially pooled. Uber has successfully ...
The deluge of IoT sensor data collected from connected devices and the powerful AI required to make that data actionable are giving rise to a hybrid ecosystem in which cloud, on-prem and edge processes become interweaved. Attendees will learn how emerging composable infrastructure solutions deliver the adaptive architecture needed to manage this new data reality. Machine learning algorithms can better anticipate data storms and automate resources to support surges, including fully scalable GPU-c...
We are seeing a major migration of enterprises applications to the cloud. As cloud and business use of real time applications accelerate, legacy networks are no longer able to architecturally support cloud adoption and deliver the performance and security required by highly distributed enterprises. These outdated solutions have become more costly and complicated to implement, install, manage, and maintain.SD-WAN offers unlimited capabilities for accessing the benefits of the cloud and Internet. ...