Service-Orientation Principles with Java Web-Based Services
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
import com.acme.businessobjects.om.Order; public interface CreditCheck { public boolean hasGoodCredit(Order order); }
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.
Example 7.2
@ServiceMode(value=Service.Mode.MESSAGE) @WebServiceProvider() public class GenericProviderImpl implements Provider<javax.xml.soap.SOAPMessage> { public SOAPMessage invoke(SOAPMessage message) { // read and process SOAPMessage... } }
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.
Example 7.3
@ServiceMode(value=Service.Mode.PAYLOAD) @WebServiceProvider() public class GenericProviderImpl implements Provider<javax.xml.transform.Source> { public Source invoke(Source source) { // read and process SOAPMessage... } }
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
@Post @Consumes("application/xml") public void createCustomer( InputStream in){ //extract customer from request Customer customer = extractCustomer(in); //create customer in system; }
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
@WebService public class OrderProcessing { public void processOrder( Order order, byte[] additionalData) { // process request... } }
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.
Example 7.6
<xs:complexType name="Customer"> <xs:sequence> <xs:element name="accounts" type="ns:Account" nillable="true" maxOccurs="unbounded" minOccurs="0"/> <xs:element name="address" type="ns:Address" minOccurs="0"/> <xs:element name="customerId" type="xs:string" minOccurs="0"/> <xs:element name="name" type="ns:Name" minOccurs="0"/> <xs:element name="orderHistory" type="ns:OrderArray" nillable="true" maxOccurs="unbounded" minOccurs="0"/> <xs:any/> </xs:sequence> </xs:complexType>
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.