Building services for service-oriented solutions requires the application of the service-orientation paradigm whose established design principles drive many Java service contract and implementation decisions. In certain cases, the programming language and runtime environment used for services can also be influenced by these guiding principles. This chapter visits each of the eight service-orientation principles in depth to highlight considerations specific to design and development with Java.

The service-orientation principles are formally documented in the series title SOA Principles of Service Design. Concise profiles of the principles are also available in Appendix B and at www.serviceorientation.com.

7.1 Service Reusability

The following are common design characteristics associated with reusable services:

The service is defined by an agnostic functional context.

The service logic is highly generic.

The service has a generic and extensible contract.

The service logic can be accessed concurrently.

Let’s take a closer look at each of these characteristics in relation to Java.

Agnostic Functional Contexts

Ensuring that the logic encapsulated by a service is agnostic to any particular functional context allows for the building of service interfaces independent of one particular business process or functional domain. The term “context” refers to the service’s functional scope. An agnostic functional context is not specific to any one purpose and is therefore considered multi-purpose. A non-agnostic functional context, on the other hand, is intentionally single-purpose.

A checkpoint that can be part of a regular code review or service interface quality gate is to look at the imports in a Java interface or implementation class for a service. Java interfaces and classes are often structured according to the applicable business domain, and focusing on the list of imported packages can help identify dependencies in the code. Returning to the simplified order management example, the Java service interface for the Credit Check service is seen in Example 7.1.

Example 7.1

The import statement indicates that the service logic depends on the functional context of order management. Such a dependency cannot always be avoided if a service is developed specifically for a particular business domain at the cost of its reusability. Utility services are generally agnostic and reusable, as explained in Chapter 8.

Highly Generic Service Logic

Generic Java service logic refers to logic independent of its service contract. In the Java world, this means that a Java service interface is created with no mapping for the data types referenced in the service contract.

The javax.xml.ws.Provider interface avoids dependency on the service contract when using the JAX-WS programming model for SOAP-based Web services. An incoming message can be received by the service as a SAAJ javax.xml.soap.SOAPMessage with the Provider interface, which allows the entire message to be parsed or navigated as a DOM tree, as seen in Example 7.2.

For the same SOAP-based Web service, the request message can be alternatively read as a javax.xml.transform.Source. As shown in Example 7.3, the message can be treated as a plain XML document with no relationship to SOAP. Only the payload of the request message can be retrieved. Developers can ignore the SOAP envelope or SOAP header to focus on the content in the body of the message.

In both Examples 7.2 and 7.3, the response data returns in the same way the request data was received. If the request is received in an object of type SOAPMessage, then a new SOAPMessage object must be built for the response. Correspondingly, a new Source object must be returned if Source is used.

Generic Java types can capture the appropriate MIME media type or resource representation format produced or consumed by a target resource when building a REST service. For text-based request/response entities, Java String, char[], and the character-based java.io.Reader or Writer interfaces can be used in the resource methods. For completely generic entity representations, which can include binary content, a java.io.InputStream, OutputStream, or a raw stream of bytes can be used as byte[]. For XML-based resource representations, the javax.xml.transform.Source type can be used to handle XML documents at a higher level than a raw stream.

As seen in Example 7.4, a slightly reworked customer resource example of the REST service from the Chapter 6 uses an InputStream. The contents of an entity are extracted in the incoming request to keep the service contract generic.

Example 7.4

Similarly, javax.xml.transform.Source can extract the customer information from the incoming request. JAX-RS relies on a bottom-up service design philosophy for building REST APIs except when using WADL. Using generic types, such as java.lang.Object or byte[], on a JAX-RS resource interface should be sufficient to keep the service contract generic. However, consider what corresponding data types will be used in the WSDL for SOAP-based Web services.

Avoid the use of concrete data types on the Java service interface. The payload of a message is cast into a Java object, such as a byte array or string. The service contract, such as the WSDL for a Web service, must match the generic type, such as java.lang.Object maps to xsd:anyType, byte[], which maps to xsd:hexBinary, and java.lang.String maps to xsd:string. The matching generic types require specific code to be developed in both the service consumer and service for the data to be inserted into the request/response messages.

In Example 7.5, the public class employs a byte array on its interface to hide the details of the data processed by the service.

Example 7.5

Supertypes in the service interface can aid in generalizing a service contract. For example, a service returns detailed account information for a bank’s customer. When creating a data model for the different types of information provided by the different types of accounts, take advantage of inheritance in XML Schema. A superclass called Account can be created in Java, with a number of subclasses defined for each type of account, such as checking, savings, loans, and mortgages. A return type of Account which includes all of the different types of accounts can be specified in the service interface.

The considerations for supertypes are the same for both SOAP and REST services. As in both cases, the XML Java marshaling/unmarshaling is handled by JAXB for XML and MOXy or JSON-P for JSON. MOXy is a framework for marshaling/unmarshaling between JSON and Java objects. JSON-P (Java API for JSON Processing) supports low-level JSON parsing in Java EE 7.

A generic service implementation can serve multiple types of request/response messages, which generally increases reuse opportunities. However, the service logic must be implemented to handle different types of messages. Type-specific code uses language-specific data types. Tooling can generate code that automatically parses messages into the right Java objects, although at the cost of increased coupling. If generic types are used, the processing of incoming and outgoing messages is left to the service implementer. However, generic types offer greater flexibility in terms of type-independence and loose coupling.

