use of org.opencastproject.workflow.api.WorkflowOperationException in project opencast by opencast.
the class AssetManagerDeleteWorkflowOperationHandler method start.
@Override
public WorkflowOperationResult start(WorkflowInstance workflowInstance, JobContext context) throws WorkflowOperationException {
final MediaPackage mediaPackage = workflowInstance.getMediaPackage();
final String mpId = mediaPackage.getIdentifier().toString();
try {
final AQueryBuilder q = assetManager.createQuery();
final long deleted = q.delete(DEFAULT_OWNER, q.snapshot()).where(q.mediaPackageId(mpId)).run();
if (deleted == 0) {
logger.info(format("The asset manager does not contain episode %s", mpId));
} else {
logger.info(format("Successfully deleted %d version/s episode %s from the asset manager", deleted, mpId));
}
} catch (Exception e) {
logger.warn(format("Error deleting episode %s from the asset manager: %s", mpId, e));
throw new WorkflowOperationException("Unable to delete episode from the asset manager", e);
}
return createResult(mediaPackage, Action.CONTINUE);
}
use of org.opencastproject.workflow.api.WorkflowOperationException in project opencast by opencast.
the class ExecuteOnceWorkflowOperationHandler method start.
/**
* {@inheritDoc}
*
* @see org.opencastproject.workflow.api.WorkflowOperationHandler#start(org.opencastproject.workflow.api.WorkflowInstance, JobContext)
*/
@Override
public WorkflowOperationResult start(WorkflowInstance workflowInstance, JobContext context) throws WorkflowOperationException {
MediaPackage mediaPackage = workflowInstance.getMediaPackage();
WorkflowOperationInstance operation = workflowInstance.getCurrentOperation();
logger.debug("Running execute workflow operation with ID {}", operation.getId());
// Get operation parameters
String exec = StringUtils.trimToNull(operation.getConfiguration(EXEC_PROPERTY));
String params = StringUtils.trimToNull(operation.getConfiguration(PARAMS_PROPERTY));
float load = 1.0f;
String loadPropertyStr = StringUtils.trimToEmpty(operation.getConfiguration(LOAD_PROPERTY));
if (StringUtils.isNotBlank(loadPropertyStr)) {
try {
load = Float.parseFloat(loadPropertyStr);
} catch (NumberFormatException e) {
String description = StringUtils.trimToEmpty(operation.getDescription());
logger.warn("Ignoring invalid load value '{}' on execute operation with description '{}'", loadPropertyStr, description);
}
}
String targetFlavorStr = StringUtils.trimToNull(operation.getConfiguration(TARGET_FLAVOR_PROPERTY));
String targetTags = StringUtils.trimToNull(operation.getConfiguration(TARGET_TAGS_PROPERTY));
String outputFilename = StringUtils.trimToNull(operation.getConfiguration(OUTPUT_FILENAME_PROPERTY));
String expectedTypeStr = StringUtils.trimToNull(operation.getConfiguration(EXPECTED_TYPE_PROPERTY));
boolean setWfProps = Boolean.valueOf(StringUtils.trimToNull(operation.getConfiguration(SET_WF_PROPS_PROPERTY)));
// Unmarshall target flavor
MediaPackageElementFlavor targetFlavor = null;
if (targetFlavorStr != null)
targetFlavor = MediaPackageElementFlavor.parseFlavor(targetFlavorStr);
// Unmarshall expected mediapackage element type
MediaPackageElement.Type expectedType = null;
if (expectedTypeStr != null) {
for (MediaPackageElement.Type type : MediaPackageElement.Type.values()) if (type.toString().equalsIgnoreCase(expectedTypeStr)) {
expectedType = type;
break;
}
if (expectedType == null)
throw new WorkflowOperationException("'" + expectedTypeStr + "' is not a valid element type");
}
// Process the result element
MediaPackageElement resultElement = null;
try {
Job job = executeService.execute(exec, params, mediaPackage, outputFilename, expectedType, load);
WorkflowOperationResult result = null;
// Wait for all jobs to be finished
if (!waitForStatus(job).isSuccess())
throw new WorkflowOperationException("Execute operation failed");
if (StringUtils.isNotBlank(job.getPayload())) {
if (setWfProps) {
// The job payload is a file with set of properties for the workflow
resultElement = MediaPackageElementParser.getFromXml(job.getPayload());
final Properties properties = new Properties();
File propertiesFile = workspace.get(resultElement.getURI());
try (InputStream is = new FileInputStream(propertiesFile)) {
properties.load(is);
}
logger.debug("Loaded {} properties from {}", properties.size(), propertiesFile);
workspace.deleteFromCollection(ExecuteService.COLLECTION, propertiesFile.getName());
Map<String, String> wfProps = new HashMap<String, String>((Map) properties);
result = createResult(mediaPackage, wfProps, Action.CONTINUE, job.getQueueTime());
} else {
// The job payload is a new element for the MediaPackage
resultElement = MediaPackageElementParser.getFromXml(job.getPayload());
if (resultElement.getElementType() == MediaPackageElement.Type.Track) {
// Have the track inspected and return the result
Job inspectionJob = null;
inspectionJob = inspectionService.inspect(resultElement.getURI());
JobBarrier barrier = new JobBarrier(job, serviceRegistry, inspectionJob);
if (!barrier.waitForJobs().isSuccess()) {
throw new ExecuteException("Media inspection of " + resultElement.getURI() + " failed");
}
resultElement = MediaPackageElementParser.getFromXml(inspectionJob.getPayload());
}
// Store new element to mediaPackage
mediaPackage.add(resultElement);
URI uri = workspace.moveTo(resultElement.getURI(), mediaPackage.getIdentifier().toString(), resultElement.getIdentifier(), outputFilename);
resultElement.setURI(uri);
// Set new flavor
if (targetFlavor != null)
resultElement.setFlavor(targetFlavor);
// Set new tags
if (targetTags != null) {
// Assume the tags starting with "-" means we want to eliminate such tags form the result element
for (String tag : asList(targetTags)) {
if (tag.startsWith("-"))
// We remove the tag resulting from stripping all the '-' characters at the beginning of the tag
resultElement.removeTag(tag.replaceAll("^-+", ""));
else
resultElement.addTag(tag);
}
}
result = createResult(mediaPackage, Action.CONTINUE, job.getQueueTime());
}
} else {
// Payload is empty
result = createResult(mediaPackage, Action.CONTINUE, job.getQueueTime());
}
logger.debug("Execute operation {} completed", operation.getId());
return result;
} catch (ExecuteException e) {
throw new WorkflowOperationException(e);
} catch (MediaPackageException e) {
throw new WorkflowOperationException("Some result element couldn't be serialized", e);
} catch (NotFoundException e) {
throw new WorkflowOperationException("Could not find mediapackage", e);
} catch (IOException e) {
throw new WorkflowOperationException("Error unmarshalling a result mediapackage element", e);
} catch (MediaInspectionException e) {
throw new WorkflowOperationException("Media inspection of " + resultElement.getURI() + " failed", e);
}
}
use of org.opencastproject.workflow.api.WorkflowOperationException in project opencast by opencast.
the class EmailWorkflowOperationHandler method start.
/**
* {@inheritDoc}
*/
@Override
public WorkflowOperationResult start(WorkflowInstance workflowInstance, JobContext context) throws WorkflowOperationException {
// The current workflow operation instance
WorkflowOperationInstance operation = workflowInstance.getCurrentOperation();
// MediaPackage from previous workflow operations
MediaPackage srcPackage = workflowInstance.getMediaPackage();
// "To", "CC", "BCC", subject, body can be Freemarker templates
String to = applyTemplateIfNecessary(workflowInstance, operation, TO_PROPERTY);
String cc = applyTemplateIfNecessary(workflowInstance, operation, CC_PROPERTY);
String bcc = applyTemplateIfNecessary(workflowInstance, operation, BCC_PROPERTY);
String subject = applyTemplateIfNecessary(workflowInstance, operation, SUBJECT_PROPERTY);
String bodyText = null;
String body = operation.getConfiguration(BODY_PROPERTY);
// If specified, templateFile is a file that contains the Freemarker template
String bodyTemplateFile = operation.getConfiguration(BODY_TEMPLATE_FILE_PROPERTY);
// Body informed? If not, use the default.
if (body == null && bodyTemplateFile == null) {
// Set the body of the message to be the ID of the media package
bodyText = srcPackage.getTitle() + "(" + srcPackage.getIdentifier().toString() + ")";
} else if (body != null) {
bodyText = applyTemplateIfNecessary(workflowInstance, operation, BODY_PROPERTY);
} else {
bodyText = applyTemplateIfNecessary(workflowInstance, operation, BODY_TEMPLATE_FILE_PROPERTY);
}
try {
logger.debug("Sending e-mail notification with subject {} and body {} to {}, CC addresses {} and BCC addresses {}", subject, bodyText, to, cc, bcc);
// "To", "CC" and "BCC" can be comma- or space-separated lists of emails
smtpService.send(to, cc, bcc, subject, bodyText);
logger.info("E-mail notification sent to {}, CC addresses {} and BCC addresses {}", to, cc, bcc);
} catch (MessagingException e) {
throw new WorkflowOperationException(e);
}
// Return the source mediapackage and tell processing to continue
return createResult(srcPackage, Action.CONTINUE);
}
use of org.opencastproject.workflow.api.WorkflowOperationException in project opencast by opencast.
the class MediaPackagePostOperationHandler method start.
/**
* {@inheritDoc}
*
* @see org.opencastproject.workflow.api.WorkflowOperationHandler#start(org.opencastproject.workflow.api.WorkflowInstance,
* JobContext)
*/
public WorkflowOperationResult start(final WorkflowInstance workflowInstance, JobContext context) throws WorkflowOperationException {
// get configuration
WorkflowOperationInstance currentOperation = workflowInstance.getCurrentOperation();
Configuration config = new Configuration(currentOperation);
MediaPackage workflowMP = workflowInstance.getMediaPackage();
MediaPackage mp = workflowMP;
/* Check if we need to replace the Mediapackage we got with the published
* Mediapackage from the Search Service */
if (config.mpFromSearch()) {
SearchQuery searchQuery = new SearchQuery();
searchQuery.withId(mp.getIdentifier().toString());
SearchResult result = searchService.getByQuery(searchQuery);
if (result.size() != 1) {
throw new WorkflowOperationException("Received multiple results for identifier" + "\"" + mp.getIdentifier().toString() + "\" from search service. ");
}
logger.info("Getting Mediapackage from Search Service");
mp = result.getItems()[0].getMediaPackage();
}
logger.info("Submitting \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString() + ") as " + config.getFormat().name() + " to " + config.getUrl().toString());
try {
// serialize MediaPackage to target format
String mpStr;
if (config.getFormat() == Configuration.Format.JSON) {
mpStr = MediaPackageParser.getAsJSON(mp);
} else {
mpStr = MediaPackageParser.getAsXml(mp);
}
// Log mediapackge
if (config.debug()) {
logger.info(mpStr);
}
// constrcut message body
List<NameValuePair> data = new ArrayList<NameValuePair>();
data.add(new BasicNameValuePair("mediapackage", mpStr));
data.addAll(config.getAdditionalFields());
// construct POST
HttpPost post = new HttpPost(config.getUrl());
post.setEntity(new UrlEncodedFormEntity(data, config.getEncoding()));
// execute POST
DefaultHttpClient client = new DefaultHttpClient();
// Handle authentication
if (config.authenticate()) {
URL targetUrl = config.getUrl().toURL();
client.getCredentialsProvider().setCredentials(new AuthScope(targetUrl.getHost(), targetUrl.getPort()), config.getCredentials());
}
HttpResponse response = client.execute(post);
// throw Exception if target host did not return 200
int status = response.getStatusLine().getStatusCode();
if ((status >= 200) && (status < 300)) {
if (config.debug()) {
logger.info("Successfully submitted \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString() + ") to " + config.getUrl().toString() + ": " + status);
}
} else if (status == 418) {
logger.warn("Submitted \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString() + ") to " + config.getUrl().toString() + ": The target claims to be a teapot. " + "The Reason for this is probably an insane programmer.");
} else {
throw new WorkflowOperationException("Faild to submit \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString() + "), " + config.getUrl().toString() + " answered with: " + Integer.toString(status));
}
} catch (Exception e) {
if (e instanceof WorkflowOperationException) {
throw (WorkflowOperationException) e;
} else {
logger.error("Submitting mediapackage failed: {}", e.toString());
throw new WorkflowOperationException(e);
}
}
return createResult(workflowMP, Action.CONTINUE);
}
use of org.opencastproject.workflow.api.WorkflowOperationException in project opencast by opencast.
the class MediaPackagePostOperationHandlerTest method testHTTPPostXML.
@Test
public void testHTTPPostXML() throws Exception {
// create a dummy mediapackage
MediaPackageBuilderFactory factory = MediaPackageBuilderFactory.newInstance();
MediaPackageBuilder builder = factory.newMediaPackageBuilder();
MediaPackage mp = builder.createNew(new IdImpl("xyz"));
mp.setTitle("test");
mp.addContributor("lkiesow");
mp.addContributor("lkiesow");
/* Sending stuff to port 9 shound never return anything as the Discard
* Protocol uses port 9 */
InstanceAndHandler tuple = createWorkflow("http://127.0.0.1:9", "xml");
MediaPackagePostOperationHandler handler = (MediaPackagePostOperationHandler) tuple.workflowHandler;
tuple.workflowInstance.setMediaPackage(mp);
try {
tuple.workflowHandler.start(tuple.workflowInstance, null);
/* This should raise an exception. Something is wrong if not. */
Assert.fail();
} catch (WorkflowOperationException e) {
logger.info(e.toString());
}
}
Aggregations