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
    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...