Apache OFBiz Services

Exclusive offer: get 50% off this eBook here
Apache OfBiz Cookbook

Apache OfBiz Cookbook — Save 50%

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

$26.99    $13.50
by Ruth Hoffman | September 2010 | Cookbooks Open Source

In this article, by Ruth Hoffman, author of Apache OFBiz Cookbook, we explore the following OFBiz Service topics:

  • Managing OFBiz Services
  • Calling asynchronous, synchronous, and recurring Services from an HTML form
  • Creating a Service definition file
  • Creating a Service definition
  • Service implementation
  • Defining Service input and output attributes
  • Service Event Condition Actions (SECAs)
  • Service groups
  • Handling Service errors
  • Implementing Groovy Services
  • Mail Event Condition Actions (MECAs)
  • Entity Event Condition Actions (EECAs)

 

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

OFBiz has been characterized as having an "event-driven, service-oriented architecture". Long before it was fashionable to build complex enterprise computer systems using service-oriented techniques, OFBiz implemented a number of architectural features enabling a service-oriented design. These features include:

  • A context-aware Service Engine available for use across the entire framework or, if configured, externally through supported network interfaces. OFBiz Service consumers need not concern themselves with the location of the called Service nor with a Service's implementation details. OFBiz handles all that transparently to both the service provider and consumer.
  • Multiple invocation methods including: inline or synchronous with the calling program; out-of-band or asynchronous from the caller's processing logic and/or as a scheduled job for recurring execution. OFBiz handles all input, output, and context parameter transfers seamlessly to both Service provider and Service caller.
  • Chaining of Services for a true, event-driven Service platform and implementation of complex workflows. Services may be configured to be invoked based on external events or triggers. Once triggered, an OFBiz Service may call other Service(s) based on additional triggering Events and/or conditions. Any combination of Services may be chained together to form Service Event Condition Action(s) or SECAs.
  • A fully integrated job scheduler for recurring and single use asynchronous job scheduling. The OFBiz job scheduler handles all the mundane coordination tasks associated with job scheduling, including calendar lookups, frequency, and interval timing.
  • Service creation and implementation tools, including selectable input and output validations based on configured parameter types; authentication and authorization checks integrated with OFBiz user login processing, and even localization preservation across Service calls.

The heart of the OFBiz service-oriented implementation is the Service Engine factory. Using a factory pattern, OFBiz provides an easily extendable Service management and invocation tool supporting any number of concurrent Services and any number of third-party execution engines including, but not limited to: Java, Groovy, Javascript, JPython, and the OFBiz "simple" Service (based on the OFBiz Mini-Language.) By offloading Service implementation to programming language-specific engines, OFBiz Services may be written and implemented in any language that suits the developer's fancy.

The Service Engine factory may be called from anywhere in the framework to handle the details of Service invocation, as shown in the following diagram:

Managing existing OFBiz Services

Out-of-the-box OFBiz comes with many hundreds of Services. To find and otherwise manage OFBiz Services, a fully featured Service management dashboard is provided. Privileged users may conveniently handle all Service related tasks using the OFBiz WebTools toolkit as described.

How to do it...

To access the OFBiz Service management main web page, navigate to the following WebTools URL:

https://localhost:8443/webtools/control/ServiceList

When prompted for a username and password, login as the administrative user (username "admin", password "ofbiz").

How it works...

WebTools provides a dashboard-like UI to view, manage, run, and support OFBiz Services. The main web page for OFBiz Service support is found at:

https://localhost:8443/webtools/ServiceList

(Note the use of case-sensitive addressing). This web page is shown in the following figure:

There's more...

Asynchronous and scheduled Service requests are managed by the OFBiz job scheduler. The job scheduler consists of multiple execution threads as configured in the ~framework/ service/config/serviceengine.xml file. Threads run from one or more thread "pools". From the OFBiz Thread List web page, you may see at a glance the configuration of the OFBiz job scheduler as well as thread and thread pool usage as shown here:

Calling a Service from an HTML form

