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.


    IoT & Smart Cities Stories
    The Japan External Trade Organization (JETRO) is a non-profit organization that provides business support services to companies expanding to Japan. With the support of JETRO's dedicated staff, clients can incorporate their business; receive visa, immigration, and HR support; find dedicated office space; identify local government subsidies; get tailored market studies; and more.
    As you know, enterprise IT conversation over the past year have often centered upon the open-source Kubernetes container orchestration system. In fact, Kubernetes has emerged as the key technology -- and even primary platform -- of cloud migrations for a wide variety of organizations. Kubernetes is critical to forward-looking enterprises that continue to push their IT infrastructures toward maximum functionality, scalability, and flexibility. As they do so, IT professionals are also embr...
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
    Atmosera delivers modern cloud services that maximize the advantages of cloud-based infrastructures. Offering private, hybrid, and public cloud solutions, Atmosera works closely with customers to engineer, deploy, and operate cloud architectures with advanced services that deliver strategic business outcomes. Atmosera's expertise simplifies the process of cloud transformation and our 20+ years of experience managing complex IT environments provides our customers with the confidence and trust tha...
    AI and machine learning disruption for Enterprises started happening in the areas such as IT operations management (ITOPs) and Cloud management and SaaS apps. In 2019 CIOs will see disruptive solutions for Cloud & Devops, AI/ML driven IT Ops and Cloud Ops. Customers want AI-driven multi-cloud operations for monitoring, detection, prevention of disruptions. Disruptions cause revenue loss, unhappy users, impacts brand reputation etc.
    As you know, enterprise IT conversation over the past year have often centered upon the open-source Kubernetes container orchestration system. In fact, Kubernetes has emerged as the key technology -- and even primary platform -- of cloud migrations for a wide variety of organizations. Kubernetes is critical to forward-looking enterprises that continue to push their IT infrastructures toward maximum functionality, scalability, and flexibility.
    Today's workforce is trading their cubicles and corporate desktops in favor of an any-location, any-device work style. And as digital natives make up more and more of the modern workforce, the appetite for user-friendly, cloud-based services grows. The center of work is shifting to the user and to the cloud. But managing a proliferation of SaaS, web, and mobile apps running on any number of clouds and devices is unwieldy and increases security risks. Steve Wilson, Citrix Vice President of Cloud,...
    When Enterprises started adopting Hadoop-based Big Data environments over the last ten years, they were mainly on-premise deployments. Organizations would spin up and manage large Hadoop clusters, where they would funnel exabytes or petabytes of unstructured data.However, over the last few years the economics of maintaining this enormous infrastructure compared with the elastic scalability of viable cloud options has changed this equation. The growth of cloud storage, cloud-managed big data e...
    Artificial intelligence, machine learning, neural networks. We're in the midst of a wave of excitement around AI such as hasn't been seen for a few decades. But those previous periods of inflated expectations led to troughs of disappointment. This time is (mostly) different. Applications of AI such as predictive analytics are already decreasing costs and improving reliability of industrial machinery. Pattern recognition can equal or exceed the ability of human experts in some domains. It's devel...