Welcome!

Weblogic Authors: Yeshim Deniz, Elizabeth White, Michael Meiner, Michael Bushong, Avi Rosenthal

Related Topics: Weblogic

Weblogic: Article

J2EE Framework for Services

J2EE Framework for Services

This article presents a lightweight framework for building a service-oriented architecture (SOA) on top of J2EE.

The architecture is a subset of a framework that we have successfully applied in various J2EE applications. The framework is built from a combination of commonly known design patterns (GoF = Gang of Four; j2eecp = J2EE Core Patterns):

  • Factory (GoF)
  • Proxy (GoF)
  • Service Locator (j2eecp)
  • Business Delegate (j2eecp)
  • Service Facade (j2eecp)
At first glance, the framework may seem to require too many artifacts, but we will justify these as we go along. We will also see that most of the artifacts can be generated.

What Is Service-Oriented Architecture?
SOA is a framework for building IT solutions in the form of services. A service encapsulates some functionality exposed through one or more well-documented interfaces. The interfaces may be published and discoverable through repositories.

Could We Use Web Services?
A popular technique for communication, publishing, and discovery of services is the use of Web services and UDDI. Web services work well as an interapplication framework where the service interfaces provide only coarse-grained methods. However, Web services are too resource intense for intra-application communication. To leverage the idea of services inside a J2EE application, we need a framework with much less overhead.

Example
To illustrate the framework, we will create a very simple service that implements a number guessing game.