Services may be called directly from HTML forms by setting the HTML form's action element to point to the URL of a controller.xml request-map that resolves to either an OFBiz Event that calls a Service or directly to a Service. To demonstrate this, the following section uses the WebTool's Run Service HTML form to invoke a Service.

Getting ready

For the purposes of this recipe, we shall use an existing Service called testScv and invoke it from the WebTools UI. In this example, we will not be creating an HTML form nor creating a Service, but rather using an existing form and Service:

  • To view the results of the testScv Service's execution, open an OFBiz console window from the command line
  • Alternatively, to view the results of the execution, run the Unix tail command tail -f ofbiz.log on the ofbiz.log file ~runtime/ofbiz.log while performing this recipe

How to do it...

Services may be called directly from HTML forms by following these steps:

  1. Navigate directly to the Run Service WebTools web page by selecting the Run Service URL: ~webtools/control/runService.
  2. From the Run Service form, enter in testScv in the field labeled Service.
  3. Leave the field labeled Pool as is.
  4. Hit the Submit button to bring up the Schedule Job web page.
  5. On the Schedule Job web page, enter in any values for the requested form fields. These fields correspond to any Service INPUT parameters as configured in the Service definition for testScv.

  6. Hit the Submit button. The testScv has been called by using an HTML form.
  7. To verify that the input parameters entered in step 6 earlier are processed by the testScv, inspect the ofbiz.log file as shown:

How it works...

Any OFBiz Service may be called from an OFBiz webapp HTML form simply by:

  1. Creating an HTML form with an action attribute URL for the target Service.
  2. Creating a controller.xml entry with a request-map for the target Service that matches the HTML form's action URL. For example, the HTML form for the Run Service tool has an action value as shown in the following code snippet:

    <form name= "scheduleForm" method= "POST"
    action= "/webtools/control/scheduleService" />
    <input type="text" name="testScv" />
    <!-- Stuff Intentionally Removed >
    </form>

When the form is submitted, the URL set within the form's action (webtools/control/scheduledService) is intercepted by the WebTools controller servlet, which consults its controller.xml file to determine how to handle this request. The controller.xml entry for this URL is shown here:

<request-map uri="scheduleService">
<security https="true" auth="true"/>
event type="java" path="org.ofbiz.webapp.event.CoreEvents"
invoke="scheduleService"/>
<response name="success" type="view" value="FindJob"/>
<response name="sync_success" type="view" value="serviceResult"/>
<response name="error" type="view" value="scheduleJob"/>
</request-map>

The URL request is mapped to an OFBiz Event called scheduleService. Inside the scheduleService Event, a call is made to the Service Engine to invoke testScv using the Java Service implementation engine as shown in the testScv Service definition file:

<service name="testScv" engine="java" export="true"
validate="false" require-new-transaction="true"
location="org.ofbiz.common.CommonServices" invoke="testScv">
<description>Test service</description>
<attribute name="defaultValue" type="Double"
mode="IN" default-value="999.9999"/>
<attribute name="message" type="String" mode="IN" optional="true"/>
<attribute name="resp" type="String" mode="OUT"/>
</service>

After testScv has been executed, processing control returns to the OFBiz request handler (part of the controller servlet) and then back to the calling webapp as configured in the controller.xml file.

Calling asynchronous Services from HTML forms

You can use WebTools and HTML forms to run a Service asynchronously either one time or on a recurring basis. The following demonstrates the steps necessary to schedule testScv to be executed one time, asynchronously, as a scheduled job.

Getting ready

Navigate directly to the Schedule Job web page.

~https://localhost:8443/webtools/control/scheduleJob

How to do it...

To execute testScv asynchronously follow, these steps:

  1. In the Service form field, enter in testScv as shown in the screenshot.
  2. Leave the Job field empty. OFBiz will pick a unique name automatically.
  3. Use the calendar pop-up icon directly next to the Start Date/Time field to select any date and time after the current wall clock time.

  4. Submit this form by clicking the Submit button to bring up the Service Parameters form, which allows the caller to provide alternative input parameters to the Service.
  5. Add INPUT parameters as shown:
  6. Submit the Service Parameters form. testScv will be scheduled to run at the specified time.

How it works...

