Home > Articles > Web Development

Service-Orientation Principles with Java Web-Based Services

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.
This chapter is from the book
07fig00.jpg

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020