Announcement: You can find the guides for Commerce 7.5 and later on the new Elastic Path Documentation site. This site contains the guides for Commerce 6.13.0 through 7.4.1.Visit new site

This version of Elastic Path Commerce is no longer supported or maintained. To upgrade to the latest version, contact your Elastic Path representative.

Learning to use Cortex Java SDK

Learning to use Cortex Java SDK

Cortex Java SDK can consume Cortex resources in client applications that are built with Java.

Setup

Cortex Java SDK is available from the Elastic Path Public Maven Repository.

To add Cortex Java SDK to your OSGi project, add the following dependencies to your Maven POM:
  1. <dependency>
  2. <groupId>com.elasticpath.rest</groupId>
  3. <artifactId>cortex-jaxrs-client</artifactId>
  4. <version>2.0.0</version>
  5. </dependency>

Copy

Usage

Cortex Java SDK is based on the JAX-RS Java API and includes a set of extensions to facilitate development with Cortex. The SDK provides both a straight JAX-RS Client service as well as a user-scoped Cortex client that scopes Cortex calls to a specific user.

JAX-RS Client

The JAX-RS Client can call any REST service, not just Cortex. The client is injected via an OSGi SCR annotation:

  1. @Reference
  2. javax.ws.rs.client.Client jaxrsClient;

Copy

JAX-RS Client Configuration

To configure the JAX-RS client instance, edit its settings through the OSGi admin console. Additionally, you can add and remove ClientConfigurator services through the admin console.

The JAX-RS Client includes the following Client Configurators:
Name Details
apache-connector Configures the JAX-RS client to use the Apache HttpClient Connector. If this configuration is removed, JAX-RS will fall back to using Java's default HttpURLConnection.
jackson Supplies a Jackson ObjectMapper for JAX-RS to use for JSON marshalling.
json-unmarshaller Instructs JAX-RS to utilize Elastic Path's JSON Unmarshaller to map JSON data into data objects.

CortexClient

The Cortex client provides the following:
  • A user-scoped wrapper around the JAX-RS client to facilitate REST calls to Cortex
  • JSON Unmarhsaller types to marshall/unmarshal JSONs
Tip: Storing Client Instances

Client instances should not be stored between requests.

Using Cortex Client in an OSGi Environment

CortexClientFactory provides the Cortex client instance. To obtain an new Cortex client instant, inject the Factory and pass in a MultiValuedMap with the header and the scope (the store code) to the factory.
  1. @Reference
  2. com.elasticpath.rest.client.CortexClientFactory clientFactory;
  3. ...
  4. MultivaluedMap<String, Object> headers = new MultivaluedHashMap<String, Object>();
  5. headers.putSingle(HeaderKeys.X_EP_USER_ID_KEY, "customerId");
  6. headers.putSingle(HeaderKeys.X_EP_USER_ROLES_KEY, "PUBLIC");
  7. headers.putSingle(HeaderKeys.AUTHORIZATION_KEY, "authToken");
  8. com.elasticpath.rest.client.CortexClient client = clientFactory.create(headers, scope);

Copy

Using Cortex Client in an Non-OSGi Environment

To use the Cortex client in a non-OSGi environment, you need to manually instantiate the required beans. The following example shows how to use a Spring application context with the Cortex client.
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans
  3. xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
  7.  
  8. <bean id="jacksonObjectMapper" class="com.elasticpath.example.ApplicationObjectMapper" init-method="init"/commerce-legacy/>
  9. <!-- Note that this is a custom com.fasterxml.jacson.databind.ObjectMapper extension which disables the
  10. FAIL_ON_UNKNOWN_PROPERTIES on initialization. this.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) -->
  11. <bean id="jsonUnmarshaller" class="com.fasterxml.jackson.contrib.jsonpath.DefaultJsonUnmarshaller"/commerce-legacy/>
  12. <bean id="zoomModelIntrospector" class="com.elasticpath.rest.client.urlbuilding.zoom.ZoomModelIntrospector"/commerce-legacy/>
  13. <bean id="zoomQueryFactory" class="com.elasticpath.rest.client.urlbuilding.zoom.ZoomQueryFactory"/commerce-legacy/>
  14. <bean id="cortexUrlFactoryImpl" class="com.elasticpath.rest.client.urlbuilding.impl.CortexUrlFactoryImpl">
  15. <constructor-arg ref="zoomModelIntrospector"/commerce-legacy/>

Copy