Scheduled Services are run asynchronously from the calling program. As such, requests for scheduling are handled by the OFBiz job scheduler. Each scheduled Service is assigned a unique job identifier (jobId) and execution pool by the job scheduler. After the Service is scheduled for execution, control returns to the calling program.

There's more...

Using the OFBiz job scheduler Job List web page, you may find all scheduled jobs. In the following screenshot, testScv is shown as scheduled for execution on the Job List Search Results web page as specified in the recipe:

Because the testScv only writes output to the logfile, we may verify successful execution and scheduling by observing the ofbiz.log runtime logfile as shown:

Calling a Service many times from an HTML form

It is possible to call a Service multiple times from a single HTML form (for example, one time for each row in the form) by placing a line similar to the following with a service-multi event type defined for the controller.xml request-map entry of the target Service.

How to do it...

Follow these steps to call a Service multiple times:

  1. Use the event type service-multi within the controller.xml request-map entry as shown here:

    <request-map uri="someService" />
    <event type="service-multi" invoke="someService"/>
    <!-- Other request-map statements intentionally left out -->
    </request-map>

  2. If using an OFBiz Form Widget, add a line similar to the following to the Form Widget definition. Note, the list-name is the name of the list that is generating multiple rows for the HTML form:

    <form name="someFormName" type="multi" use-row-submit="true"
    list-name="someList" target="someServiceName" /
    <!-- Form fields removed for reading clarity -->
    </form>

  3. If using a FreeMarker template, add lines similar to the following:

    <form name="mostrecent" mode="POST"
    action="<@ofbizUrl>someService</@ofbizUrl>"/>
    <#assign row=0/>
    <#list someList as listItem>
    <#-- HTML removed for reading clarity.
    Each row has a unique input name associated with it
    allowing this single Form to be submitted to the
    "someServiceName" Service from each row -->
    <input type="radio" name="someFormField_o_${row}"
    value="someValue" checked/>
    <input type="radio" name="someFormField_o_${row}"
    value="someValue"/>
    </#list>
    </form>

How it works...

The Event type service-multi provides a convenient shortcut for coding HTML forms that are embedded within lists. Each list item is automatically converted to a unique form field so that a single Service may be called from any row within the list.

Apache OfBiz Cookbook Over 60 simple but incredibly effective recipes for taking control of OFBiz
Published: September 2010
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

Read more about this book

(For more resources on Apache see here.)

Creating a new Service definition file

Services are defined in Service definition XML document files. By convention, Service definition files are located in a containing Component's servicedef directory. This may be changed by editing the Component's ofbiz-component.xml file.

How to do it...

To define a new Service definition file, follow these few steps:

  1. Check the ofbiz-component.xml file to make sure there is a location pointer to the Service definition file. For example:

    <!-- For Service Definition files, use the following -->
    <service-resource type="model" loader="main"
    location="servicedef/Services.xml"/>
    <!-- For Service Event Control Action files, use the following -->
    <service-resource type="eca" loader="main"
    location="servicedef/secas.xml"/>
    <!-- For Service Group Definition files, use the following -->
    <service-resource type="group" loader="main"
    location="servicedef/groups.xml"/>

  2. Using your favorite operating system editor or IDE tool, add Service definition files in the directory locations specified in the ofbiz-component.xml file shown earlier. Make sure each file has the appropriate XML version and XSD declarations in the beginning of the file, as follows:

    <?xml version="1.0" encoding="UTF-8"?>
    <services xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation=
    "http://ofbiz.apache.org/dtds/services.xsd">

  3. Make sure the new Service definition file has a closing tag.
  4. Insert as many Service definitions within this file as needed.
  5. Save and close the file.
  6. Restart OFBiz to make any changes to the ofbiz-component.xml file effective.

How it works...

OFBiz is made aware of Service definition files by placing one or more declarations about the definition files within a Component's ofbiz-component.xml file. There is one such declaration for each Service definition file located within the containing Component. Each declaration instructs OFBiz as to what types of definitions are found in the file and the location of the file relative to the Component's root. There is no limit to the number of Service definition file declarations that may be included in a single ofbiz-component.xml file.

Creating a new Service definition

