Announcement: You can find the guides for Commerce 7.5 and later on the new Elastic Path Documentation site. The Developer Center continues to support Commerce 6.13.0 through 7.4.1.Visit new site

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 and OSGi.

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:
<dependency>
  <groupId>com.elasticpath.rest</groupId>
  <artifactId>cortex-jaxrs-client</artifactId>
  <version>${java.cortex.jaxrs.client.version}</version>
</dependency>

<dependency>
  <groupId>com.elasticpath.rest</groupId>
  <artifactId>cortex-jaxrs-client</artifactId>
  <version>${java.cortex.jaxrs.client.version}</version>
  <classifier>javadoc</classifier>
</dependency>

<dependency>
  <groupId>com.elasticpath.rest</groupId>
  <artifactId>cortex-jaxrs-client</artifactId>
  <version>${java.cortex.jaxrs.client.version}</version>
  <classifier>sources</classifier>
</dependency>

Usage

Cortex Java SDK is based on the JAX-RS Java API and includes a set of extensions to facilitate development with Cortex.

Authentication

Cortex Java SDK should be configured to perform OAuth2 authentication with Cortex by creating and registering a OAuth2RequestFilter object as shown below:
OAuth2Token oAuth2Token = new OAuth2Token();
oAuth2Token.setHeaderValue(authenticationToken);
OAuth2RequestFilter oAuth2RequestFilter = new OAuth2RequestFilter(oAuth2Token);
 
Client client =  Client.newClient()
  .register(jacksonProvider)
  .register(jsonUnmarshallReaderInterceptor)
  .register(oAuth2RequestFilter)
  .register(new WebApplicationExceptionMapper());

Sending Requests

Sending requests with a JAX-RS client are well documented here. The following example shows how to unmarshal a simple Cortex GET request:

Response response = client.target("http://localhost:9080/cortex/carts/geometrixx/default/")
    .request()
    .get();
CartView cart = response.readEntity(CartView.class);

CartView is a custom class with @JsonPath and @JsonProperty annotations, which are described later in this document.

Constructing URIs

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

  • @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.

Example: Zoom and FollowLocation

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

@Zoom(@Path("order"))
@FollowLocation
public class Cart {}
URLs with Zoom or FollowLocation query parameters can be constructed by calling the createResourceUrlWithQueryParameters method:
baseUrl = "http://localhost:9080/cortex/"
path = "carts/geometrixx/default"
result = cortexUrlFactory.addQueryParametersToResourceUrl(baseUrl, path, Cart.class)
//result = "http://localhost:9080/cortex/carts/geometrixx/default?zoom=order&followLocation=true"

Example: Without Query Parameters

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

Example: With Entry Point Resource

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

@EntryPointUri(“carts/{scope}/default”)
@Zoom(@Path("lineitems"))
@FollowLocation
public class Carts {}
URLs using entry point URIs can be constructed by calling the createResourceUrlFromAnnotations method:
baseUrl = “http://localhost:9080/cortex/”
store = “geometrixx”
result = cortexUrlFactory.createResourceUrlFromAnnotations(baseUrl, store, Carts.class)
//result = "http://localhost:9080/cortex/carts/geometrixx/default?zoom=lineitems&followLocation=true" 

Unmarshalling Cortex Responses

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:
{
  "self": {
    "type": "elasticpath.carts.cart",
    "uri": "/carts/mobee/gwu=?zoom=lineitems:element",
    "href": "http://api.demo.elasticpath.com/cortex/carts/mobee/gwu=?zoom=lineitems:element",
    "max-age": 0
  },
  "total-quantity": 1,
  "_lineitems": [
    {
      "_element": [
        {
          "self": {
            "type": "elasticpath.carts.line-item",
            "uri": "/carts/mobee/gwu=/lineitems/gq4=",
            "href": "http://api.demo.elasticpath.com/cortex/carts/mobee/gwu=/lineitems/gq4=",
            "max-age": 0
          },
          "links": [
            {
              "rel": "list",
              "type": "elasticpath.collections.links",
              "uri": "/carts/mobee/gwu=/lineitems",
              "href": "http://api.demo.elasticpath.com/cortex/carts/mobee/gwu=/lineitems"
            }
          ],
          "quantity": 1
        }
      ]
    }
  ],
  "links": [
    {
      "rel": "lineitems",
      "rev": "cart",
      "type": "elasticpath.collections.links",
      "uri": "/carts/mobee/gwu=/lineitems",
      "href": "http://api.demo.elasticpath.com/cortex/carts/mobee/gwu=/lineitems"
    },
    {
      "rel": "order",
      "rev": "cart",
      "type": "elasticpath.orders.order",
      "uri": "/orders/mobee/hbr=",
      "href": "http://api.demo.elasticpath.com/cortex/orders/mobee/hbr="
    },
    {
      "rel": "total",
      "rev": "cart",
      "type": "elasticpath.totals.total",
      "uri": "/totals/carts/mobee/gwu=",
      "href": "http://api.demo.elasticpath.com/cortex/totals/carts/mobee/gwu="
    }
  ]
}

Example: Extract JSON Property using @JsonProperty

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

Example: Extract Nested JSON Properties using @JsonPath

Extract nested JSON properties:
public class Cart {
  //Non-nested JSON property
  @JsonPath("$.total-quantity")
  private int totalQuantity;

  //Nested Property
  @JsonPath("$._lineitems[0]._element[0].quantity")
  private int quantity;

  //Nested Array 
  @JsonPath("$._lineitems[0]._element")
  private List<LineItem> lineItems;
}