...
Read more

  1. ...
  2. public CortexClientFactory exampleCortexClientFactorySetup(final ApplicationContext context) {
  3. ClientConfig clientConfig = new ClientConfig();
  4. clientConfig.register(new WebApplicationExceptionMapper())
  5. .register(jacksonProvider)
  6. .register(jsonUnmarshallReaderInterceptor)
  7. .register(new LoggingFilter(Logger.getLogger(App.class.getName()), true)) // Should be configurable at runtime
  8. .property(ClientProperties.CONNECT_TIMEOUT, CONNECT_TIMEOUT) // Should be configurable at runtime
  9. .property(ClientProperties.READ_TIMEOUT, READ_TIMEOUT); // Should be configurable at runtime
  10. //Real implementation will want to pass configurable values to this builder.
  11. HttpClientConfigurator httpClientConfigurator = new HttpClientConfiguratorBuilder().build();
  12. httpClientConfigurator.configure(clientConfig);
  13. Client jaxRsClient = ClientBuilder.newClient(clientConfig);
  14. CortexUrlFactory cortexUrlFactory = (CortexUrlFactory) context.getBean("cortexUrlFactoryImpl");
  15. //Cortex url should be configurable at runtime.

Copy

...
Read more

Sending Requests

Once a client is obtained, it can be used to fetch a view:

  1. CartView cart = client.get(CartView.class);

Copy

CartView is a custom class with @JsonPath and @JsonProperty annotations.

Constructing URIs

Cortex Java SDK provides four class level annotations to construct Cortex resource URLs:

  • @EntryPointUri: Defines the URI of a Cortex entry point resource.
  • @Zoom: Adds a Zoom query parameter to the request URL.
  • @Path: Used together with @Zoom, @Path specifies the relation/link to follow from the Zoom request.
  • @FollowLocation: Adds a FollowLocation query parameter to the request URL.

Example: Zoom and FollowLocation

A class that models the expected response should be annotated as follows:

  1. @Zoom(@Path("order"))
  2. @FollowLocation
  3. public class Cart {}

Copy

URLs with Zoom or FollowLocation query parameters can be constructed by calling the createResourceUrlWithQueryParameters method:
  1. baseUrl = "http://localhost:9080/cortex/"
  2. path = "carts/mobee/default"
  3. result = cortexUrlFactory.addQueryParametersToResourceUrl(baseUrl, path, Cart.class)
  4. //result = "http://localhost:9080/cortex/carts/mobee/default?zoom=order&followLocation=true"

Copy

Example: Without Query Parameters

URLs without query parameters can be constructed by calling the createResourceUrl method:
  1. baseUrl = "http://localhost:9080/cortex/"
  2. path = "carts/mobee/default"
  3. result = cortexUrlFactory.createResourceUrl(baseUrl, path)
  4. //result = "http://localhost:9080/cortex/carts/mobee/default"

Copy

Example: With Entry Point Resource

A class that models the expected response should be annotated as follows:

  1. @EntryPointUri(“carts/{scope}/default”)
  2. @Zoom(@Path("lineitems"))
  3. @FollowLocation
  4. public class Carts {}

Copy

URLs using entry point URIs can be constructed by calling the createResourceUrlFromAnnotations method:
  1. baseUrl = http://localhost:9080/cortex/”
  2. store = mobee
  3. result = cortexUrlFactory.createResourceUrlFromAnnotations(baseUrl, store, Carts.class)
  4. //result = "http://localhost:9080/cortex/carts/mobee/default?zoom=lineitems&followLocation=true"

Copy

Unmarshalling Cortex Responses

Cortex Java SDK unmarshalling is provided by the Elastic Path JSON Unmarshaller, an open source project. This section shows some simple examples of how to use the JSON Unmarshaller. For more complex unmarhalling examples, see the JSON Unmarshaller project page.

Cortex Java SDK provides two annotations to extract data from a Cortex response:

  • @JsonProperty: Extracts a JSON property from a Cortex response.
  • @JsonPath: Uses JSONPath to extract either a single or multiple JSON properties from a Cortex response. This annotation is useful to extract nested JSON properties.
    Tip: JSONPath Expression Tester

    Cortex Studio comes bundled with a JSONPath tester for creating and testing JSONPath expressions.

The examples below parse this response:
  1. {
  2. "self": {
  3. "type": "elasticpath.carts.cart",
  4. "uri": "/commerce-legacy/carts/mobee/gwu=?zoom=lineitems:element",
  5. "href": "http://api.demo.elasticpath.com/cortex/carts/mobee/gwu=?zoom=lineitems:element"
  6. },
  7. "total-quantity": 1,
  8. "_lineitems": [
  9. {
  10. "_element": [
  11. {
  12. "self": {
  13. "type": "elasticpath.carts.line-item",
  14. "uri": "/commerce-legacy/carts/mobee/gwu=/lineitems/gq4=",
  15. "href": "http://api.demo.elasticpath.com/cortex/carts/mobee/gwu=/lineitems/gq4="

Copy

...
Read more

Example: Extract JSON Property using @JsonProperty

Extract a single, non-nested, JSON property:
  1. public class Cart {)
  2. @JsonProperty("total-quantity")
  3. private String totalQuantity;
  4. }

Copy

Example: Extract Nested JSON Properties using @JsonPath

Extract nested JSON properties:
  1. public class Cart {
  2. //Non-nested JSON property
  3. @JsonPath("$.total-quantity")
  4. private int totalQuantity;
  5.  
  6. //Nested Property
  7. @JsonPath("$._lineitems[0]._element[0].quantity")
  8. private int quantity;
  9.  
  10. //Nested Array
  11. @JsonPath("$._lineitems[0]._element")
  12. private List<LineItem> lineItems;
  13. }

Copy