OFBiz is made aware of a Service by the presence of a Service definition within a Service definition file. Each OFBiz Service has a Service definition that configures the Service with a name, location information, Service implementation engine type, and other optional parameters.

How to do it...

To create a new Service definition, follow these steps:

  1. Find an existing Service definition file or create a new one.
  2. Add one or more service element XML declarations. For example:

    <service name="someName" engine="one_of_the_available_engines"
    location="component_or_CLASSPATH_location"
    <!-- Add any INPUT/OUTPUT attribute elements here -->
    <!-- Add a PERMISSION-SERVICE element -->
    <!-- For Simple Services, add any AUTO-ATTRIBUTE elements -->
    </service>

  3. Make sure the new Service definition element has a closing tag.
  4. Save and close the file.
  5. Restart OFBiz.

How it works...

Using Service definitions, OFBiz removes Service location and implementation details from the Service and "injects" these values at runtime. This enables the Service developer to concentrate on implementing business logic and the Service consumer to call the Service without regard for location or implementation details.

When a Service is called, OFBiz automatically locates the Service on the CLASSPATH by consulting the Service's Service definition, manages all defined context parameters and passes control to the appropriate Service implementation engine.

Implementing Services

Services may be implemented—that is, developed in any language—for which there is a corresponding Service implementation engine. As of this writing, Service Engines supported include, but are not limited to: Java, Groovy, BeanShell, Mini-Language, Jacl, Javascript, JPython.

Getting ready

Before starting work on any new Service, you must first decide which tool to use to develop your Service. For simple database read, write, and update processing, you may want to use the OFBiz Mini-Language tool to develop "simple Services". Simple Services consist of one or more XML declarations instructing OFBiz on how to handle business processing tasks. For those who prefer to use procedural languages such as Java or Groovy, these options are available as well.

How to do it...

To implement a Service definition, follow these steps:

  1. Create a new Service definition.
  2. Create the Service implementation using a tool of choice (Java, Mini-Language, Groovy).
  3. For Java Services, you must rebuild the component containing the Java code. For Mini-Language and other scripting tools such as Groovy, there is no need to rebuild the Component.
  4. Restart OFBiz.
  5. Test the Service definition.

How it works...

A Service's Service definition describes to OFBiz how a Service is implemented and where it is located on the runtime CLASSPATH. To create a new Service requires only an implementation of the Service (using a supported programming tool) and a proper Service definition entry in a valid Service definition file.

Defining Service attributes (INPUT/OUTPUT)

Service input and output parameters are defined within the Service's definition using XML declaration statements with an element tag of attribute. Each XML attribute element declaration represents either an input parameter (INPUT), an output parameter (OUTPUT), or a parameter that is passed as both input and output (INOUT). The participation of each parameter as an input or output value may be made optional by adding an optional attribute to the declaration. By default, the optional value is false, and all parameters that are defined are required to be passed. This means that the Service will fail if one or more of the configured (non-optional) parameters are not passed.

Note: If an INPUT parameter is not defined for a Service, then that value will not be passed into the Service's execution context regardless of the values that are sent by the calling program. Similarly, if an OUT or INOUT parameter is not defined for a value, then that value will not be passed back to the calling program.

How to do it...

Add one or more attribute elements within the Service definition. For example:

<service name="myService" engine="SupportedEngine"
location="somewhere.on.the.classpath" invoke="myService">
<attribute name="attribute1" type="String" mode="IN"
optional="true"/>
<attribute name="attribute2" type="String" mode="IN"
optional="false"/>
<attribute name="attribute3" type="String" mode="INOUT"/>
</service>

How it works...

The OFBiz Service Engine handles the passing of input, output, and context parameters automatically based on the Service's Service definition. Only parameters configured for the Service (and several OFBiz managed context parameters such as the userLogin GenericValue, locale, timeZone, errorMessage, and errorMessageList) will be passed as input or as output.

By default, OFBiz automatically validates, at runtime, all incoming and outgoing parameters against the defined type attribute as configured. Validation failures will cause the Service to fail and control will be passed back to the calling program.

Service Event Condition Actions

