Skip to main content
Version: 1.5.x

Development Support Features

This section details information about the different development support features available.

Extension Annotations​

Extension classes can have the following annotations:

@Extension​

All extension classes must contain this annotation to be recognized as an extension by the Extension Point Framework.

@XPFEmbedded​

This annotation indicates that the extension should be instantiated by the Spring Framework. This allows the extension to define fields with the @Autowired annotation so it can access Spring services.

warning

Do not add this annotation to extensions within external plugins.

@XPFAssignment​

This annotation indicates that the extension should be automatically assigned to an extension point. If an extension does not contain this annotation, then it will not be assigned at startup but can still assigned at runtime using JMX methods.

This annotation can be defined multiple times on the same extension to assign the extension to multiple extension points, as in the example below:

@XPFAssignment(extensionPoint = XPFExtensionPointEnum.VALIDATE_PRODUCT_SKU_AT_ADD_TO_CART_READ, priority = 1050)
@XPFAssignment(extensionPoint = XPFExtensionPointEnum.VALIDATE_PRODUCT_SKU_AT_CHECKOUT, priority = 1040)
@XPFAssignment(extensionPoint = XPFExtensionPointEnum.VALIDATE_PRODUCT_SKU_AT_ADD_TO_CART, priority = 1040)

The extensionPoint parameter indicates which extension point the extension should be assigned to.

The priority parameter indicates the priority of the extension for that extension point. For extensions retrieved using XPFExtensionLookup#getSingleExtension, the assigned extensions are ordered by priority, and the first valid extension is returned. For extensions retrieved using XPFExtensionLookup#getMultipleExtensions, the extensions are ordered by priority and returned in that order. Therefore, extensions with lower priority numbers are returned before extensions with higher priority numbers.

note

All Elastic Path Commerce extensions that are delivered as part of the product will be assigned priorities in the range 1000 to 1999. Since we may add or remove extensions in the future, make sure to use priorities outside of that range for your custom extensions.

Extension Point Selectors​

Selectors are a mechanism to ensure that extensions are only executed in certain contexts. For example, extensions can be configured to only run for certain scopes (stores) in Cortex.

To define the selector mode and the selectors for each extension, see Configuring and Deploying. To determine which selector an extension point supports, see the XPFExtensionPointEnum documentation.

Extensions can be configured to run in one of two different selector modes:

  • DEFAULT_NONE means that the extension will not be executed unless a selector context is defined that matches the current runtime context.
  • DEFAULT_ALL means that the extension will be executed unless a selector context is defined that matches the current runtime context.

The currently supported selectors are described below:

SELECTOR_NONE​

This selector always matches the runtime context.

SELECTOR_STORE​

This selector matches the runtime context if the current store matches the defined store code.

Plugin Initialization​

To execute certain functionality as soon as a plugin is started, your plugin class can override the public void start() method from the PF4j Plugin class. Unlike the constructor, this method can access the Plugin Initialization Context.

The Plugin Initialization Context is an object available to external plugin and external plugin extensions. It provides access to support features such as plugin settings, logging, and caching. This object is not available to embedded extensions.

To define an object that can be accessed by extensions, the start method can store the object in the custom data map as in the following example:

getContext().getCustomData().put("jedisPool", new JedisPool(new JedisPoolConfig(), redisHost, redisPort));

To access this object, classes can execute MyPlugin.getInstance().getContext(), where MyPlugin is replaced with the name of the external plugin class.

Extension Initialization​

To execute certain functionality as soon as an extension is instantiated, your extension class can override the public void initialize(XPFExtensionInitializationContext context) method from the XPFExtensionPointImpl class. Unlike the constructor, this method can access the Extension Initialization Context, which is passed as a parameter.

The Extension Initialization Context provides access to support features such as extension settings.

Settings​

Setting values can be passed into both external plugins and external plugin extensions. This can be useful for inputs such as endpoint URIs, credentials, or behavioural flags.

