Welcome!

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

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
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
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...
To Really Work for Enterprises, MultiCloud Adoption Requires Far Better and Inclusive Cloud Monitoring and Cost Management … But How? Overwhelmingly, even as enterprises have adopted cloud computing and are expanding to multi-cloud computing, IT leaders remain concerned about how to monitor, manage and control costs across hybrid and multi-cloud deployments. It’s clear that traditional IT monitoring and management approaches, designed after all for on-premises data centers, are falling short in ...
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...