Service Event Condition Actions (SECAs) are a powerful tool used to build complex business processing solutions out of one or more OFBiz Service(s). With SECAs, you may associate one or more Services together to form a chain of processing logic based on defined triggering events and conditions.

There are no limits on the number of SECAs supported by OFBiz, or in the number of Services that may participate within a single SECA.

Getting ready

Writing SECAs is simple. To write a SECA, you will need one or more Services to participate as either the action Service and/or the target Service. Once you have your Services defined:

  1. Find or create a new SECA definition XML document. The SECA definition document must have the following XML line at the top of the file:

    <?xml version="1.0" encoding="UTF-8" ?>

  2. Followed by the SECA XML schema declaration:

    <service-eca xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation=
    "http://ofbiz.apache.org/dtds/service-eca.xsd">

How to do it...

Once the groundwork is laid, you can write SECAs by following these steps:

    Create an ECA definition within a SECA definition file by adding an eca element with a service attribute similar to the following (Note: the following XML declarations are for illustration purposes only. Please substitute real values where appropriate):

    <eca service="eca_service_name" event="required_some_event_name"
    run-on-failure="optional_true_or_false"
    run-on-error="optional_true_or_false"
    type="optional_some_type" format="optional_some_format" >

  1. Optionally, add one ore more condition elements:

    <condition field-name="some_name" operator="operator_values"
    value="some_value" type="supported_types" />

  2. Optionally, add on or more set elements as input parameters or to format an existing parameter:

    <set field-name="some_field" value="some_value"
    format="some_format" />

  3. Add one or more action declarations. Each action declaration calls a Service to perform some action as shown below. The Service called may have the same name as the ECA:

    <action service="some_service_to_call" mode="some_mode"
    run-as-user="optionally_set_to_a_user" />

  4. Don't forget to close the eca service element with an end tag.
  5. Close and save the file.
  6. Restart OFBiz to make the SECA(s) configuration effective.

How it works...

When a Service is called, the first thing the OFBiz Service Engine does, even before assigning a Service implementation engine, is to check for any defined ECAs. If one or more ECAs exists for a Service, each ECA is processed before the initial target Service is invoked.

Note: Some ECAs perform actions on the output of a Service. In such cases, while the ECA itself is processed before the call to the Service, actions defined within the ECA may be invoked after the target Service is run.

In this way, it is possible to combine together any number of Services using any combination of conditions and Events, and thus solve complex business problems using one or more discrete OFBiz Services.

Apache OfBiz Cookbook Over 60 simple but incredibly effective recipes for taking control of OFBiz
Published: September 2010
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

Read more about this book

(For more resources on Apache see here.)

Service groups

Service "groups" are a technique for grouping together Services where there is a need to run all the Services together.

Getting ready

Create or find an existing Service group definition XML document. This XML document will have an XML version declaration as follows:

<?xml version="1.0" encoding="UTF-8" ?>

And a Service group XML schema declaration as shown:

<service-group xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation=
"http://ofbiz.apache.org/dtds/service-group.xsd">

If creating a new Service group definition XML document, ensure that this document is configured in the containing Component's ofbiz-component.xml file. For example, if creating a Service group definition XML document in the servicedef directory, add a line similar to the following to the ofbiz-component.xml file:

<service-resource type="group" loader="main"
location="servicedef/groups.xml"/>

How to do it...

To group Services together, follow these steps:

  1. Add one or more group elements as shown here. Each group element defines a Service group:

    <group name="updateCreditCardAndAddress" send-mode="all"> </group>

  2. Within each group element, add one or more invoke declaration(s). Each invoke declaration points to a Service:

    <invoke name="createPostalAddress" mode="sync"
    result-to-context="true"/>
    <invoke name="createCreditCard" mode="sync"/>
    <invoke name="createPartyContactMech" mode="sync"/>

  3. Close each element with an end tag.
  4. Save the file.
  5. Restart OFBiz to make Service group definitions effective.

How it works...

Service groups are a set of Services that should all run as a result of the initial Service call. Unlike SECAs, where conditions and triggers determine which Services will be run during any particular invocation, Service groups are used to indicate that all Services within the group should be run. Note, it is possible to have Service groups with participating Services that have SECAs defined.