To access plugin settings, extensions can read Map<String, XPFPluginSetting> getSettings() from the Plugin Initialization Context. To access extension settings, extensions can read Map<String, XPFPluginSetting> getSettings() from the Extension Initialization Context.

For simple single-valued settings, developers can use the Optional<XPFPluginSettingValue> getSingleSettingValue(final String settingKey) convenience function, which returns a single value for the specified key. If the setting key can't be found, or if the number of setting values is more or less than 1, then Optional.empty() will be returned. This function is available on both the Plugin Initialization Context and the Extension Initialization Context.

Example:

Optional<XPFPluginSettingValue> apiKeySettingValue = SegmentOrderReleasePlugin.getInstance().getContext().getSingleSettingValue("api_key");

Setting value keys are not pre-defined, so any setting values can be passed into a plugin or extension. It is up to the plugin developer to decide how to handle expected setting values that are missing, such as falling back to a default value or throwing an exception.

For more information about how to specify the setting values to pass into plugins and extensions, see Configuring and Deploying External Plugins.

Price Calculators​

Price calculators provide a standard mechanism for retrieving prices from various XPF entity classes.

XPFItemPricing​

The XPFItemPricing interface provides methods to calculate the price of a product SKU. It can be accessed from the following XPF entity classes:

  • XPFProductSkuValidationContext#getPricing()
  • XPFShoppingItemValidationContext#getPricing()

The XPFItemPricing interface provides the following methods that can be chained together to determine the desired price:

MethodDescription
withListPriceIncludes the item list price in the price calculation.
withDiscountsIncludes the difference between the list price and sale price, plus catalog promotion discounts in the price calculation.

The chain can be terminated by calling one of these methods:

MethodReturn TypeDescription
getAmountBigDecimalReturns the amount of the price calculation as a BigDecimal.
getCurrencyCurrencyReturns the currency of the price calculation.
isNonZerobooleanReturns whether the price calculation is non-zero.

Examples:

  • .withListPrice().getAmount() returns the item list price.
  • .withDiscounts().getAmount() returns the sale and catalog promotion discounts. (Note that this value will be negative.)
  • .withListPrice().withDiscounts().getAmount() returns the item list price minus discounts.

XPFLinePricing​

The XPFLinePricing interface provides methods to calculate the price of a shopping cart line item or order line item. It can be accessed from the following XPF entity classes:

  • XPFShoppingItem#getPricing()
  • XPFOrderItem#getPricing()

The XPFLinePricing interface provides the following methods that can be chained together to determine the desired price:

MethodDescription
withListPriceIncludes the item list price in the price calculation.
withDiscountsIncludes the difference between the list price and sale price, plus catalog and line-level promotion discounts in the price calculation.
withApportionedContainerDiscountsIncludes the line item apportioned value of the container discounts in the price calculation. For example, if there is a $20.00 discount on the shopping cart, and there are two line items of equal value, they will each be allocated $10.00 of the discount.

The chain can be terminated by calling one of these methods:

MethodReturn TypeDescription
getAmountBigDecimalReturns the amount of the price calculation as a BigDecimal.
getCurrencyCurrencyReturns the currency of the price calculation.
isNonZerobooleanReturns whether the price calculation is non-zero.

Examples:

  • .withListPrice().getAmount() returns the item list price.
  • .withDiscounts().getAmount() returns the sale, catalog, and line-level promotion discounts. (Note that this value will be negative.)
  • .withListPrice().withDiscounts().getAmount() returns the item list price minus sale, catalog, and line-level promotion discounts.
  • .withListPrice().withDiscounts().withApportionedContainerDiscounts().getAmount() returns the item list price minus sale, catalog, and line-level promotion discounts and minus the apportioned container-level discounts.

XPFContainerPricing​