Generalizing service logic also applies to the service consumer. For example, JAX-WS defines a generic service invocation API using the javax.xml.ws Dispatch interface. Services can be invoked with unknown interfaces when the service consumer code is developed. Similar to how the use of the Provider interface supports handling requests from different types of service consumers, the use of the Dispatch API allows a service consumer to interact with different types of services. For REST service clients, if a JAX-RS implementation is used, all the generic Java types the JAX-RS implementation supports can be used to build requests and consume responses. However, generic service logic requires the client code to handle different types of messages and have some knowledge about the message formats expected.

Generic and Extensible Service Contracts

Service logic can be made generic for reuse across a wide range of scenarios and adapted to changes in its environment, such as by changing and evolving services or service consumers. A service contract can be made generic by restricting the dependencies on data types referred to in the service contract and limiting the services composed inside the service logic to a minimum. When translated into Java-specific terms, reduce or eliminate the number of business-domain-specific classes in the service implementation.

Creating a generic service contract means applying generic types like string, hex-Binary, or anyType in the schema type definitions for a Web service. Alternatively, message formats can be defined in a service contract with schema inheritance to use common supertypes, and the runtime allowed to determine which concrete subtype is used. Generic types are not only true for the top-level elements in a message but can also be used within a type definition. In Example 7.6, the schema describes a Customer type with a number of well-defined fields and a generic part.

When used in a service contract, the schema in Example 7.6 allows the service to process messages that have a fixed part at the beginning and a variable part at the end, which is represented by the <xs:any> element. SOAP-based Web services can use the Dispatch APIs in the service logic and Provider APIs in the service consumer logic without affecting how the service contract is built.

Service consumer logic can be implemented generically even if a detailed and specific service contract is provided. For REST services, the same considerations hold true for resource representations. XML-based representations can use highly specific types while the JAX-RS resource class can leverage generic Java types. The programmer then becomes responsible for performing the type mapping between XML and Java in the service logic.

Concurrent Access to Service Logic

A particular instance of a shared service will almost always be used by multiple service consumers simultaneously at runtime. How the service is deployed and the characteristics of the service’s runtime environment as influences on service reuse are significant design considerations.

For example, each service request starts a new process that executes the service logic for the request, which ensures that the processing of one request does not affect the processing of another request. Each execution is completely independent of other executions and creates a new thread in the process. However, starting a new process is a relatively expensive operation in terms of system resources and execution time in most runtime environments. Sharing services in this way is inefficient.

All service requests executed within the same process share all the resources assigned to that process, which provides a lightweight method of serving multiple concurrent requests to the same service. Starting a new thread is an inexpensive operation on most systems. Most, if not all, Web service engines work this way. Implementing services in a multithreaded environment requires adherence to the basic rules of concurrent Java programming.

CASE STUDY EXAMPLE

As part of an initiative to comply with recently introduced legal obligations, the NovoBank IT team decides to create a Document Manager service that stores documents for auditing purposes. The service supports storing and retrieving XML documents. To maximize the reusability of this service, the NovoBank IT team creates a generic service contract and flexible service implementation to handle different types of documents, which can be extended over time.

Initially, the service will have the operations of store and retrieve. The service contract does not imply any structure of the documents stored, as shown in Example 7.7.

Example 7.7 NovoBank’s service contract for the Document Manager service is deliberately generic.

Example 7.7 shows that the content of the stored messages is represented by an <xs:any/> element, which means that any well-formed XML can be inserted in the content. The <xs: any/> element allows the Document Manager service to be reused across many different types of messages and documents.

The development team decides to create a flexible implementation of the service which is independent of the specific type of document being sent or retrieved. The service must extend without affecting the existing implementation, preparing support for more specific processing of specific document types. A flexible implementation is achieved with a handler and factory. The implementation leverages the javax.xml.ws.Provider interface and delegates the processing of each message to a handler. The handler instance is then retrieved via a factory.

Example 7.8 shows the implementation class for the Document Manager service in the detailed source code.

Example 7.8 The implementation of the Document Manager service utilizes a factory to retrieve a handler.

This class implements the Provider interface, so that any invocation of the service is directed to the invoke() method. The @ServiceMode annotation indicates that only the actual content of the SOAP body should be passed into the implementation.

In the implementation of the invoke() method, a single instance of a class called DocumentHandlerFactory is used to retrieve a DocumentHandler for this message. Example 7.9 shows the source code for the DocumentHandler interface.

Example 7.9 The source code for the DocumentHandler interface

The DocumentHandler interface only defines the process() method, which processes the message. Different implementations of the interface that process messages in different ways can exist. The message content is passed into the process() method as a stream of type javax.xml.transform.Source. When revisiting the source code for the Document Manager service in Example 7.2, the message returned by the factory can be seen to be passed to the handler.

A part of the source code for the factory is presented in Example 7.10.

The message is parsed to the point where an appropriate handler can be found. Handlers are registered via several mechanisms that can include hardcoding into the factory class, retrieval from a file, or lookup in a registry. The concrete DocumentHandler implementation chosen for a particular message is often based on the root element of the passed message. The root element typically provides adequate indication of the nature of the message.

Using the factory mechanism, where the service implementation class calls a factory to retrieve a handler to process the message, allows new handlers to be later added without affecting the existing code. The combination of a generic service definition using the <xs:any/> element, a flexible service implementation using the Provider interface, and a factory to delegate the processing of the message ensures maximum reusability of the service across a variety of environments and domains.

SUMMARY OF KEY POINTS

For SOAP-based Web services, the JAX-WS standard offers ways of implementing service logic as generic and therefore capable of handling different types of messages.

For REST services, Java generic types can be used in JAX-RS-based resource implementations. The request/response entities are treated as a raw sequence of bytes or characters.

Using generic data types for domain entities or resource representations allows the service to be reused across a greater number of potential service consumers.