use of org.opencastproject.workflow.api.WorkflowOperationException in project opencast by opencast.
the class CoverImageWorkflowOperationHandlerBase method getPosterImageFileUrl.
protected String getPosterImageFileUrl(MediaPackage mediaPackage, String posterimageFlavor) throws WorkflowOperationException {
if (posterimageFlavor == null) {
logger.debug("Optional configuration key '{}' not set", POSTERIMAGE_FLAVOR);
return null;
}
MediaPackageElementFlavor flavor;
try {
flavor = MediaPackageElementFlavor.parseFlavor(posterimageFlavor);
} catch (IllegalArgumentException e) {
logger.warn("'{}' is not a valid flavor", posterimageFlavor);
throw new WorkflowOperationException(e);
}
Attachment[] atts = mediaPackage.getAttachments(flavor);
if (atts.length > 1) {
logger.warn("More than one attachment with the flavor '{}' found in media package '{}'", posterimageFlavor, mediaPackage.getIdentifier());
throw new WorkflowOperationException("More than one attachment with the flavor'" + posterimageFlavor + "' found.");
} else if (atts.length == 0) {
logger.warn("No attachment with the flavor '{}' found in media package '{}'", posterimageFlavor, mediaPackage.getIdentifier());
return null;
}
try {
return getWorkspace().get(atts[0].getURI()).getAbsolutePath();
} catch (NotFoundException e) {
throw new WorkflowOperationException(e);
} catch (IOException e) {
throw new WorkflowOperationException(e);
}
}
use of org.opencastproject.workflow.api.WorkflowOperationException in project opencast by opencast.
the class CoverImageWorkflowOperationHandlerBase method loadXsl.
protected String loadXsl(WorkflowOperationInstance operation) throws WorkflowOperationException {
String xslUriString = operation.getConfiguration(XSL_FILE_URL);
if (StringUtils.isBlank(xslUriString))
throw new WorkflowOperationException("Configuration option '" + XSL_FILE_URL + "' must not be empty");
FileReader reader = null;
try {
URI xslUri = new URI(xslUriString);
File xslFile = new File(xslUri);
reader = new FileReader(xslFile);
return IOUtils.toString(reader);
} catch (FileNotFoundException e) {
logger.warn("There is no (xsl) file at the given uri '{}': {}", xslUriString, e.getMessage());
throw new WorkflowOperationException("There is no (XSL) file at the given URI", e);
} catch (URISyntaxException e) {
logger.warn("Given XSL file URI ({}) is not valid: {}", xslUriString, e.getMessage());
throw new WorkflowOperationException("Given XSL file URI is not valid", e);
} catch (IOException e) {
logger.warn("Error while reading XSL file ({}): {}", xslUriString, e.getMessage());
throw new WorkflowOperationException("Error while reading XSL file", e);
} finally {
IOUtils.closeQuietly(reader);
}
}
use of org.opencastproject.workflow.api.WorkflowOperationException in project opencast by opencast.
the class CompositeWorkflowOperationHandler method handleSingleTrack.
private WorkflowOperationResult handleSingleTrack(MediaPackage mediaPackage, WorkflowOperationInstance operation, CompositeSettings compositeSettings, Option<Attachment> watermarkAttachment) throws EncoderException, IOException, NotFoundException, MediaPackageException, WorkflowOperationException {
if (compositeSettings.getSingleSourceLayout() == null) {
throw new WorkflowOperationException("Single video layout must be set! Please verify that you have a " + LAYOUT_SINGLE + " property in your composite operation in your workflow definition.");
}
try {
VideoStream[] videoStreams = TrackSupport.byType(compositeSettings.getSingleTrack().getStreams(), VideoStream.class);
if (videoStreams.length == 0) {
logger.warn("No video stream available to compose! {}", compositeSettings.getSingleTrack());
return createResult(mediaPackage, Action.SKIP);
}
// Read the video dimensions from the mediapackage stream information
Dimension videoDimension = Dimension.dimension(videoStreams[0].getFrameWidth(), videoStreams[0].getFrameHeight());
// Create the video layout definitions
List<Tuple<Dimension, HorizontalCoverageLayoutSpec>> shapes = new ArrayList<Tuple<Dimension, HorizontalCoverageLayoutSpec>>();
shapes.add(0, Tuple.tuple(videoDimension, compositeSettings.getSingleSourceLayout()));
// Determine dimension of output
Dimension outputDimension = null;
String outputResolutionSource = compositeSettings.getOutputResolutionSource();
if (outputResolutionSource.equals(CompositeSettings.OUTPUT_RESOLUTION_FIXED)) {
outputDimension = compositeSettings.getOutputDimension();
} else if (outputResolutionSource.equals(CompositeSettings.OUTPUT_RESOLUTION_LOWER)) {
outputDimension = videoDimension;
} else if (outputResolutionSource.equals(CompositeSettings.OUTPUT_RESOLUTION_UPPER)) {
outputDimension = videoDimension;
}
// Calculate the single layout
MultiShapeLayout multiShapeLayout = LayoutManager.multiShapeLayout(outputDimension, shapes);
// Create the laid out element for the videos
LaidOutElement<Track> lowerLaidOutElement = new LaidOutElement<Track>(compositeSettings.getSingleTrack(), multiShapeLayout.getShapes().get(0));
// Create the optionally laid out element for the watermark
Option<LaidOutElement<Attachment>> watermarkOption = createWatermarkLaidOutElement(compositeSettings, outputDimension, watermarkAttachment);
Job compositeJob = composerService.composite(outputDimension, Option.<LaidOutElement<Track>>none(), lowerLaidOutElement, watermarkOption, compositeSettings.getProfile().getIdentifier(), compositeSettings.getOutputBackground());
// Wait for the jobs to return
if (!waitForStatus(compositeJob).isSuccess())
throw new WorkflowOperationException("The composite job did not complete successfully");
if (compositeJob.getPayload().length() > 0) {
Track compoundTrack = (Track) MediaPackageElementParser.getFromXml(compositeJob.getPayload());
compoundTrack.setURI(workspace.moveTo(compoundTrack.getURI(), mediaPackage.getIdentifier().toString(), compoundTrack.getIdentifier(), "composite." + FilenameUtils.getExtension(compoundTrack.getURI().toString())));
// Adjust the target tags
for (String tag : compositeSettings.getTargetTags()) {
logger.trace("Tagging compound track with '{}'", tag);
compoundTrack.addTag(tag);
}
// Adjust the target flavor.
compoundTrack.setFlavor(compositeSettings.getTargetFlavor());
logger.debug("Compound track has flavor '{}'", compoundTrack.getFlavor());
// store new tracks to mediaPackage
mediaPackage.add(compoundTrack);
WorkflowOperationResult result = createResult(mediaPackage, Action.CONTINUE, compositeJob.getQueueTime());
logger.debug("Composite operation completed");
return result;
} else {
logger.info("Composite operation unsuccessful, no payload returned: {}", compositeJob);
return createResult(mediaPackage, Action.SKIP);
}
} finally {
if (compositeSettings.getSourceUrlWatermark() != null)
workspace.deleteFromCollection(COLLECTION, compositeSettings.getWatermarkIdentifier() + "." + FilenameUtils.getExtension(compositeSettings.getSourceUrlWatermark()));
}
}
use of org.opencastproject.workflow.api.WorkflowOperationException in project opencast by opencast.
the class ComposeWorkflowOperationHandler method encode.
/**
* Encode tracks from MediaPackage using profiles stored in properties and updates current MediaPackage.
*
* @param src
* The source media package
* @param operation
* the current workflow operation
* @return the operation result containing the updated media package
* @throws EncoderException
* if encoding fails
* @throws WorkflowOperationException
* if errors occur during processing
* @throws IOException
* if the workspace operations fail
* @throws NotFoundException
* if the workspace doesn't contain the requested file
*/
private WorkflowOperationResult encode(MediaPackage src, WorkflowOperationInstance operation) throws EncoderException, IOException, NotFoundException, MediaPackageException, WorkflowOperationException {
MediaPackage mediaPackage = (MediaPackage) src.clone();
// Check which tags have been configured
String sourceTagsOption = StringUtils.trimToNull(operation.getConfiguration("source-tags"));
String targetTagsOption = StringUtils.trimToNull(operation.getConfiguration("target-tags"));
String sourceFlavorOption = StringUtils.trimToNull(operation.getConfiguration("source-flavor"));
String sourceFlavorsOption = StringUtils.trimToNull(operation.getConfiguration("source-flavors"));
String targetFlavorOption = StringUtils.trimToNull(operation.getConfiguration("target-flavor"));
boolean tagsAndFlavorsOption = Boolean.parseBoolean(StringUtils.trimToNull(operation.getConfiguration("tags-and-flavors")));
AbstractMediaPackageElementSelector<Track> elementSelector = new TrackSelector();
// Make sure either one of tags or flavors are provided
if (StringUtils.isBlank(sourceTagsOption) && StringUtils.isBlank(sourceFlavorOption) && StringUtils.isBlank(sourceFlavorsOption)) {
logger.info("No source tags or flavors have been specified, not matching anything");
return createResult(mediaPackage, Action.CONTINUE);
}
// Select the source flavors
for (String flavor : asList(sourceFlavorsOption)) {
try {
elementSelector.addFlavor(MediaPackageElementFlavor.parseFlavor(flavor));
} catch (IllegalArgumentException e) {
throw new WorkflowOperationException("Source flavor '" + flavor + "' is malformed");
}
}
// Support legacy "source-flavor" option
if (StringUtils.isNotBlank(sourceFlavorOption)) {
String flavor = StringUtils.trim(sourceFlavorOption);
try {
elementSelector.addFlavor(MediaPackageElementFlavor.parseFlavor(flavor));
} catch (IllegalArgumentException e) {
throw new WorkflowOperationException("Source flavor '" + flavor + "' is malformed");
}
}
// Select the source tags
for (String tag : asList(sourceTagsOption)) {
elementSelector.addTag(tag);
}
// Find the encoding profile
String profilesOption = StringUtils.trimToNull(operation.getConfiguration("encoding-profiles"));
List<EncodingProfile> profiles = new ArrayList<EncodingProfile>();
for (String profileName : asList(profilesOption)) {
EncodingProfile profile = composerService.getProfile(profileName);
if (profile == null)
throw new WorkflowOperationException("Encoding profile '" + profileName + "' was not found");
profiles.add(profile);
}
// Support legacy "encoding-profile" option
String profileOption = StringUtils.trimToNull(operation.getConfiguration("encoding-profile"));
if (StringUtils.isNotBlank(profileOption)) {
String profileId = StringUtils.trim(profileOption);
EncodingProfile profile = composerService.getProfile(profileId);
if (profile == null)
throw new WorkflowOperationException("Encoding profile '" + profileId + "' was not found");
profiles.add(profile);
}
// Make sure there is at least one profile
if (profiles.isEmpty())
throw new WorkflowOperationException("No encoding profile was specified");
// Audio / Video only?
String audioOnlyConfig = StringUtils.trimToNull(operation.getConfiguration("audio-only"));
String videoOnlyConfig = StringUtils.trimToNull(operation.getConfiguration("video-only"));
boolean audioOnly = audioOnlyConfig != null && Boolean.parseBoolean(audioOnlyConfig);
boolean videoOnly = videoOnlyConfig != null && Boolean.parseBoolean(videoOnlyConfig);
// Target tags
List<String> targetTags = asList(targetTagsOption);
// Target flavor
MediaPackageElementFlavor targetFlavor = null;
if (StringUtils.isNotBlank(targetFlavorOption)) {
try {
targetFlavor = MediaPackageElementFlavor.parseFlavor(targetFlavorOption);
} catch (IllegalArgumentException e) {
throw new WorkflowOperationException("Target flavor '" + targetFlavorOption + "' is malformed");
}
}
// Look for elements matching the tag
Collection<Track> elements = elementSelector.select(mediaPackage, tagsAndFlavorsOption);
String processOnlyOneConfig = StringUtils.trimToNull(operation.getConfiguration("process-first-match-only"));
boolean processOnlyOne = processOnlyOneConfig != null && Boolean.parseBoolean(processOnlyOneConfig);
// Encode all tracks found
long totalTimeInQueue = 0;
Map<Job, JobInformation> encodingJobs = new HashMap<Job, JobInformation>();
for (Track track : elements) {
// Skip audio/video only mismatches
if (audioOnly && track.hasVideo()) {
logger.info("Skipping encoding of '{}', since it contains a video stream", track);
continue;
} else if (videoOnly && track.hasAudio()) {
logger.info("Skipping encoding of '{}', since it containsa an audio stream", track);
continue;
}
// Encode the track with all profiles
for (EncodingProfile profile : profiles) {
// Check if the track supports the output type of the profile
MediaType outputType = profile.getOutputType();
if (outputType.equals(MediaType.Audio) && !track.hasAudio()) {
logger.info("Skipping encoding of '{}', since it lacks an audio stream", track);
continue;
} else if (outputType.equals(MediaType.Visual) && !track.hasVideo()) {
logger.info("Skipping encoding of '{}', since it lacks a video stream", track);
continue;
}
logger.info("Encoding track {} using encoding profile '{}'", track, profile);
// Start encoding and wait for the result
encodingJobs.put(composerService.encode(track, profile.getIdentifier()), new JobInformation(track, profile));
if (processOnlyOne)
break;
}
}
if (encodingJobs.isEmpty()) {
logger.info("No matching tracks found");
return createResult(mediaPackage, Action.CONTINUE);
}
// Wait for the jobs to return
if (!waitForStatus(encodingJobs.keySet().toArray(new Job[encodingJobs.size()])).isSuccess()) {
throw new WorkflowOperationException("One of the encoding jobs did not complete successfully");
}
// Process the result
for (Map.Entry<Job, JobInformation> entry : encodingJobs.entrySet()) {
Job job = entry.getKey();
Track track = entry.getValue().getTrack();
// add this receipt's queue time to the total
totalTimeInQueue += job.getQueueTime();
// it is allowed for compose jobs to return an empty payload. See the EncodeEngine interface
if (job.getPayload().length() > 0) {
Track composedTrack = (Track) MediaPackageElementParser.getFromXml(job.getPayload());
// Adjust the target tags
for (String tag : targetTags) {
logger.trace("Tagging composed track with '{}'", tag);
composedTrack.addTag(tag);
}
// Adjust the target flavor. Make sure to account for partial updates
if (targetFlavor != null) {
String flavorType = targetFlavor.getType();
String flavorSubtype = targetFlavor.getSubtype();
if ("*".equals(flavorType))
flavorType = track.getFlavor().getType();
if ("*".equals(flavorSubtype))
flavorSubtype = track.getFlavor().getSubtype();
composedTrack.setFlavor(new MediaPackageElementFlavor(flavorType, flavorSubtype));
logger.debug("Composed track has flavor '{}'", composedTrack.getFlavor());
}
// store new tracks to mediaPackage
mediaPackage.addDerived(composedTrack, track);
String fileName = getFileNameFromElements(track, composedTrack);
composedTrack.setURI(workspace.moveTo(composedTrack.getURI(), mediaPackage.getIdentifier().toString(), composedTrack.getIdentifier(), fileName));
}
}
WorkflowOperationResult result = createResult(mediaPackage, Action.CONTINUE, totalTimeInQueue);
logger.debug("Compose operation completed");
return result;
}
use of org.opencastproject.workflow.api.WorkflowOperationException in project opencast by opencast.
the class TimelinePreviewsWorkflowOperationHandler method start.
/**
* {@inheritDoc}
*
* @see
* org.opencastproject.workflow.api.WorkflowOperationHandler#start(org.opencastproject.workflow.api.WorkflowInstance,
* org.opencastproject.job.api.JobContext)
*/
@Override
public WorkflowOperationResult start(WorkflowInstance workflowInstance, JobContext context) throws WorkflowOperationException {
MediaPackage mediaPackage = workflowInstance.getMediaPackage();
logger.info("Start timeline previews workflow operation for mediapackage {}", mediaPackage.getIdentifier().compact());
String sourceFlavorProperty = StringUtils.trimToNull(workflowInstance.getCurrentOperation().getConfiguration(SOURCE_FLAVOR_PROPERTY));
String sourceTagsProperty = StringUtils.trimToNull(workflowInstance.getCurrentOperation().getConfiguration(SOURCE_TAGS_PROPERTY));
if (StringUtils.isEmpty(sourceFlavorProperty) && StringUtils.isEmpty(sourceTagsProperty)) {
throw new WorkflowOperationException(String.format("Required property %s or %s not set", SOURCE_FLAVOR_PROPERTY, SOURCE_TAGS_PROPERTY));
}
String targetFlavorProperty = StringUtils.trimToNull(workflowInstance.getCurrentOperation().getConfiguration(TARGET_FLAVOR_PROPERTY));
if (targetFlavorProperty == null) {
throw new WorkflowOperationException(String.format("Required property %s not set", TARGET_FLAVOR_PROPERTY));
}
String targetTagsProperty = StringUtils.trimToNull(workflowInstance.getCurrentOperation().getConfiguration(TARGET_TAGS_PROPERTY));
String imageSizeArg = StringUtils.trimToNull(workflowInstance.getCurrentOperation().getConfiguration(IMAGE_SIZE_PROPERTY));
int imageSize;
if (imageSizeArg != null) {
try {
imageSize = Integer.parseInt(imageSizeArg);
} catch (NumberFormatException e) {
imageSize = DEFAULT_IMAGE_SIZE;
logger.info("No valid integer given for property {}, using default value: {}", IMAGE_SIZE_PROPERTY, DEFAULT_IMAGE_SIZE);
}
} else {
imageSize = DEFAULT_IMAGE_SIZE;
logger.info("Property {} not set, using default value: {}", IMAGE_SIZE_PROPERTY, DEFAULT_IMAGE_SIZE);
}
TrackSelector trackSelector = new TrackSelector();
for (String flavor : asList(sourceFlavorProperty)) {
trackSelector.addFlavor(flavor);
}
for (String tag : asList(sourceTagsProperty)) {
trackSelector.addTag(tag);
}
Collection<Track> sourceTracks = trackSelector.select(mediaPackage, false);
if (sourceTracks.isEmpty()) {
logger.info("No tracks found in mediapackage {} with specified {} {}", mediaPackage.getIdentifier().compact(), SOURCE_FLAVOR_PROPERTY, sourceFlavorProperty);
createResult(mediaPackage, WorkflowOperationResult.Action.SKIP);
}
List<Job> timelinepreviewsJobs = new ArrayList<Job>(sourceTracks.size());
for (Track sourceTrack : sourceTracks) {
try {
// generate timeline preview images
logger.info("Create timeline previews job for track '{}' in mediapackage '{}'", sourceTrack.getIdentifier(), mediaPackage.getIdentifier().compact());
Job timelinepreviewsJob = timelinePreviewsService.createTimelinePreviewImages(sourceTrack, imageSize);
timelinepreviewsJobs.add(timelinepreviewsJob);
} catch (MediaPackageException | TimelinePreviewsException ex) {
logger.error("Creating timeline previews job for track '{}' in media package '{}' failed with error {}", sourceTrack.getIdentifier(), mediaPackage.getIdentifier().compact(), ex.getMessage());
}
}
logger.info("Wait for timeline previews jobs for media package {}", mediaPackage.getIdentifier().compact());
if (!waitForStatus(timelinepreviewsJobs.toArray(new Job[timelinepreviewsJobs.size()])).isSuccess()) {
cleanupWorkspace(timelinepreviewsJobs);
throw new WorkflowOperationException(String.format("Timeline previews jobs for media package '%s' have not completed successfully", mediaPackage.getIdentifier().compact()));
}
try {
// copy timeline previews attachments into workspace and add them to the media package
for (Job job : timelinepreviewsJobs) {
String jobPayload = job.getPayload();
if (StringUtils.isNotEmpty(jobPayload)) {
MediaPackageElement timelinePreviewsMpe = null;
File timelinePreviewsFile = null;
try {
timelinePreviewsMpe = MediaPackageElementParser.getFromXml(jobPayload);
timelinePreviewsFile = workspace.get(timelinePreviewsMpe.getURI());
} catch (MediaPackageException ex) {
// unexpected job payload
throw new WorkflowOperationException("Can't parse timeline previews attachment from job " + job.getId());
} catch (NotFoundException ex) {
throw new WorkflowOperationException("Timeline preview images file '" + timelinePreviewsMpe.getURI() + "' not found", ex);
} catch (IOException ex) {
throw new WorkflowOperationException("Can't get workflow image file '" + timelinePreviewsMpe.getURI() + "' from workspace");
}
FileInputStream timelinePreviewsInputStream = null;
logger.info("Put timeline preview images file {} from media package {} to the media package work space", timelinePreviewsMpe.getURI(), mediaPackage.getIdentifier().compact());
try {
timelinePreviewsInputStream = new FileInputStream(timelinePreviewsFile);
String fileName = FilenameUtils.getName(timelinePreviewsMpe.getURI().getPath());
URI timelinePreviewsWfrUri = workspace.put(mediaPackage.getIdentifier().compact(), timelinePreviewsMpe.getIdentifier(), fileName, timelinePreviewsInputStream);
timelinePreviewsMpe.setURI(timelinePreviewsWfrUri);
} catch (FileNotFoundException ex) {
throw new WorkflowOperationException("Timeline preview images file " + timelinePreviewsFile.getPath() + " not found", ex);
} catch (IOException ex) {
throw new WorkflowOperationException("Can't read just created timeline preview images file " + timelinePreviewsFile.getPath(), ex);
} catch (IllegalArgumentException ex) {
throw new WorkflowOperationException(ex);
} finally {
IoSupport.closeQuietly(timelinePreviewsInputStream);
}
// set the timeline previews attachment flavor and add it to the mediapackage
MediaPackageElementFlavor targetFlavor = MediaPackageElementFlavor.parseFlavor(targetFlavorProperty);
if ("*".equals(targetFlavor.getType())) {
targetFlavor = new MediaPackageElementFlavor(timelinePreviewsMpe.getFlavor().getType(), targetFlavor.getSubtype());
}
if ("*".equals(targetFlavor.getSubtype())) {
targetFlavor = new MediaPackageElementFlavor(targetFlavor.getType(), timelinePreviewsMpe.getFlavor().getSubtype());
}
timelinePreviewsMpe.setFlavor(targetFlavor);
if (!StringUtils.isEmpty(targetTagsProperty)) {
for (String tag : asList(targetTagsProperty)) {
timelinePreviewsMpe.addTag(tag);
}
}
mediaPackage.add(timelinePreviewsMpe);
}
}
} finally {
cleanupWorkspace(timelinepreviewsJobs);
}
logger.info("Timeline previews workflow operation for mediapackage {} completed", mediaPackage.getIdentifier().compact());
return createResult(mediaPackage, WorkflowOperationResult.Action.CONTINUE);
}
Aggregations