The XPFContainerPricing interface provides methods to calculate the price of a shopping cart or order. It can be accessed from the following XPF entity classes:

  • XPFShoppingCart#getPricing()
  • XPFOrder#getPricing()
  • XPFOrderShipment#getPricing()

The XPFContainerPricing interface provides the following methods that can be chained together to determine the desired price:

MethodDescription
withSubtotalIncludes line item subtotals and line-level discounts, but does not include any cart, order, or order shipment discounts, taxes, or shipping in the price calculation.
withContainerDiscountsIncludes the cart, order, or order shipment discounts, but does not include any line-level discounts in the price calculation.
withTaxesIncludes item taxes but not shipping taxes in the price calculation.
withShippingSubtotalIncludes shipping subtotal but not shipping discounts or taxes in the price calculation.
withShippingDiscountsIncludes shipping discounts in the price calculation.
withShippingTaxesIncludes shipping taxes in the price calculation.
withTotalThis is a convenience method that is equivalent to .withSubtotal().withContainerDiscounts().withTaxes().withShippingSubtotal().withShippingDiscounts().withShippingTaxes().

The chain can be terminated by calling one of these methods:

MethodReturn TypeDescription
getAmountBigDecimalReturns the amount of the price calculation as a BigDecimal.
getCurrencyCurrencyReturns the currency of the price calculation.
isNonZerobooleanReturns whether the price calculation is non-zero.

Examples:

  • .withSubtotal().getAmount() returns the container subtotal without any discounts, shipping, or taxes.
  • .withContainerDiscounts().getAmount() returns the container discounts, but not any line-level discounts (which are part of the subtotal). (Note that this value will be negative.)
  • .withSubtotal().withContainerDiscounts().getAmount() returns the container subtotal including container discounts.
  • .withShippingSubtotal().withShippingDiscounts().getAmount() returns the shipping subtotal including shipping discounts.
  • .withTaxes().withShippingTaxes().getAmount() returns item and shipping taxes.
  • .withTotal().getAmount() returns the container total including all discounts, taxes, and shipping.

Exceptions​

If an extension method is unable to complete its work due to a problem, it should throw an exception. However, try to avoid throwing arbitrary runtime exceptions; there are two exceptions that Elastic Path Commerce expects extensions to throw. The choice of which exception to throw boils down to how the problem should be handled:

  • XPFPluginRuntimeException should be thrown if an unexpected error occurred that the end-user cannot correct. If this is thrown by an extension invoked by Cortex, this will result in a 500 Internal Server Error response, and the details of the exception will be logged.
  • XPFPluginInvalidBusinessStateException should be thrown if there is a problem that can be corrected by the end-user. If this is thrown by an extension invoked by Cortex, this will result in a 400 Bad Request response, along with a structured error message containing the details. For example, if a Tax Calculation extension detects that the destination address has a postal code that doesn’t match with the specified province, then a XPFPluginInvalidBusinessStateException exception should be thrown. The extension can specify what should be returned in the structured error message by populating the structuredErrorMessages collection in the exception class constructor.

Logging​

External plugins and external plugin extensions can write to the service logs through an SLF4j logger. Extensions can read Logger getLogger() from the Plugin Initialization Context. The logger is automatically initialized with the logger name set to the plugin class name.

For example:

@Override
public void initialize(XPFExtensionInitializationContext context) {
super.initialize(context);
MyPlugin.getInstance().getContext().getLogger().info("Extension initialized.");
}

Additionally, the following Extension Point Framework events are logged automatically:

  • When an external plugin is loaded: INFO: XPF plugin {plugin-id} loaded.
  • When an external plugin is started: INFO: XPF plugin {plugin-id} started.
  • When an external plugin is stopped: INFO: XPF plugin {plugin-id} stopped.
  • When an external plugin is unloaded: INFO: XPF plugin {plugin-id} unloaded.
  • When an extension is assigned: DEBUG: Extension class {extension-class-name} assigned to {xpf-extension-enum} with priority {priority}.
  • When an extension is unassigned: DEBUG: Extension class {extension-class-name} unassigned from {xpf-extension-enum}.
  • After an extension method is invoked: TRACE: Extension class {extension-class-name} method {method-name} took {time} ms to execute.
  • After an extension method is invoked, if it took more than 100ms: WARN: Extension class {extension-class-name} method {method-name} took {time} ms to execute.

