Class TasksClient

java.lang.Object
com.mayam.wf.ws.client.TasksClient

public class TasksClient extends Object
Client for the Mayam Tasks Webservices. Client instances need to be provided with the base URL for Mayam Tasks Webservices, which is the root of the web application tasks-ws that serves them. Also required is one of the API account tokens of the siteconfig.properties file, found under the property name api.accounts. These, by convention, take the form of "user:password". Server side logging will discard any part of the token starting with the first colon under the assumption that this convention is followed.
  final URL url = new URL("http://mayam:8084/tasks-ws");
  final String token = "someaccount:somepassword";
 

Creating client using Guice injection

Google Guice is a powerful dependency injection system that is used extensively on the server side of Mayam Tasks and available for the client as well. First of all, a new AttributesModule() must either be installed inside another Guice module or added to the injector directly.
  final Injector injector = Guice.createInjector(
      new AttributesModule()
  );
 
You will now be able to Inject TasksClient where needed and set it up. Provided below is an example using the injector we just created.
  final TasksClient client = injector.getInstance(TasksClient.class).setup(url, token);
 

Creating client using static factory method

It is possible to totally bypass Guice using a provided static factory method.
  final TasksClient client = TasksClient.createTaskClient().setup(URL, String).setup(url, token);
 

Expiration scheduler

It is highly recommended to enable the expiration scheduler using enableExpirationScheduler(). It creates a connection pool monitoring thread which closes connections that have expired, leaving room for new connections. This is essential for a long running process, but also means that the call to teardown() is not optional, since the new thread will keep your application from shutting down properly.

Existing task example

The following example will fetch a task and check its current state.
  final Long taskId = 1234L;
  final AttributeMap task = client.taskApi().getTask(taskId);
  final TaskState state = task.getAttribute(Attribute.TASK_STATE);
  if (state == TaskState.OPEN) {
      ...
  }
 

Existing asset example

The following example will fetch an asset and update it, increasing the duration by one second. This demonstrates the dirty value handling of the AttributeMap - only updated values will be passed to the server, making the AttributeMap safe to reuse.
  final String assetId = "1234567890";
  final AttributeMap asset = client.assetApi().getAsset(AssetType.ITEM, assetId);
  final String title = asset.getAttribute(Attribute.ASSET_TITLE);
  final Integer durationMs = asset.getAttribute(Attribute.ASSET_DURATION);
  final Integer longerDurationMs = durationMs + 1000;
  System.out.println("Updating duration of " + title + " to " + longerDurationMs);
  asset.setAttribute(Attribute.ASSET_DURATION, longerDurationMs);
  client.assetApi().updateAsset(asset);
 

New task example

In order to create a new task, a fresh AttributeMap instance is needed. You should not create it by calling new AttributeMap() since this will create an instance with insufficient security measures. If using Guice, the recommended approach is using a Provider<AttributeMap> but for users of the static factory method, the createAttributeMap() provides the same functionality and will be used in the below example. A new task will be created that is linked to a given asset which means it will retrieve data from the MAM. If creating a task that is mapped to a asset, it is recommended to not set the values that are retrieved from that asset unless that value should change.
  final AttributeMap task = client.createAttributeMap();
  final AssetType assetType = AssetType.ITEM;
  final String assetId = "1234567890";
  final String tasklist = "ingest";
  final TaskState state = TaskState.OPEN;
  task.setAttribute(Attribute.ASSET_TYPE, assetType);
  task.setAttribute(Attribute.ASSET_ID, assetId);
  task.setAttribute(Attribute.TASK_STATE, state);
  task.setAttribute(Attribute.TASK_LIST_ID, tasklist);
  final AttributeMap result = client.taskApi().createTask(task);
  final Long taskId = result.getAttribute(Attribute.TASK_ID);
 

Filter tasks example

Starting with Tasks 2.3, there are two supported means of filtering tasks - criteria and expressions. The former, and older, approach has better type safety but is not quite as powerful as the more free form expressions based on Ecmascript. The following example will use crriteria to fetch all assets found in the "ingest" task list that are in state "ERROR" that begin with "a" and describe an episode of season 1 or 2. The list is sorted based on task creation date, with the most recent task first in the list.
 final FilterCriteria criteria = client.taskApi().createFilterCriteria();
 criteria.getFilterEqualities().setAttribute(Attribute.TASK_LIST_ID, "ingest").setAttribute(Attribute.TASK_STATE,
                TaskState.ERROR);
 criteria.getFilterSimilarities().setAttribute(Attribute.ASSET_TITLE, "a*");
 criteria.getSearchRanges().setAttributeRange(Attribute.SEASON_NUMBER, 1, 2);
 criteria.getSortOrders().add(new SortOrder(Attribute.TASK_CREATED, SortOrder.Direction.DESC));
 final FilterResult result = client.taskApi().getTasks(criteria, 40, 0);
 System.out.println("Total matches: " + result.getTotalMatches());
 for (final AttributeMap match : result.getMatches()) {
        System.out.println(" - " + match.getAttributeAsString(Attribute.ASSET_TITLE));
 }
 
The same filter, as an expression looks like this:
 final String expr = "s.TASK_LIST_ID=='ingest' invalid input: '&'invalid input: '&' s.TASK_STATE=='ERROR' invalid input: '&'invalid input: '&' startsWith(s.ASSET_TITLE,'a')";
 final FilterResult result = client.taskApi().getTasks(new FilterExpression(expr), 40, 0);
 