The following table provides some of the more often used Service group configuration elements. Attribute values include:

To configure one or more Services within a group element declaration, add invoke elements configured as follows:

Handling Service errors

OFBiz Services may complete successfully or return to the caller with one or more errors. Upon successful completion of a Service, OFBiz automatically commits any database transactions and maps the return parameters to the context before returning control to the caller.

If a Service encounters an error and returns to the caller through an error processing path, OFBiz will automatically rollback all transactions initiated for the Service and/or SECAs regardless of the Service definition settings. To manage error processing from within a Service implementation, use the OFBiz-provided Service utility API as shown in this recipe.

Getting ready

The following examples assume a Service implemented in Java. Other Service Engine supported languages will behave in a similar fashion, although utility usage (API) details may vary.

For Java and Groovy programs, be sure to include the OFBiz Service utility program with a Java package import statement:

import org.ofbiz.service.ServiceUtil;

How to do it...

From within the Service's implementation, use the provided OFBiz utilities to control error message handling, including transaction rollback:

  • To return an error message and have OFBiz manage transaction rollback from within a Java Service, add one or more lines similar to the following where appropriate:

    org.ofbiz.service.ServiceUtil.returnError(
    "An Error Message Here");

  • To return a list of error messages and have OFBiz manage transaction rollback from within a Java Service, add one or more lines similar to the following:

    // Don't forget to include imports for FastList
    List<Object> errMsgList = FastList.newInstance();


    // Add error messages to the errMsgList () for example
    errMsgList.add("A new error message");
    return ServiceUtil.returnError(errMsgList);

  • To return an error message and have the error message localized based on the value of the locale context variable, add code similar to the following:

    // Note, don't forget to import Map, UtilMisc, and
    // UtilProperties to use this snippet
    Map messageMap = UtilMisc.toMap("errMessage", e.getMessage());
    errMsg = UtilProperties.getMessage("CommonUiLabels",
    "CommonDatabaseProblem", messageMap, locale);
    return ServiceUtil.returnError(errMsg)

  • To return an error and instruct OFBiz to NOT rollback transactions, add one or more lines similar to the following:

    org.ofbiz.service.ServiceUtil.returnFailure(
    "Some error message, but don't roll back transactions");

  • To pass Service errors from one Service call to another, simply use the ServiceUtil.returnError methods and include the error message or list of messages as method parameters.
  • To easily retrieve an error message from the results of a Service call:

    Map results = dispatcher.runSync("SomeService", inputMap);
    String errMsg = ServiceUtil.getErrorMessage(results);

  • To check if the results from a Service call contain any errors:

    if(ServiceUtil.isError(someResult) ||
    ServiceUtil.isFailure(someResult))
    {
    return someValue;}

How it works...

The OFBiz best practice and convention for passing error messages from Services (and OFBiz Events) to calling programs is to use the following request attributes:

  • _ERROR_MESSAGE_ for a single error message
  • _ERROR_MESSAGE_LIST_ for a list of error messages where the list consists of one or more Java strings and each string contains an error message

When using the ServiceUtil error processing utilities to return from Service when an error is encountered, OFBiz will automatically map error messages and lists of error messages to the proper HTTP/HTTPS request object attribute(s).

Writing Groovy Services

While Groovy is normally used for data preparation, this and other integrated scripting languages may be used to implement OFBiz Services. Using a scripting language to implement a Service has the advantage that the Service does not need to be compiled nor the containing Component rebuilt prior to use.

Getting ready