Caching​

External plugins and external plugin extensions can create a cache that is backed by EhCache. Extensions can call XPFCache<K, V> createCache(String cacheName, int timeToLive, int timeToIdle, int maxObjects) on the Plugin Initialization Context.

Each Elastic Path Commerce service holds a separate cache in memory; they are not shared between services. Also, the cache name is scoped to the plugin ID, meaning that if another plugin specifies the same cache name, separate caches will be created.

The cache will continue to exist even if the plugin is unloaded and reloaded. When createCache is invoked, if an existing cache already exists for that plugin ID with the same name, the existing cache will be returned. Note that the plugin ID includes the version, so if a new plugin is loaded with a different version, then a new cache will be created.

Parameters​

  • The cacheName parameter specifies the name of the cache.
  • The timeToLive parameter specifies the maximum number of seconds an element can exist in the cache regardless of use.
  • The timeToIdle parameter specifies the maximum number of seconds an element can exist in the cache without being accessed.
  • The maxObjects parameter specifies the maximum number of objects that can exist in the cache.

For example

XPFCache<String, BigDecimal> skuCodeToPriceCache = LifecycleLoggerPlugin.getInstance().getContext().createCache("skuCodeToPriceCache", 3600, 3600, 10000);
BigDecimal price = skuCodeToPriceCache.get("alien_sku", skuCode -> getPriceFromAPI(skuCode));

Entity JSON Serialization​

The XPFJSONSerializationHelper class provides utility methods for serializing XPF entity objects to JSON and deserializing JSON back to entity objects. This is particularly useful when extensions need to exchange entity data with external systems in a portable format.

Serialization​

To serialize an XPF entity object to JSON, use the marshalToJSON method:

String json = XPFJSONSerializationHelper.marshalToJSON(myEntity, scopes);

The marshalToJSON method takes two parameters:

  • objectToSerialize - The XPF entity object to serialize to JSON.
  • scopes - A Set<SerializationScope> that controls which fields are included in the serialization.

Deserialization​

To deserialize JSON back to an XPF entity object, use one of the unmarshalFromJSON methods:

// Deserialize to a specific entity class
MyEntity entity = XPFJSONSerializationHelper.unmarshalFromJSON(json, MyEntity.class);

// Deserialize to a list of entities using a TypeReference parameter
List<MyEntity> entities = XPFJSONSerializationHelper.unmarshalFromJSON(json, new TypeReference<List<MyEntity>>() {});

// Deserialize to a map of entities using a TypeReference parameter
Map<String, MyEntity> entities = XPFJSONSerializationHelper.unmarshalFromJSON(json, new TypeReference<Map<String, MyEntity>>() {});

Serialization Scopes​

Serialization scopes control which fields are included when marshaling objects to JSON. Fields or methods annotated with @SkipSerialization will be excluded from serialization when the specified scopes are active. The fields will still appear in the resulting JSON but will have a null value.

The following scopes are available:

ScopeDescription
PROMO_EVALUATIONThe contents of fields annotated with @SkipSerialization(scopes = {SerializationScope.PROMO_EVALUATION}) will be excluded from the output. The fields will still appear in the resulting JSON but will have a null value. Used for promotions evaluation through the Promotions Calculator extension point.
SKIP_LAZY_LOADINGThe contents of fields annotated with @LazyLoaded will be excluded from the output. The fields will still appear in the resulting JSON but will have a null value. This is useful for avoiding the performance penalty of loading lazy-loaded entity fields when they are not needed.

Using SKIP_LAZY_LOADING​