The special object "s" can be thought of as the individual AttributeMap of every single tasks as if the they were all pulled from the database end checked versus the expression. The reality is, of course, a far more optimized approach. To make the expressions more useful, they can be parameterized by registering and referencing objects. This allows the developer to create a (possibly) complex expression without having to worry about escaping, quotation, and string concatation.
 new FilterExpression("s.TASK_LIST_ID==p.list").registerObject("list", "ingest");
 

Parsing an incoming JMS message

Mayam Tasks uses the serialized form of AttributeMap as content for text messages passed on message queues. These can be deserialized into the original form by injecting an AttributeMapMapper or using the utility method deserializAttributeMap(String) as shown below.
  final TextMessage message = ...;
  final String messageType = message.getJMSType();
  if ("mayam.asset.create".equals(messageType)) {
      final String serialized = message.getText();
      final AttributeMap subject = client.deserializAttributeMap(serialized);
      final Long assetId = result.getAttribute(Attribute.ASSET_ID);
      final AssetType assetType = result.getAttribute(Attribute.ASSET_TYPE);
      ...
  }
 

Direct MAM metadata managment, bypassing all attribute management

See getUnmanagedMetadata(AssetType, String) and updateUnmanagedMetadata(AssetType, String, UnmanagedMetadata)
Author:
Markus MÃ¥rtensson
  • Field Details

    • target

      protected org.jboss.resteasy.client.jaxrs.ResteasyWebTarget target
  • Constructor Details

    • TasksClient

      public TasksClient()
  • Method Details

    • injectHelpers

      @Inject public void injectHelpers(com.mayam.wf.config.server.JacksonConfigMapperImpl mapper, javax.inject.Provider<AttributeMap> mapProvider, javax.inject.Provider<AttributeRangeMap> rangeMapProvider, javax.inject.Provider<AttributeMultiMap> multiMapProvider)
      Allows injection of dependencies through Guice/CDI or through the
      invalid reference
      #createTaskClient(URL, String)
      method.
      Parameters:
      mapper - provides a mapping between AttributeMap and its JSON representation.
      mapProvider - creates new AttributeMap instances, with their dependencies.
    • setup

      public final TasksClient setup(URL baseUrl, String apiToken)
      It's recommended to use setup(URL, String, String, String) instead
      Parameters:
      baseUrl -
      apiToken -
    • setup

      public final TasksClient setup(URL baseUrl, String apiToken, String appName, String appVersion)
      Connects a client to the Mayam end-points by providing their shared base URL, typically http://mayam:8084/tasks-ws. Also specified is one of the API account tokens of the siteconfig.properties file (api.accounts).
      Parameters:
      baseUrl - Mayam Webservices base URL.
      apiToken - API account token.
      appName - client application name
      appVersion - client application version
      Returns:
      the client, allowing convenient chaining.
    • setup

      public final TasksClient setup(URL baseUrl, String apiToken, String appName, String appVersion, boolean noConnectionPool)
      Internal use only for now. Do not use
    • postSetup

      protected void postSetup()
    • enableExpirationScheduler

      public TasksClient enableExpirationScheduler()
      Creates a connection pool monitoring thread which closes connections that have expired, leaving room for new connections. This is essential for a long running process, but also means that the call to teardown() is not optional, since the new thread will keep your application from shutting down properly.
    • teardown

      public void teardown()
      Disconnects the client and frees up resources used.
    • isInitialized

      public boolean isInitialized()
    • createTaskClient

      public static TasksClient createTaskClient()
      Creates a client using manual dependency injection. Needs to be followed by a setup(URL, String).
      Returns:
      the newly created client instance.
    • segmentApi

      public SegmentApi segmentApi()
      Returns a SegmentApi, this is used to do segment operations. See SegmentApi for usage
    • taskApi

      public TaskApi taskApi()
      Returns a TaskApi, this is used to do task operations. See TaskApi for usage
    • assetApi

      public AssetApi assetApi()
      Returns a AssetApi, this is used to do asset operations. See AssetApi for usage
    • userApi

      public UserApi userApi()
      Returns a UserApi, this is used to do user operations. See UserApi for usage
    • configApi

      public ConfigApi configApi()
      Returns a ConfigApi, this is used to do configuration operations. See ConfigApi for usage
    • activityApi

      public ActivityApi activityApi()
      Returns an ActivityApi, this is used to perform server activities. See ActivityApi for usage
    • bpmsApi

      public BpmsApi bpmsApi()
      Returns a BpmsApi, this is used to do Bpms operations See BpmsApi for usage
    • createAttributeMap

      public AttributeMap createAttributeMap()
      Creates a new AttributeMap, with dependencies that allow input validation to be performed on change. Guice enabled code should instead inject the AttributeMap directly (typically via a Provider).
      Returns:
      a newly created AttributeMap.
    • deserializAttributeMap

      public AttributeMap deserializAttributeMap(String serialized)
      Creates a AttributeMap based on its serialized string equivalent. Guice enabled code should instead inject an AttributeMapMapper instance and call deserialize().
      Returns:
      a newly created AttributeMap.
    • testAlwaysReturnTask

      public AttributeMap testAlwaysReturnTask()
      A method used for testing or troubleshooting. It will produce output on System.err describing its progress in retrieving a task from a webservices call that is expected to always return one.
    • testAlwaysThrowException

      public void testAlwaysThrowException()
      A method used for testing or troubleshooting. It will produce output on System.err describing its progress in performing a a webservices call that is expected to always throw an exception.
    • testPutMap

      public AttributeMap testPutMap(AttributeMap map) throws RemoteException
      Throws:
      RemoteException
    • expectRemoteException

      protected static RemoteException expectRemoteException(Throwable t)
      Tries to locate a RemoteException in the stacktrace, and if so it returns that. Failing that, the input exception is thrown (wrapping in RuntimeException if needed).