Package com.mayam.wf.ws.client
Class TasksClient
java.lang.Object
com.mayam.wf.ws.client.TasksClient
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.
finalURL
url = newURL
("http://mayam:8084/tasks-ws"); finalString
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, anew AttributesModule()
must either be installed
inside another Guice module or added to the injector directly.
finalYou will now be able toInjector
injector =Guice.createInjector
( newAttributesModule
() );
Inject
TasksClient
where
needed and set it up. Provided below is an example using the injector we just
created.
finalTasksClient
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.finalTasksClient
client =TasksClient
.createTaskClient()
.setup(URL, String)
.setup(url, token);
Expiration scheduler
It is highly recommended to enable the expiration scheduler usingenableExpirationScheduler()
. 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.finalLong
taskId = 1234L; finalAttributeMap
task = client.taskApi().getTask(taskId); finalTaskState
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 theAttributeMap
- only updated values will be
passed to the server, making the AttributeMap
safe to reuse.
finalString
assetId = "1234567890"; finalAttributeMap
asset = client.assetApi().getAsset(AssetType.ITEM
, assetId); finalString
title = asset.getAttribute(Attribute.ASSET_TITLE
); finalInteger
durationMs = asset.getAttribute(Attribute.ASSET_DURATION
); finalInteger
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 freshAttributeMap
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.
finalAttributeMap
task = client.createAttributeMap(); finalAssetType
assetType =AssetType.ITEM
; finalString
assetId = "1234567890"; finalString
tasklist = "ingest"; finalTaskState
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); finalAttributeMap
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 ofAttributeMap
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.
finalTextMessage
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
); finalAssetType
assetType = result.getAttribute(Attribute.ASSET_TYPE
); ... }
Direct MAM metadata managment, bypassing all attribute management
SeegetUnmanagedMetadata(AssetType, String)
and
updateUnmanagedMetadata(AssetType, String, UnmanagedMetadata)
- Author:
- Markus MÃ¥rtensson
-
Field Summary
Modifier and TypeFieldDescriptionprotected org.jboss.resteasy.client.jaxrs.ResteasyWebTarget
-
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescriptionReturns an ActivityApi, this is used to perform server activities.assetApi()
Returns a AssetApi, this is used to do asset operations.bpmsApi()
Returns a BpmsApi, this is used to do Bpms operations SeeBpmsApi
for usageReturns a ConfigApi, this is used to do configuration operations.Creates a newAttributeMap
, with dependencies that allow input validation to be performed on change.static TasksClient
Creates a client using manual dependency injection.deserializAttributeMap
(String serialized) Creates aAttributeMap
based on its serialized string equivalent.Creates a connection pool monitoring thread which closes connections that have expired, leaving room for new connections.protected static RemoteException
Tries to locate a RemoteException in the stacktrace, and if so it returns that.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 theinvalid reference
#createTaskClient(URL, String)
boolean
protected void
Returns a SegmentApi, this is used to do segment operations.final TasksClient
It's recommended to usesetup(URL, String, String, String)
insteadfinal TasksClient
Connects a client to the Mayam end-points by providing their shared base URL, typicallyhttp://mayam:8084/tasks-ws
.final TasksClient
Internal use only for now.taskApi()
Returns a TaskApi, this is used to do task operations.void
teardown()
Disconnects the client and frees up resources used.A method used for testing or troubleshooting.void
A method used for testing or troubleshooting.testPutMap
(AttributeMap map) userApi()
Returns a UserApi, this is used to do user operations.
-
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 theinvalid reference
#createTaskClient(URL, String)
- Parameters:
mapper
- provides a mapping betweenAttributeMap
and its JSON representation.mapProvider
- creates new AttributeMap instances, with their dependencies.
-
setup
It's recommended to usesetup(URL, String, String, String)
instead- Parameters:
baseUrl
-apiToken
-
-
setup
Connects a client to the Mayam end-points by providing their shared base URL, typicallyhttp://mayam:8084/tasks-ws
. Also specified is one of the API account tokens of thesiteconfig.properties
file (api.accounts
).- Parameters:
baseUrl
- Mayam Webservices base URL.apiToken
- API account token.appName
- client application nameappVersion
- 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
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
Creates a client using manual dependency injection. Needs to be followed by asetup(URL, String)
.- Returns:
- the newly created client instance.
-
segmentApi
Returns a SegmentApi, this is used to do segment operations. SeeSegmentApi
for usage -
taskApi
Returns a TaskApi, this is used to do task operations. SeeTaskApi
for usage -
assetApi
Returns a AssetApi, this is used to do asset operations. SeeAssetApi
for usage -
userApi
Returns a UserApi, this is used to do user operations. SeeUserApi
for usage -
configApi
Returns a ConfigApi, this is used to do configuration operations. SeeConfigApi
for usage -
activityApi
Returns an ActivityApi, this is used to perform server activities. SeeActivityApi
for usage -
bpmsApi
Returns a BpmsApi, this is used to do Bpms operations SeeBpmsApi
for usage -
createAttributeMap
Creates a newAttributeMap
, with dependencies that allow input validation to be performed on change. Guice enabled code should instead inject theAttributeMap
directly (typically via aProvider
).- Returns:
- a newly created AttributeMap.
-
deserializAttributeMap
Creates aAttributeMap
based on its serialized string equivalent. Guice enabled code should instead inject anAttributeMapMapper
instance and calldeserialize()
.- Returns:
- a newly created 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. -
expectRemoteException
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).
-