11 min read

 

Apache OfBiz Cookbook

Apache OfBiz Cookbook

Over 60 simple but incredibly effective recipes for taking control of OFBiz

  • Optimize your OFBiz experience and save hours of frustration with this timesaving collection of practical recipes covering a wide range of OFBiz topics.
  • Get answers to the most commonly asked OFBiz questions in an easy-to-digest reference style of presentation.
  • Discover insights into OFBiz design, implementation, and best practices by exploring real-life solutions.
  • Each recipe in this Cookbook is crafted to describe not only “how” to accomplish a specific task, but also “why” the technique works to ensure you get the most out of your OFBiz implementation.

Read more about this book

(For more resources on Apache see here.)

Introduction

Ask five people what “web services” are and you will likely get at least six different opinions. Because the term evokes such ambiguity, we need to set ground rules for this article and define what we mean by “web services”. Therefore, for the purposes of this book, “web services” are the interactive exchange of messages from one system to another using the Internet as the network transport and HTTP/HTTPS as the messaging protocol. Message exchange transpires without human intervention and may be one-way—that is, called without an immediate response expected—or two-way.

Web services operate as producer/consumer systems where the producer—called the “service provider”—offers one or more “services” to the “consumer”—sometimes referred to as the “client”. In the web services world, Internet-based service providers advertise and deliver service from locations throughout the Web. The Internet, and the Web in particular, serve as the highway over which potential web service clients travel to find service providers, make contact, and deliver products.

Service-oriented by design, OFBiz is a natural for building and deploying both web service clients and web service providers. Any OFBiz web application (webapp) may both consume web services and act as a web service provider within the same application or in an unlimited number of OFBiz webapps.

Within the web service producer/consumer model, service providers are responsible for accepting and validating requests for service and delivering the product. Consumers must find service providers, request service, and accept delivery of the product. There are a number of ad-hoc and formal standards that have evolved over the last few years to help facilitate the business of enabling web services, including, but not limited to, URL parameter passing, XML-RPC, and Simple Object Access Protocol (SOAP) based messaging. OFBiz provides builtin support with tools and integration points to make implementing both service provider and consumer web services a snap.

Requesting web services using URL parameters

There are many web service providers that require nothing more than URL parameter passing to request a service. These service providers take HTTP/HTTPS request parameters as appended to a prospective consumer’s URL, and process requests according to the passed parameter values. Services are delivered back to the requestor through the client’s HTTP/ HTTPS response message or as a separate HTTP/HTTPS request message exchange.

An example of such a real world web service is the PayPal Payments Standard payment processing service . This web service expects requests to come in on an advertised URL with request particulars appended to the URL as request parameters. Prospective consuming systems send HTTP/HTTPS request messages to the PayPal URL asking for service. Once a request for service has been accepted by PayPal, the Payments Standard web service responds and delivers service using the HTTP/HTTPS response message.

A separate web service, also involving PayPal, called the Instant Payment Notification (IPN) web service is an example of a web service in which parameters are passed on the URL from the service provider to a consumer such as OFBiz. In this case, OFBiz listens on a configured URL for an HTTP/HTTPS request message from PayPal. When one is received, OFBiz responds appropriately, taking delivery of PayPal service.

Note: to implement a PayPal IPN client within an OFBiz web application, you must provide PayPal a destination URL that maps to a valid OFBiz request-map, and then process any incoming URL parameters according to the PayPal IPN directions.

Getting ready

To act as a web service client and pass parameters on the URL within an OFBiz Java Event or Service, make sure you include the following Java packages in your program:

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import javax.Servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

How to do it…

To request a service using URL parameters, follow these steps:

  1. Within an existing OFBiz Java program (either an Event, Service, or any other) method, create a Java HashMap containing the name/value pairs that you wish to pass on the URL. For example:

    Map parameters = UtilMisc.toMap("param1", "A", "param2", "B");

  2. Use the OFBiz-provided UtilHttp.urlEncodeArgs method to properly encode the parameters directly from the HashMap into a Java String. For example:

    String encodedParameters = UtilHttp.urlEncodeArgs(parameters, false);

  3. Build a URL and add the encoded parameter string to the URL:

    String redirectUrl = "http://www.somehost.com";
    String redirectString = redirectUrl + "?" + encodedParameters;

  4. Send the request by way of the HttpServletResponse object’s redirect method:

    try {
    response.sendRedirect(redirectString);
    }
    catch (IOException e) {
    // process errors here
    return "error";
    }

How it works…

In a very simple web service client scenario, OFBiz acts on behalf of a user or another OFBiz process and makes a web service consumer request of a remote service provider. The request is sent using a HTTP/HTTPS request message with one or more service parameters appended to the URL. The URL is the location on the web of the service provider.

Because the scenario described above is a one-way message exchange—that is, the request message is delivered to the destination URL, but OFBiz does not wait around for a response message—there must be assumptions made about how the web service provider will deliver service. Many times, service is delivered through a totally separate message exchange, initiated by first making the one-way request as described earlier.

To illustrate how this may play out, we consider the PayPal Payments Standard web service. This web service may be invoked from OFBiz in at least two different ways. For example, one approach is to include an HTML form on an OFBiz web page with a Submit button. The Submit button when clicked redirects the browser (with the request message) to the PayPal web service site passing the form contents as is.

An alternative implementation is to have an HTML form on an OFBiz web page with a Submit button that, when clicked, forwards the browser’s request of an OFBiz Service (or Event). In this case, the OFBiz Event or Service will take the form attribute values (from the request message) and create a URL for the PayPal web service location. The original form attribute values and any other information as provided by the context or through database reads is appended to the URL. OFBiz then redirects the user’s original request message using the sendRedirect method on the HttpServletResponse object to effectively send the user, by way of a browser and an appropriately crafted URL, to the PayPal web service.

