Announcement: You can find the guides for Commerce 7.5 and later on the new Elastic Path Documentation site. This Developer Center 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.

Interfacing With Commerce Engine

Interfacing With Commerce Engine

Warning: Before you begin

This tutorial assumes you have created the terms and conditions resource in Writing Your First Resource.

Commerce Engine is the heart of Elastic Path's e-commerce system and is responsible for executing e-commerce operations, such as adding to cart, updating customer profiles, and so on. To call down into Commerce Engine to run operations, Cortex resources use lookups to read data, and writers to create, update, and delete data. For an example of a call progressing through Cortex architecture to Commerce Engine, see Cortex Call Stack.

In this tutorial, you will learn how to:
  • Add a lookup strategy interface to the terms and conditions resource you created in Writing Your First Resource.
  • Create a resource integration to implement the lookup strategy and call into Commerce Engine to retrieve data.

After completing this tutorial, you can retrieve the terms and conditions resource and see data returned from Commerce Engine.

Implement a Lookup Strategy in the Terms and Conditions Resource

In this section, you'll define a lookup strategy interface in the terms and conditions resource and change the resource operator implementation to call that lookup strategy. In a later section, you will create a resource integration that implements the lookup strategy interface in order to return data from Commerce Engine.

Use the resource-integration generator to create the strategy interface and implementation:

  1. Open a command line and navigate to the extensions/tutorials directory.
  2. Run the following command to add the lookup strategy interface to the Cortex resource implementation project and create the Cortex resource integration project:
    mvn clean package -Dtheme=cortex -Dpatch=generators/resource-integration -Dproperties="resourceFamily=terms,resourceEntity=termsAndConditions"
  3. In your IDE, open the extensions/cortex/resources/terms-and-conditions project.
  4. Open TermsResourceOperatorImpl and change the processRead method to call the TermsLookupStrategy interface in order to retrieve the terms-and-conditions entity:
    public OperationResult processRead(
          @ResourceId
          final String termsId,
          final ResourceOperation operation) {
    
        TermsAndConditionsEntity entity = Assign.ifSuccessful(termsLookupStrategy.getTerms(termsId));
    
        ResourceState<TermsAndConditionsEntity> state = ResourceState.Builder
        .<TermsAndConditionsEntity>builder()
            .withEntity(entity)
            .withSelf(createSelf(operation.getUri()))
            .build();
    
        return createReadOK(state, operation);
    }
  5. In TermsResourceOperatorImplTest, delete the tests shouldBuildStateWithId() and shouldBuildStateWithValue(), and replace them with a test that verifies the entity from the lookup strategy is used:
    @Test
    public void shouldUseEntityFromLookup() {
    
       TermsAndConditionsEntity expected = TermsAndConditionsEntity.Builder.builder()
               .withTermsId(TERMS_ID)
               .build();
       ExecutionResult<TermsAndConditionsEntity> executionResult = ExecutionResultFactory.createReadOK(expected);
       when(termsLookupStrategy.getTerms(TERMS_ID)).thenReturn(executionResult);
    
       OperationResult result = resourceOperator.processRead(TERMS_ID, resourceOperation);
    
       ResourceState<TermsAndConditionsEntity> state = (ResourceState<TermsAndConditionsEntity>) result.getResourceState();
       assertEquals(expected, state.getEntity());
    }
  6. Add any missing imports and then run the following command to rebuild the terms and conditions resource JAR file and execute the unit tests:
    mvn clean install
Note: Ignore Errors

You can safely ignore any errors that occur at this point.

Creating the Resource Integration

Now that we have the terms and conditions resource delegating to the lookup strategy, we need to implement the strategy in a resource integration. The resource-integration generator created most of the necessary code, so you just need to add the calls to Commerce Engine. In this section, you will call the SettingsService to retrieve a setting definition description to use as the terms and conditions resource's text.
  1. In your IDE, open the extensions/cortex/integrations/terms-and-conditions-resource-epcommerce project.
  2. In the lookup strategy implementation class, TermsLookupStrategyImpl:
    1. Add a reference to the SettingsService and inject it via the constructor:
        private final SettingsService settingsService;
      
        /**
         * Constructor.
         *
         * @param settingsService the tag definition reader
         */
        @Inject
        public TermsLookupStrategyImpl(
          @Named("settingsService")
          final SettingsService settingsService) {
      
            this.settingsService = settingsService;
        }
    2. Add a private method to wrap the service call in an ExecutionResult:
      private ExecutionResult<String> findTermsAndConditionMessage() {
          ExecutionResult<String> result;
          Set<SettingDefinition> definitions = settingsService.getAllSettingDefinitions();
          if (definitions == null || definitions.isEmpty()) {
              result = ExecutionResultFactory.createNotFound();
          } else {
              result = ExecutionResultFactory.createReadOK(definitions.iterator().next().getDescription());
          }
          return result;
      }
    3. In the getTerms() method, change the .withEntityValue(value) line to call your private method:
      .withMessage(Assign.ifSuccessful(findTermsAndConditionMessage()))
  3. Make corresponding changes in the test class, TermsLookupStrategyImplTest:
    1. Add a mock for the SettingsService:
      @Mock
      private SettingsService settingsService;
    2. Write a test to verify which strategy calls the settings service and to verify the setting definition description in the terms-and-conditions entity's message field. Replace the existing test with the following code.
      @Test
      public void testGetTermsWhenSuccessful() {
      final String expectedMessage = "EP Commerce Terms and Conditions";
      
          Set<SettingDefinition> definitions = new HashSet<SettingDefinition>();
          SettingDefinition definition = mock(SettingDefinition.class);
          definitions.add(definition);
      
          when(definition.getDescription()).thenReturn(expectedMessage);
          when(settingsService.getAllSettingDefinitions()).thenReturn(definitions);
      
          ExecutionResult<TermsAndConditionsEntity> result = termsLookupStrategy.getTerms(SCOPE);
      
          assertTrue("The call should have been successful", result.isSuccessful());
      
          assertEquals("The expected message should have been returned", expectedMessage, result.getData().getMessage());
      }
      
  4. Make sure the SettingsService is imported as a blueprint service by adding the following to OSGI-INF/blueprint/terms-integration-blueprint.xml:
        <reference id="settingsService"
                   interface="com.elasticpath.settings.SettingsService"/commerce-legacy/>
  5. Add any missing imports and then run the following command to build the terms and conditions resource integration JAR file and execute the unit tests:
    mvn clean install

Testing the Integration

At this point, you've created all the necessary components for integrating the terms and conditions resource with Commerce Engine and the final result can be verified.

  1. Open a command line and navigate to the extensions/cortex/ext-cortex-webapp directory.
  2. Run the following command to build and run the Cortex web application:
    mvn clean tomcat7:run-war
  3. Open Cortex Studio in a browser at http://localhost:9080/studio/ and submit a GET Request for:
    /terms/gezdgnbvhu=
    Response:
    {
       self: {
          type: "{vendor}.terms.terms-and-conditions",
          uri: "/commerce-legacy/terms/gezdgnbvhu=",
          href: "http://localhost:9080/cortex/terms/gezdgnbvhu="
       },
       message: "Set to true to enable search autocomplete in the storefront.",
       links: [ ]
    }
    Congratulations, you’ve completed your first integration of a Cortex resource with Commerce Engine.