The SKIP_LAZY_LOADING scope is particularly important for performance. Many XPF entity fields are annotated with @LazyLoaded, which means they are expensive to calculate and are only loaded when accessed. When serializing entities, you often don't need these fields, and loading them can significantly impact performance.

To skip lazy-loaded fields during serialization:

Set<SerializationScope> scopes = EnumSet.of(SerializationScope.SKIP_LAZY_LOADING);
String json = XPFJSONSerializationHelper.marshalToJSON(myEntity, scopes);

To serialize without skipping any fields:

String json = XPFJSONSerializationHelper.marshalToJSON(myEntity, null);

Combining Multiple Scopes​

You can combine multiple scopes to exclude fields based on multiple criteria:

Set<SerializationScope> scopes = EnumSet.of(
SerializationScope.SKIP_LAZY_LOADING,
SerializationScope.PROMO_EVALUATION
);
String json = XPFJSONSerializationHelper.marshalToJSON(myEntity, scopes);

Custom Data on Entity Classes​

All XPF entity classes extend XPFEntity, which provides a getCustomData() method that returns a Map<String, Object>. This map is a mechanism for passing custom platform data into extensions and plugins without modifying the XPF entity class definitions.

warning

Do not extend XPF entity classes to add custom fields. Extending entity classes will make future upgrades more difficult because changes to the entity class hierarchy may break your custom subclasses. Use the customData map instead.

Populating Custom Data​

Custom data is populated by extending the corresponding converter class that builds the entity. Converters implement Spring's Converter interface and are responsible for mapping platform domain objects to XPF entity objects.

For example, to add custom data to XPFCustomer objects, extend CustomerConverter and override its convert method:

public class ExtCustomerConverter extends CustomerConverter {

@Override
public XPFCustomer convert(final StoreDomainContext<Customer> storeDomainContext) {
XPFCustomer customer = super.convert(storeDomainContext);

Map<String, Object> customData = new HashMap<>(customer.getCustomData());
customData.put("loyaltyTier", getLoyaltyTier(storeDomainContext.getDomain()));

return XPFCustomer.builder()
.guid(customer.getGuid())
.sharedId(customer.getSharedId())
.createdDate(customer.getCreatedDate())
.email(customer.getEmail())
.status(customer.getStatus())
.type(customer.getType())
.attributeValues(customer.getAttributeValues())
.segments(customer.getSegments())
.firstTimeBuyer(customer.isFirstTimeBuyer())
.customData(customData)
.build();
}
}

Register the custom converter as a Spring bean in your ext-core configuration so that it replaces the default converter.

Accessing Custom Data in Extensions​

Extensions can access custom data from any entity object by calling getCustomData(). For example:

@Override
public Collection<XPFStructuredErrorMessage> validate(final XPFShoppingCartValidationContext context) {
Map<String, Object> customData = context.getShoppingCart().getCustomData();
String loyaltyTier = (String) customData.get("loyaltyTier");
// ...
}

Correlation ID​

All extensions have access to the current correlation ID for the current thread. The XPFExtensionPointImpl class that all extensions extend contains the following method:

String getCorrelationId();

Extensions can call this method to access the current Correlation ID so it can be optionally passed to downstream systems as part of an integration.

Performance​

Long execution warning​

All extension method invocations are monitored to ensure they execute within an expected execution time threshold. If an extension method takes more than 100ms to execute, a warning will be logged: Extension class {} method {} took {} ms to execute.

Lazy-loaded entity fields​

Some entity class values are slow to calculate while at the same time may not be required by the configured extensions. To address this, some entity getter methods are lazy loaded when called by the extension. These methods can be identified by the existence of the @LazyLoaded annotation on the method. Note that calling these methods may incur a performance penalty. However, if they are called more than once, a cached value will be returned after the first invocation. Additionally, there is a (small) chance that a lazy loaded method throws an exception, so make sure to add exception handling around these methods in your extension.