Building URL request parameters out of plain Java strings can be tricky given the nature of the characters used to construct request parameters and delimit multiple parameter strings. For example, how do you pass a space character as part of a parameter when spaces are used as delimiters?

Enter URL encoding. URL encoding takes certain characters, deemed “special” characters, and “escapes” them so that they may be used as part of a request parameter string. OFBiz provides an easy-to-use encoder (and decoder) method(s): the UrlEncodeArgs method on the UtilHttp utility that takes as an argument a Java Map and returns an encoded string that may then be appended to a URL as shown earlier.

Note: an exhaustive treatment of URL encoding is beyond the scope of this article. For more information on HTML and ASCII character codes and encoding symbols, please see the HTML Codes page

There’s more…

The UrlEncodeArgs method has two modes of operation: selecting the false method-parameter value will encode using only an ampersand (&) symbol while the true parameter value tells OFBiz to use &amp as the encoding string. Based on the web service provider’s instructions, you will need to determine which mode is appropriate for your application.

Many web services do not require encoded values. You will need to verify for each service whether or not it is necessary to encode and decode URL parameters. For example, the PayPal IPN web service sends request parameters without any encoding. When returning IPN messages, the client web service is, however, instructed to encode parameters.

PayPal IPN is strictly a server-to-server (there is no human intervention) messaging system where message traffic is transported across the web from one server URL to another. PayPal is the web service provider while, in this scenario, OFBiz acts as the web service client. It works something like shown in the following diagram:

Requesting web services using an HttpClient

Many web services are implemented using HTTP/HTTPS request methods and parameters passed as part of the request’s message body. These requests for service mimic a user sitting at a browser submitting HTML forms and waiting for server response. Service providers read HTTP/HTTPS request header information and name/value request message parameter pairs, and deliver service through the HTTP/HTTPS response message.

Writing clients for these types of web services usually require a synchronous call to the service provider. From within your OFBiz client code, you initiate a call to a service provider and then wait until a response (or timeout) is received. Unlike the PayPal Payments Standard service described earlier, the OFBiz client program does not redirect HTTP/HTTPS request messages to another URL.

There are a number of examples within the out-of-the-box OFBiz project of service providers that use the HTTP/HTTPS request message body to exchange information with OFBiz clients. They include, but are not limited to:

  • Authorize.net Payment Services
  • ClearCommerce Payment Services
  • Go Software RiTA
  • ValueLink Prepaid/Gift Card Payment Services
  • DHL, FedEx, United Parcel Services (UPS), and United States Post Office Shipping Services
  • CDYNE Web Based Services
  • PayPal Payments Pro

Getting ready

The first step in writing any web service client is to gather the following information about how the target web service operates:

  • The URL on the web for the service provider
  • Any connection parameters and/or HTTP/HTTPS request message header settings that must be passed as required by the service provider
  • The HTTP/HTTPS connection verb (get, post, or other)

Within a Java program, to send and receive web service messages as a client and use the built-in HTTP client utility provided by OFBiz, make sure you have the following Java packages imported in your program:

import org.ofbiz.base.util.HttpClient;
import org.ofbiz.base.util.HttpClientException;

How to do it…

You can request a web service by following these steps:

  1. Create a connection string that includes the URL of the target web service and the type of request:

    String connectString = "http://www.some_web_service_url.com/serviceName";

  2. Within your Java program, create an instance of the HttpClient object with the URL/connection string passed to the constructor as shown here:

    HttpClient http = new HttpClient(connectString);

  3. Create the content of your request as dictated by the target web service provider. For example, some web services expect XML documents; others, simple string parameters. A web service that expects a string of name/value pairs could be coded as follows:

    http.setParameter("Param1", "X");
    http.setParameter("Param2", "Y");

  4. Send your request using the appropriate method on the HttpClient object. For “get” requests, use the get method. For “post” requests, use the post method as shown here:

    try {
    response = http.post();
    }
    catch (HttpClientException e) {
    // Process error conditions here
    }

  5. Handle any service response inline. Unlike the asynchronous nature of the PayPal IPN web service described earlier, HttpClient based web services process return calls inline with the initial web service call. Under the covers, the HttpClient utility handles all the network connection set up and lower-level message transmissions.
  6. There is no need to release or close the connection as OFBiz manages the handoff of connections.

How it works…

When using the HttpClient to access web services remote to OFBiz, you send the consumer-side call synchronously; that is, you wait for the return from the remote web service call within your program. The OFBiz integration of the HttpClient utility manages the details necessary to open the network connection, maintain direct request and response message exchanges, and close the connection upon completion of processing.

There’s more…

The OFBiz implementation of the HttpClient object provides several convenience constructors, which may be useful depending on your processing needs. These include:

// To create a new client object and connect using a URL object instead of a String
URL url = "https://www.some_host.com/";
HttpClient http = new HttpClient(url);

// To create a new client object using a Java Map containing request parameters
HttpClient http = new HttpClient(url, UtilMisc.toMap("param1", "X",
"param2", "Y");

//To create a new client object with a parameter map and header settings
HttpClient http = new HttpClient(connectString,
UtilMisc.toMap("param1", "X"),
UtilMisc.toMap("User-Agent, "Mozilla/4.0"));

See also

OFBiz provides an integration of the Apache HttpClient software package: the Jakarta Commons HTTP Client that is accessed by creating a new HttpClient object. Any method you can call on, the original Apache HttpClient object is available in the OFBiz implementation. This includes full support for HTTPS (SSL) clients. For more information, please see the Jakarta Commons HTTP Client web page

LEAVE A REPLY

Please enter your comment!
Please enter your name here