Make sure you have a "local dispatcher" and "local delegator" (if you want to use database Services) defined in the web.xml file, then follow these steps:

  1. Check the web.xml file and make sure there is a local dispatcher and local delegator defined for the Component from which you will be calling the Service. For example:

    <context-param>
    <param-name>localDispatcherName</param-name>
    <param-value>example</param-value>
    <description>
    A unique name used to identify the local dispatcher for the
    Service Engine
    </description>
    </context-param>

    <context-param>
    <param-name>entityDelegatorName</param-name>
    <param-value>default</param-value>
    <description>
    The Name of the Entity Delegator to use,
    defined in entityengine.xml
    </description>
    </context-param>

  2. Create the Service definition within an existing Service definition file. Note, any changes to the Service definition such as adding or removing input and/or output parameters require an OFBiz restart to become effective:

    <service name="myGroovyService" engine="groovy"
    location="component://myComponent/script/myGroovyService.groovy"
    invoke="">
    </service>

  3. Restart OFBiz to ensure the Service's configuration (definition) is read and reloaded.
  4. To test this Service from a web page, create a controller.xml request-map to call and test this Service from a webapp web page. For example, to call the Service in step 2:

    <!-- ======= Testing a groovy Service ===== -->
    <request-map uri="testGroovyService">
    <security https="false" auth="false"/>
    <event type="service" invoke="myGroovyService"/>
    <response name="success" type="view" value="main"/>
    <response name="error" type="view" value="main"/>
    </request-map>

  5. To test this Service from a web page, create a HTML form or link. For example, to call the Service with a request-map set to testGroovyService as shown in step 3, you might write something like the following:

    <a href="<@ofbizUrl>testGroovyService</@ofbizUrl>">
    test groovy Service
    </a>

How to do it...

Implement your Service by writing the Groovy script and saving it in the location and file specified in the Service's definition location attribute value. Note, to tell OFBiz to execute the Groovy script from top to bottom, leave the invoke parameter empty.

Unlike Java-based Services, there is no need to compile or restart OFBiz to make a Groovy Service immediately effective. Remember, however, that Service definition changes do require an OFBiz restart.

How it works...

Use of OFBiz Service implementation engines such as the Groovy engine make OFBiz Services implementation agnostic. Callers do not need to know that the Service is written in Groovy, and Groovy programmers do not need to concern themselves with the details of calling programs.

To make OFBiz aware that a Service is available and written in Groovy, simply indicate that the Service is to use the Groovy Service Engine by setting the service element's engine attribute value to groovy. OFBiz takes care of the rest.

Mail Event Condition Actions

To handle incoming e-mail automatically through the Service Engine interface, use Mail Event Condition Actions (MECAs).

Note: The OFBiz processes for handling incoming e-mail are not the same as those for sending e-mail. To configure OFBiz to send e-mail, please see the ~framework/common/config/general. properties file.

Getting ready

A few steps to ensure before we can use Services to handle e-mail:

  1. To trigger one or more Services based on the receipt of incoming e-mail, you will need to enable the OFBiz inbound e-mail listener by removing the appropriate comments from the JavaMail Listener Container entry in ~framework/base/config/ofbiz-containers.xml.
  2. Implement one or more Services using a Service implementation language of your choice to handle processing based on the occurrence of a mail Event.

How to do it...

Configure the MECA as shown in the following steps:

  1. If one does not already exist, add a declaration to an ofbiz-component.xml file with a location pointer to the MECA definition file, as shown:
  2. <service-resource type="mca" loader="main"
    location="servicedef/mca.xml"/>

  3. Create a new MECA definition file or use an existing one. A valid MECA definition file will have the XML version declaration and a service-mca XML schema declaration element, as shown:

    <?xml version="1.0" encoding="UTF-8"?>
    <service-mca xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation=
    "http://ofbiz.apache.org/dtds/service-mca.xsd">

  4. Add one or more mca elements as needed. Each MCA action element locates one or more Services:

    <mca mail-rule-name="processIncomingEmail">
    <action service="storeIncomingEmail" mode="sync"/>
    </mca>

  5. Close all elements with closing tags.
  6. Save and close the file.
  7. Restart OFBiz to make the MCAs effective.

How it works...

The OFBiz e-mail listener process has been implemented to trigger any defined MECAs when an incoming e-mail is detected.

To set the conditions under which the MECA should fire, add one or more condition-field elements with configuration settings, as shown here:

Entity Event Condition Actions

It is possible to write ECAs for specific entities using an Entity Event Condition Action (EECA). For example, to trigger an Event, say a notification Service, when a field in an entity changes, you could write an EECA as we shall see in this recipe.

How to do it...