The number guessing game has two methods:

  • The method start starts (or restarts) the game and sets the upper and lower boundary for possible guesses. The service generates a random secret number that it stores internally.
  • The method guess is called when a client wants to guess the value of the secret number. The method returns the value -1 if the guess is too low, 0 if the guess is correct, and 1 if the guess is too high.

    To implement this simple service, we create the following artifacts:

  • Service Interface: Declaration of the interface for the service
  • Service Factory: Used by service clients and session beans to instantiate services
  • Session Bean Proxy: Client-side implementation of the service interface that forwards to a session bean
  • Business Bean: The "real" service implementation
  • Mockup Bean: A "fake" service implementation
  • Session Bean: A standard EJB session bean enabling enterprise-strength declaration of services (security, transactions, remote communication, etc.)

    The Client's View
    One goal of the framework is to make it easy for clients to obtain and use services. A client could be a Web component (JSP, servlet, or Struts action), a stand-alone application, or a business component running inside the EJB tier.

    In our framework, the clients obtain services through a service factory. The service factory returns an object implementing an interface that the client expects. This shields the clients from the complexity of J2EE (JNDI lookup, narrowing, etc.). The following code fragment shows how a client obtains the number guessing game service:

    NumberGuessingGame game = (NumberGuessingGame)
    ServiceFactory.lookup("NumberGuessingGame");

    With the clients' independence of J2EE artifacts now achieved, it is significantly easier to change the underlying implementation. This allows us to post-optimize the implementation of the number guessing game without affecting the client.

    The Implementer's View
    Ideally, the implementer of the business logic should also be shielded from the details of the EJB technology. The framework enables the business logic to be implemented as a standard JavaBean (see Figure 3).

    The implementer would typically provide two implementations of the service interface. The first implementation is a simple mockup that allows its clients to develop their logic without waiting for the real implementation to be complete. For this simple game, such a mockup is not justified, but it is very useful in enterprise applications where the development of the service may take a long time. A mockup reduces the risk of integration problems, especially when several teams concurrently implement services (see Figure 4).

    A simple mockup implementation of the guess method could generate a random number from -1 to 1:

    class NumberGuessingGameMockup implements NumberGuessingGame {
    public NumberGuessingGameMockup () {}
    public void start(int min, int max) {}
    public int guess(int aGuess) throws
    TechnicalException {
    return (((int)(Math.random() * 3.0)) - 1);
    }
    }

    Later we would follow up with the real implementation shown in Listing 1.

    The J2EE Connector Implementation
    To enable a remote client to communicate with the business logic, we must provide an implementation of a proxy that has the service interface, but forwards to the business logic. This requires several artifacts in J2EE.

    A proper port into the EJB container is a session bean, which provides server-side activation of the business logic. It receives remote business requests from clients, looks up the business logic bean, and forwards the business requests to it. The session bean is implemented according to standard EJB rules (see Figure 5).

    Notice that the session bean has a reference to a service implementing the NumberGuessingGame interface. When the session bean is activated, it uses a server-side service factory to create the service:

    void ejbCreate() {
    this.service =
    (NumberGuessingGame) ServiceFactory.lookup("NumberGuessingGame");
    }

    When a business method is invoked, the session bean simply forwards the request to the service:

    int guess(int theGuess) throws TechnicalException {
    return this.service.guess( theGuess );
    }

    To provide the client view we discussed earlier, we must also provide a client-side implementation that hides the use of the session bean from the client. We call this implementation a session bean proxy. In the core J2EE patterns, this implementation corresponds to the business delegate pattern.

    The session bean proxy created for the client acts quite similarly to the session bean. Upon creation, it accesses JNDI to look up the home and creates the remote proxy from the home (see Listing 2).

    The implementation of business methods on the session bean proxy forwards requests to the remote object. If a remote exception occurs, the exception is rethrown as a technical exception. For example:

    public int guess(int theGuess) throws TechnicalException {
    try {
    return this.remote.guess( theGuess );
    }
    catch (RemoteException e ) {
    throw new TechnicalException( e );
    }
    }

    We rethrow the remote exception to avoid exposing the underlying technology.

    The Service Factory
    The service factory is responsible for instantiating the correct implementation of a service based on the context in which it is being requested. There are many possible implementations. For our example we use simple property files to store name-value pairs. The name identifies the service and the value holds the name of the class implementing the service (the business object, the mockup implementation, or the session bean proxy). The service factory uses reflection to instantiate the proper implementation (see Listing 3).

    Every J2EE container has its own instance of service factory with a different configuration (defined by the property files).

    Putting It Together
    The framework can be seen as a layered architecture. The real communication is between the client and the business implementation. To add J2EE enterprise services (such as transactions, security, etc.), we may instantiate a session bean proxy/session bean layer. If the client and the business logic live in two different containers, we may use remote proxies (remote object + ejb object) provided by J2EE.

    The collaboration diagram in Figure 7 illustrates a runtime scenario. In this scenario, a client running in a remote container uses a business service implemented in an EJB container. The business service uses another service (dependent business service) running in the same container.

    In Figure 7:
    1.   The client requests a service from the client-side service factory.
    2.   The service factory creates the session bean proxy.
    3.   The service factory uses JNDI to look up the home and create the remote object.
    4.   The client invokes a business method on the session bean proxy.
    5.   The session bean proxy uses the remote object for the session bean obtained in step 3 to forward the business request.
    6.   The session bean uses the server-side factory to create the business service.
    7.   The server-side factory creates the business service and returns it to the session bean.
    8.   The session bean forwards the business request to the business service.
    9.   The business service needs another service to fulfill the business request. It asks the server-side factory for the dependent service.
    10.   The server-side factory creates the requested service (no session bean is required).
    11.   The business service calls business services on its dependent service.

    In our simple example, the number guessing game does not need help from other services, so steps 9 through 11 are not required.

    Generative Programming
    We seem to have created many artifacts to implement a simple service. The effort can be greatly minimized by use of generative programming. We can write a program to generate the session bean (home interface, remote interface, and the session bean implementation; XML fragments for the deployment descriptor) and the session bean proxy. Here are a few approaches that we have had success with:

  • Create a simple program that uses reflection upon the business logic bean or the service interface
  • Write a script in our favorite case tool
  • Write an explicit tool to generate the J2EE connectors (as in OMG's Model Driven Architecture)

    Conclusion
    In this article, we have presented an approach to service-oriented architecture that yields the following benefits:

  • Shields developers from the complexity of J2EE: The J2EE code can be generated.
  • Clients only see the factory and the interface to the service.
  • Business logic developers use standard JavaBeans to implement the interface.
  • Offers support for concurrent development: Service providers can offer mockup implementations for the service early in the project's life cycle that enable dependents to continue their work prior to the completion of the real service implementation.
  • Avoids session bean call overhead on service-to-service calls: The server-side factory would only issue business logic beans, removing the overhead of calling through a session bean (this advantage is minimal with EJB 2.0's local beans).
  • Minimize impact of post-optimization: We now have a layer of code running on the client side. We can easily move algorithms and data to the client side (either by adding implementation to the session bean proxy or by instantiating the service on the client side).

    A complete implementation of the example can be downloaded from www.sys-con.com/weblogic/sourcec.cfm.

  • More Stories By Petter Graff

    Petter Graff is Vice President of InferData Corporation. He has more than 20 years of experience building object-oriented software solutions. The last 10 years he has been teaching and consulting on enterprise architectures for Fortune 500 companies worldwide.

    Comments (0)

    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.


    @ThingsExpo Stories
    Michael Maximilien, better known as max or Dr. Max, is a computer scientist with IBM. At IBM Research Triangle Park, he was a principal engineer for the worldwide industry point-of-sale standard: JavaPOS. At IBM Research, some highlights include pioneering research on semantic Web services, mashups, and cloud computing, and platform-as-a-service. He joined the IBM Cloud Labs in 2014 and works closely with Pivotal Inc., to help make the Cloud Found the best PaaS.
    Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution. In his session at @ThingsExpo, Akvelon expert and IoT industry leader Sergey Grebnov provided an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
    Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
    Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
    Personalization has long been the holy grail of marketing. Simply stated, communicate the most relevant offer to the right person and you will increase sales. To achieve this, you must understand the individual. Consequently, digital marketers developed many ways to gather and leverage customer information to deliver targeted experiences. In his session at @ThingsExpo, Lou Casal, Founder and Principal Consultant at Practicala, discussed how the Internet of Things (IoT) has accelerated our abilit...
    In his session at Cloud Expo, Alan Winters, U.S. Head of Business Development at MobiDev, presented a success story of an entrepreneur who has both suffered through and benefited from offshore development across multiple businesses: The smart choice, or how to select the right offshore development partner Warning signs, or how to minimize chances of making the wrong choice Collaboration, or how to establish the most effective work processes Budget control, or how to maximize project result...
    To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
    Data is the fuel that drives the machine learning algorithmic engines and ultimately provides the business value. In his session at Cloud Expo, Ed Featherston, a director and senior enterprise architect at Collaborative Consulting, discussed the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
    In his keynote at 19th Cloud Expo, Sheng Liang, co-founder and CEO of Rancher Labs, discussed the technological advances and new business opportunities created by the rapid adoption of containers. With the success of Amazon Web Services (AWS) and various open source technologies used to build private clouds, cloud computing has become an essential component of IT strategy. However, users continue to face challenges in implementing clouds, as older technologies evolve and newer ones like Docker c...
    "Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
    Two weeks ago (November 3-5), I attended the Cloud Expo Silicon Valley as a speaker, where I presented on the security and privacy due diligence requirements for cloud solutions. Cloud security is a topical issue for every CIO, CISO, and technology buyer. Decision-makers are always looking for insights on how to mitigate the security risks of implementing and using cloud solutions. Based on the presentation topics covered at the conference, as well as the general discussions heard between sessio...
    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 ...
    Organizations planning enterprise data center consolidation and modernization projects are faced with a challenging, costly reality. Requirements to deploy modern, cloud-native applications simultaneously with traditional client/server applications are almost impossible to achieve with hardware-centric enterprise infrastructure. Compute and network infrastructure are fast moving down a software-defined path, but storage has been a laggard. Until now.
    DXWorldEXPO LLC announced today that the upcoming DXWorldEXPO | CloudEXPO New York event will feature 10 companies from Poland to participate at the "Poland Digital Transformation Pavilion" on November 12-13, 2018.
    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...
    The best way to leverage your CloudEXPO | DXWorldEXPO presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering CloudEXPO | DXWorldEXPO 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 CloudEXPO. Product announcements during our show provide your company with the most reach through our targeted audienc...
    In an era of historic innovation fueled by unprecedented access to data and technology, the low cost and risk of entering new markets has leveled the playing field for business. Today, any ambitious innovator can easily introduce a new application or product that can reinvent business models and transform the client experience. In their Day 2 Keynote at 19th Cloud Expo, Mercer Rowe, IBM Vice President of Strategic Alliances, and Raejeanne Skillern, Intel Vice President of Data Center Group and ...
    More and more brands have jumped on the IoT bandwagon. We have an excess of wearables – activity trackers, smartwatches, smart glasses and sneakers, and more that track seemingly endless datapoints. However, most consumers have no idea what “IoT” means. Creating more wearables that track data shouldn't be the aim of brands; delivering meaningful, tangible relevance to their users should be. We're in a period in which the IoT pendulum is still swinging. Initially, it swung toward "smart for smart...
    DXWorldEXPO LLC announced today that All in Mobile, a mobile app development company from Poland, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. All In Mobile is a mobile app development company from Poland. Since 2014, they maintain passion for developing mobile applications for enterprises and startups worldwide.
    @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.