use of org.opencastproject.workflow.api.WorkflowInstance in project opencast by opencast.
the class ConfigurablePublishWorkflowOperationHandlerTest method testNormal.
@Test
public void testNormal() throws WorkflowOperationException, URISyntaxException, DistributionException, MediaPackageException {
String channelId = "engage-player";
String attachmentId = "attachment-id";
String catalogId = "catalog-id";
String trackId = "track-id";
Attachment attachment = new AttachmentImpl();
attachment.addTag("engage-download");
attachment.setIdentifier(attachmentId);
attachment.setURI(new URI("http://api.com/attachment"));
Catalog catalog = CatalogImpl.newInstance();
catalog.addTag("engage-download");
catalog.setIdentifier(catalogId);
catalog.setURI(new URI("http://api.com/catalog"));
Track track = new TrackImpl();
track.addTag("engage-streaming");
track.setIdentifier(trackId);
track.setURI(new URI("http://api.com/track"));
Publication publicationtest = new PublicationImpl(trackId, channelId, new URI("http://api.com/publication"), MimeType.mimeType(trackId, trackId));
Track unrelatedTrack = new TrackImpl();
unrelatedTrack.addTag("unrelated");
Capture<MediaPackageElement> capturePublication = Capture.newInstance();
MediaPackage mediapackageClone = EasyMock.createNiceMock(MediaPackage.class);
EasyMock.expect(mediapackageClone.getElements()).andStubReturn(new MediaPackageElement[] { attachment, catalog, track, unrelatedTrack });
EasyMock.expect(mediapackageClone.getIdentifier()).andStubReturn(new IdImpl("mp-id-clone"));
EasyMock.expectLastCall();
EasyMock.replay(mediapackageClone);
MediaPackage mediapackage = EasyMock.createNiceMock(MediaPackage.class);
EasyMock.expect(mediapackage.getElements()).andStubReturn(new MediaPackageElement[] { attachment, catalog, track, unrelatedTrack });
EasyMock.expect(mediapackage.clone()).andStubReturn(mediapackageClone);
EasyMock.expect(mediapackage.getIdentifier()).andStubReturn(new IdImpl("mp-id"));
mediapackage.add(EasyMock.capture(capturePublication));
mediapackage.add(publicationtest);
EasyMock.expect(mediapackage.getPublications()).andStubReturn(new Publication[] { publicationtest });
EasyMock.expectLastCall();
EasyMock.replay(mediapackage);
WorkflowOperationInstance op = EasyMock.createNiceMock(WorkflowOperationInstance.class);
EasyMock.expect(op.getConfiguration(ConfigurablePublishWorkflowOperationHandler.CHANNEL_ID_KEY)).andStubReturn(channelId);
EasyMock.expect(op.getConfiguration(ConfigurablePublishWorkflowOperationHandler.MIME_TYPE)).andStubReturn("text/html");
EasyMock.expect(op.getConfiguration(ConfigurablePublishWorkflowOperationHandler.URL_PATTERN)).andStubReturn("http://api.opencast.org/api/events/${event_id}");
EasyMock.expect(op.getConfiguration(ConfigurablePublishWorkflowOperationHandler.SOURCE_TAGS)).andStubReturn("engage-download,engage-streaming");
EasyMock.expect(op.getConfiguration(ConfigurablePublishWorkflowOperationHandler.CHECK_AVAILABILITY)).andStubReturn("true");
EasyMock.expect(op.getConfiguration(ConfigurablePublishWorkflowOperationHandler.STRATEGY)).andStubReturn("retract");
EasyMock.expect(op.getConfiguration(ConfigurablePublishWorkflowOperationHandler.MODE)).andStubReturn("single");
EasyMock.replay(op);
WorkflowInstance workflowInstance = EasyMock.createNiceMock(WorkflowInstance.class);
EasyMock.expect(workflowInstance.getMediaPackage()).andStubReturn(mediapackage);
EasyMock.expect(workflowInstance.getCurrentOperation()).andStubReturn(op);
EasyMock.replay(workflowInstance);
JobContext jobContext = EasyMock.createNiceMock(JobContext.class);
EasyMock.replay(jobContext);
Job attachmentJob = EasyMock.createNiceMock(Job.class);
EasyMock.expect(attachmentJob.getPayload()).andReturn(MediaPackageElementParser.getAsXml(attachment));
EasyMock.replay(attachmentJob);
Job catalogJob = EasyMock.createNiceMock(Job.class);
EasyMock.expect(catalogJob.getPayload()).andReturn(MediaPackageElementParser.getAsXml(catalog));
EasyMock.replay(catalogJob);
Job trackJob = EasyMock.createNiceMock(Job.class);
EasyMock.expect(trackJob.getPayload()).andReturn(MediaPackageElementParser.getAsXml(track));
EasyMock.replay(trackJob);
Job retractJob = EasyMock.createNiceMock(Job.class);
EasyMock.expect(retractJob.getPayload()).andReturn(MediaPackageElementParser.getAsXml(track));
EasyMock.replay(retractJob);
DownloadDistributionService distributionService = EasyMock.createNiceMock(DownloadDistributionService.class);
// Make sure that all of the elements are distributed.
EasyMock.expect(distributionService.distribute(channelId, mediapackage, attachmentId, true)).andReturn(attachmentJob);
EasyMock.expect(distributionService.distribute(channelId, mediapackage, catalogId, true)).andReturn(catalogJob);
EasyMock.expect(distributionService.distribute(channelId, mediapackage, trackId, true)).andReturn(trackJob);
EasyMock.expect(distributionService.retract(channelId, mediapackage, channelId)).andReturn(retractJob);
EasyMock.replay(distributionService);
SecurityService securityService = EasyMock.createNiceMock(SecurityService.class);
EasyMock.expect(securityService.getOrganization()).andStubReturn(org);
EasyMock.replay(securityService);
ServiceRegistry serviceRegistry = EasyMock.createNiceMock(ServiceRegistry.class);
EasyMock.replay(serviceRegistry);
// Override the waitForStatus method to not block the jobs
ConfigurablePublishWorkflowOperationHandler configurePublish = new ConfigurablePublishWorkflowOperationHandler() {
@Override
protected Result waitForStatus(long timeout, Job... jobs) {
HashMap<Job, Status> map = Stream.mk(jobs).foldl(new HashMap<Job, Status>(), new Fn2<HashMap<Job, Status>, Job, HashMap<Job, Status>>() {
@Override
public HashMap<Job, Status> apply(HashMap<Job, Status> a, Job b) {
a.put(b, Status.FINISHED);
return a;
}
});
return new Result(map);
}
};
configurePublish.setDownloadDistributionService(distributionService);
configurePublish.setSecurityService(securityService);
configurePublish.setServiceRegistry(serviceRegistry);
WorkflowOperationResult result = configurePublish.start(workflowInstance, jobContext);
assertNotNull(result.getMediaPackage());
assertTrue("The publication element has not been added to the mediapackage.", capturePublication.hasCaptured());
assertTrue("Some other type of element has been added to the mediapackage instead of the publication element.", capturePublication.getValue().getElementType().equals(MediaPackageElement.Type.Publication));
Publication publication = (Publication) capturePublication.getValue();
assertEquals(1, publication.getAttachments().length);
assertNotEquals(attachment.getIdentifier(), publication.getAttachments()[0].getIdentifier());
attachment.setIdentifier(publication.getAttachments()[0].getIdentifier());
assertEquals(attachment, publication.getAttachments()[0]);
assertEquals(1, publication.getCatalogs().length);
assertNotEquals(catalog.getIdentifier(), publication.getCatalogs()[0].getIdentifier());
catalog.setIdentifier(publication.getCatalogs()[0].getIdentifier());
assertEquals(catalog, publication.getCatalogs()[0]);
assertEquals(1, publication.getTracks().length);
assertNotEquals(track.getIdentifier(), publication.getTracks()[0].getIdentifier());
track.setIdentifier(publication.getTracks()[0].getIdentifier());
assertEquals(track, publication.getTracks()[0]);
}
use of org.opencastproject.workflow.api.WorkflowInstance in project opencast by opencast.
the class JobEndpoint method getTasksAsJSON.
/**
* Returns the list of tasks matching the given query as JSON Object
*
* @param query
* The worklfow query
* @return The list of matching tasks as JSON Object
* @throws JobEndpointException
* @throws NotFoundException
*/
public JObject getTasksAsJSON(WorkflowQuery query) throws JobEndpointException, NotFoundException {
// Get results
WorkflowSet workflowInstances = null;
long totalWithoutFilters = 0;
List<JValue> jsonList = new ArrayList<>();
try {
workflowInstances = workflowService.getWorkflowInstances(query);
totalWithoutFilters = workflowService.countWorkflowInstances();
} catch (WorkflowDatabaseException e) {
throw new JobEndpointException(String.format("Not able to get the list of job from the database: %s", e), e.getCause());
}
WorkflowInstance[] items = workflowInstances.getItems();
for (WorkflowInstance instance : items) {
long instanceId = instance.getId();
String series = instance.getMediaPackage().getSeriesTitle();
// Retrieve submission date with the workflow instance main job
Date created;
try {
created = serviceRegistry.getJob(instanceId).getDateCreated();
} catch (ServiceRegistryException e) {
throw new JobEndpointException(String.format("Error when retrieving job %s from the service registry: %s", instanceId, e), e.getCause());
}
jsonList.add(obj(f("id", v(instanceId)), f("title", v(nul(instance.getMediaPackage().getTitle()).getOr(""))), f("series", v(series, Jsons.BLANK)), f("workflow", v(instance.getTitle(), Jsons.BLANK)), f("status", v(instance.getState().toString())), f("submitted", v(created != null ? DateTimeSupport.toUTC(created.getTime()) : ""))));
}
JObject json = obj(f("results", arr(jsonList)), f("count", v(workflowInstances.getTotalCount())), f("offset", v(query.getStartPage())), f("limit", v(jsonList.size())), f("total", v(totalWithoutFilters)));
return json;
}
use of org.opencastproject.workflow.api.WorkflowInstance in project opencast by opencast.
the class JobEndpoint method getOperationsAsJSON.
/**
* Returns the list of operations for a given workflow instance
*
* @param jobId
* the workflow instance id
* @return the list of workflow operations as JSON object
* @throws JobEndpointException
* @throws NotFoundException
*/
public JValue getOperationsAsJSON(long jobId) throws JobEndpointException, NotFoundException {
WorkflowInstance instance = getWorkflowById(jobId);
List<WorkflowOperationInstance> operations = instance.getOperations();
List<JValue> operationsJSON = new ArrayList<>();
for (WorkflowOperationInstance wflOp : operations) {
List<Field> fields = new ArrayList<>();
for (String key : wflOp.getConfigurationKeys()) {
fields.add(f(key, v(wflOp.getConfiguration(key), Jsons.BLANK)));
}
operationsJSON.add(obj(f("status", v(wflOp.getState(), Jsons.BLANK)), f("title", v(wflOp.getTemplate(), Jsons.BLANK)), f("description", v(wflOp.getDescription(), Jsons.BLANK)), f("id", v(wflOp.getId(), Jsons.BLANK)), f("configuration", obj(fields))));
}
return arr(operationsJSON);
}
use of org.opencastproject.workflow.api.WorkflowInstance in project opencast by opencast.
the class JobEndpoint method getOperationAsJSON.
/**
* Returns the operation with the given id from the given workflow instance
*
* @param jobId
* the workflow instance id
* @param operationPosition
* the operation position
* @return the operation as JSON object
* @throws JobEndpointException
* @throws NotFoundException
*/
public JObject getOperationAsJSON(long jobId, int operationPosition) throws JobEndpointException, NotFoundException {
WorkflowInstance instance = getWorkflowById(jobId);
List<WorkflowOperationInstance> operations = instance.getOperations();
if (operations.size() > operationPosition) {
WorkflowOperationInstance wflOp = operations.get(operationPosition);
return obj(f("retry_strategy", v(wflOp.getRetryStrategy(), Jsons.BLANK)), f("execution_host", v(wflOp.getExecutionHost(), Jsons.BLANK)), f("failed_attempts", v(wflOp.getFailedAttempts())), f("max_attempts", v(wflOp.getMaxAttempts())), f("exception_handler_workflow", v(wflOp.getExceptionHandlingWorkflow(), Jsons.BLANK)), f("fail_on_error", v(wflOp.isFailWorkflowOnException())), f("description", v(wflOp.getDescription(), Jsons.BLANK)), f("state", v(wflOp.getState(), Jsons.BLANK)), f("job", v(wflOp.getId(), Jsons.BLANK)), f("name", v(wflOp.getTemplate(), Jsons.BLANK)), f("time_in_queue", v(wflOp.getTimeInQueue(), v(0))), f("started", wflOp.getDateStarted() != null ? v(toUTC(wflOp.getDateStarted().getTime())) : Jsons.BLANK), f("completed", wflOp.getDateCompleted() != null ? v(toUTC(wflOp.getDateCompleted().getTime())) : Jsons.BLANK));
}
return null;
}
use of org.opencastproject.workflow.api.WorkflowInstance in project opencast by opencast.
the class TasksEndpoint method createNewTask.
@POST
@Path("/new")
@RestQuery(name = "createNewTask", description = "Creates a new task by the given metadata as JSON", returnDescription = "The task identifiers", restParameters = { @RestParameter(name = "metadata", isRequired = true, description = "The metadata as JSON", type = RestParameter.Type.TEXT) }, reponses = { @RestResponse(responseCode = HttpServletResponse.SC_CREATED, description = "Task sucessfully added"), @RestResponse(responseCode = SC_NOT_FOUND, description = "If the workflow definition is not found"), @RestResponse(responseCode = SC_BAD_REQUEST, description = "If the metadata is not set or couldn't be parsed") })
public Response createNewTask(@FormParam("metadata") String metadata) throws NotFoundException {
if (StringUtils.isBlank(metadata)) {
logger.warn("No metadata set");
return RestUtil.R.badRequest("No metadata set");
}
Gson gson = new Gson();
Map metadataJson = null;
try {
metadataJson = gson.fromJson(metadata, Map.class);
} catch (Exception e) {
logger.warn("Unable to parse metadata {}", metadata);
return RestUtil.R.badRequest("Unable to parse metadata");
}
String workflowId = (String) metadataJson.get("workflow");
if (StringUtils.isBlank(workflowId))
return RestUtil.R.badRequest("No workflow set");
List eventIds = (List) metadataJson.get("eventIds");
if (eventIds == null)
return RestUtil.R.badRequest("No eventIds set");
Map<String, String> configuration = (Map<String, String>) metadataJson.get("configuration");
if (configuration == null) {
configuration = new HashMap<>();
} else {
Iterator<String> confKeyIter = configuration.keySet().iterator();
while (confKeyIter.hasNext()) {
String confKey = confKeyIter.next();
if (StringUtils.equalsIgnoreCase("eventIds", confKey)) {
confKeyIter.remove();
}
}
}
WorkflowDefinition wfd;
try {
wfd = workflowService.getWorkflowDefinitionById(workflowId);
} catch (WorkflowDatabaseException e) {
logger.error("Unable to get workflow definition {}: {}", workflowId, ExceptionUtils.getStackTrace(e));
return RestUtil.R.serverError();
}
final Workflows workflows = new Workflows(assetManager, workspace, workflowService);
final List<WorkflowInstance> instances = workflows.applyWorkflowToLatestVersion(eventIds, workflow(wfd, configuration)).toList();
if (eventIds.size() != instances.size()) {
logger.debug("Can't start one or more tasks.");
return Response.status(Status.BAD_REQUEST).build();
}
return Response.status(Status.CREATED).entity(gson.toJson($(instances).map(getWorkflowIds).toList())).build();
}
Aggregations