Triggering a notification Service using EECA can be done by following these steps:

  1. If one does not already exist, add an entry in the ofbiz-component.xml file to identify the EECA definition file location as shown:

    <entity-resource type="eca" reader-name="main" loader="main"
    location="entitydef/eecas.xml"/>

  2. Create or add an EECA definition file with an XML version declaration and an XML XSD schema declaration, as shown here:

    <?xml version="1.0" encoding="UTF-8"?>
    <entity-eca xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation=
    "http://ofbiz.apache.org/dtds/entity-eca.xsd">

  3. Add one or more EECA definitions to the EECA definition file. Don't forget to close each eca element declaration with a closing tag ().

    <!-- To maintain FinAccount.actualBalance and
    FinAccount.availableBalance -->
    <eca entity="FinAccountTrans" operation="create-store"
    event="return">
    <action service="updateFinAccountBalancesFromTrans"
    mode="sync"/>
    </eca>

  4. Be sure to close all XML element tags.
  5. Save and close the EECA definition file.
  6. Restart OFBiz to make the changes effective.

How it works...

EECA rules are checked before and/or after a call to access the database. Services defined by the action element are invoked when the configured entity is accessed by way of the operation attribute setting.

There's more...

Commonly used EECA attribute values are shown in the following table:

To configure action elements for an EECA, the following configuration attribute values are supported:

To add one or more triggering conditions, add condition element declarations with the appropriate settings:

set elements are used to equate entity field(s) or context variables to values. set declarations may be configured as shown:

Summary

In the above article we have covered:

  • Managing OFBiz Services
  • Calling asynchronous, synchronous, and recurring Services from an HTML form
  • Creating a Service definition file
  • Creating a Service definition
  • Service implementation
  • Defining Service input and output attributes
  • Service Event Condition Actions (SECAs)
  • Service groups
  • Handling Service errors
  • Implementing Groovy Services
  • Mail Event Condition Actions (MECAs)
  • Entity Event Condition Actions (EECAs)

Further resources on this subject:


About the Author :


Ruth Hoffman

An OFBiz evangelist with over 25 years of information technology experience including stints in software design and development, training, project management, product marketing and software sales, Ruth has dedicated the last few years of her eventful career to furthering the OFBiz vision. Whether it be writing about OFBiz, providing implementation and OFBiz consulting services or just “kicking the OFBiz tires” for each new release, she enjoys working with and telling the world about all that this amazing ERP software suite has to offer.
Ruth’s current passion is her quest to provide high quality, cost effective OFBiz training and documentation. She has pursued this quest through multiple channels including the myofbiz.com website. She invites everyone to stop by, take a gander and give some feedback: http://www.myofbiz.com
As a long standing supporter of OFBiz, she has authored several other OFBiz titles including “OFBiz E-Commerce Out-Of-The-Box” and “The OFBiz Catalog Manager” For more information, please see: http://www.myofbiz.com.
Acknowledgements
I’d like to thank my partner, JC,  for being so patient and understanding, my daughter for not getting too upset when I cancelled our planned Lilac Festival adventure and my dog Sadie for sitting by me all those long hours when no one else would.
Also, my sincerest thanks go to Adrian Crum and Shi Jinghai for their dedicated efforts in providing technical review of this book. Thanks for keeping me honest and setting me straight on a number of occasions. Your contributions are greatly appreciated!

Books From Packt


Apache MyFaces 1.2 Web Application Development
Apache MyFaces 1.2 Web Application Development

Apache Roller 4.0 – Beginner's Guide
Apache Roller 4.0 – Beginner's Guide

Apache MyFaces Trinidad 1.2: A Practical Guide
Apache MyFaces Trinidad 1.2: A Practical Guide

Apache CXF Web Service Development
Apache CXF Web Service Development

Apache Geronimo 2.1: Quick Reference
Apache Geronimo 2.1: Quick Reference

Apache Maven 2 Effective Implementation
Apache Maven 2 Effective Implementation

Apache Struts 2 Web Application Development
Apache Struts 2 Web Application Development

Apache JMeter
Apache JMeter


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
U
B
5
A
q
n
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software