use of org.opencastproject.util.MimeType in project opencast by opencast.
the class MediaInspector method enrichTrack.
/**
* Enriches the track's metadata and can be executed in an asynchronous way.
*
* @param originalTrack
* the original track
* @param override
* <code>true</code> to override existing metadata
* @return the media package element
* @throws MediaInspectionException
*/
private MediaPackageElement enrichTrack(final Track originalTrack, final boolean override, final Map<String, String> options) throws MediaInspectionException {
try {
URI originalTrackUrl = originalTrack.getURI();
MediaPackageElementFlavor flavor = originalTrack.getFlavor();
logger.debug("enrich(" + originalTrackUrl + ") called");
// Get the file from the URL
File file = null;
try {
file = workspace.get(originalTrackUrl);
} catch (NotFoundException e) {
throw new MediaInspectionException("File " + originalTrackUrl + " was not found and can therefore not be " + "inspected", e);
} catch (IOException e) {
throw new MediaInspectionException("Error accessing " + originalTrackUrl, e);
}
// TODO: Try to guess the extension from the container's metadata
if ("".equals(FilenameUtils.getExtension(file.getName()))) {
throw new MediaInspectionException("Can not inspect files without a filename extension");
}
MediaContainerMetadata metadata = getFileMetadata(file, getAccurateFrameCount(options));
if (metadata == null) {
throw new MediaInspectionException("Unable to acquire media metadata for " + originalTrackUrl);
} else {
TrackImpl track = null;
try {
track = (TrackImpl) MediaPackageElementBuilderFactory.newInstance().newElementBuilder().elementFromURI(originalTrackUrl, MediaPackageElement.Type.Track, flavor);
} catch (UnsupportedElementException e) {
throw new MediaInspectionException("Unable to create track element from " + file, e);
}
// init the new track with old
track.setChecksum(originalTrack.getChecksum());
track.setDuration(originalTrack.getDuration());
track.setElementDescription(originalTrack.getElementDescription());
track.setFlavor(flavor);
track.setIdentifier(originalTrack.getIdentifier());
track.setMimeType(originalTrack.getMimeType());
track.setReference(originalTrack.getReference());
track.setSize(file.length());
track.setURI(originalTrackUrl);
for (String tag : originalTrack.getTags()) {
track.addTag(tag);
}
// enrich the new track with basic info
if (track.getDuration() == null || override)
track.setDuration(metadata.getDuration());
if (track.getChecksum() == null || override) {
try {
track.setChecksum(Checksum.create(ChecksumType.DEFAULT_TYPE, file));
} catch (IOException e) {
throw new MediaInspectionException("Unable to read " + file, e);
}
}
// Add the mime type if it's not already present
if (track.getMimeType() == null || override) {
try {
MimeType mimeType = MimeTypes.fromURI(track.getURI());
// The mimetype library doesn't know about audio/video metadata, so the type might be wrong.
if ("audio".equals(mimeType.getType()) && metadata.hasVideoStreamMetadata()) {
mimeType = MimeTypes.parseMimeType("video/" + mimeType.getSubtype());
} else if ("video".equals(mimeType.getType()) && !metadata.hasVideoStreamMetadata()) {
mimeType = MimeTypes.parseMimeType("audio/" + mimeType.getSubtype());
}
track.setMimeType(mimeType);
} catch (UnknownFileTypeException e) {
logger.info("Unable to detect the mimetype for track {} at {}", track.getIdentifier(), track.getURI());
}
}
// find all streams
Dictionary<String, Stream> streamsId2Stream = new Hashtable<String, Stream>();
for (Stream stream : originalTrack.getStreams()) {
streamsId2Stream.put(stream.getIdentifier(), stream);
}
// audio list
try {
addAudioStreamMetadata(track, metadata);
} catch (Exception e) {
throw new MediaInspectionException("Unable to extract audio metadata from " + file, e);
}
// video list
try {
addVideoStreamMetadata(track, metadata);
} catch (Exception e) {
throw new MediaInspectionException("Unable to extract video metadata from " + file, e);
}
logger.info("Successfully inspected track {}", track);
return track;
}
} catch (Exception e) {
logger.warn("Error enriching track " + originalTrack, e);
if (e instanceof MediaInspectionException) {
throw (MediaInspectionException) e;
} else {
throw new MediaInspectionException(e);
}
}
}
use of org.opencastproject.util.MimeType in project opencast by opencast.
the class AbstractAttachmentBuilderPlugin method accept.
/**
* This implementation of <code>accept</code> tests for the correct node type (attachment).
*
* @see org.opencastproject.mediapackage.elementbuilder.MediaPackageElementBuilderPlugin#accept(org.w3c.dom.Node)
*/
@Override
public boolean accept(Node elementNode) {
try {
// Test for attachment
String nodeName = elementNode.getNodeName();
if (nodeName.contains(":")) {
nodeName = nodeName.substring(nodeName.indexOf(":") + 1);
}
if (!MediaPackageElement.Type.Attachment.toString().equalsIgnoreCase(nodeName))
return false;
// Check flavor
if (this.flavor != null) {
String nodeFlavor = (String) xpath.evaluate("@type", elementNode, XPathConstants.STRING);
if (!flavor.eq(nodeFlavor))
return false;
}
// Check mime type
if (mimeTypes != null && mimeTypes.size() > 0) {
String nodeMimeType = (String) xpath.evaluate("mimetype", elementNode, XPathConstants.STRING);
MimeType mimeType = MimeTypes.parseMimeType(nodeMimeType);
if (!mimeTypes.contains(mimeType))
return false;
}
return true;
} catch (XPathExpressionException e) {
logger.warn("Error while reading attachment flavor from manifest: " + e.getMessage());
return false;
}
}
use of org.opencastproject.util.MimeType in project opencast by opencast.
the class MediaPackageBuilderTest method testLoadPublicationElement.
@Test
public void testLoadPublicationElement() throws Exception {
String fileName = "/publicationElement.xml";
String id = "p-1";
String channel = "engage";
String uri = "http://localhost/engage.html";
MimeType mimeType = MimeTypes.parseMimeType("text/html");
File baseDir = new File(MediaPackageBuilderTest.class.getResource("/").toURI());
File xmlFile = new File(baseDir, fileName);
String xml = IOUtils.toString(new FileInputStream(xmlFile));
Publication pubElement = (Publication) MediaPackageElementParser.getFromXml(xml);
assertNotNull(pubElement);
assertEquals(id, pubElement.getIdentifier());
assertEquals(channel, pubElement.getChannel());
assertEquals(new URI(uri), pubElement.getURI());
assertEquals(mimeType, pubElement.getMimeType());
}
use of org.opencastproject.util.MimeType in project opencast by opencast.
the class ConfigurablePublishWorkflowOperationHandler method start.
@Override
public WorkflowOperationResult start(WorkflowInstance workflowInstance, JobContext context) throws WorkflowOperationException {
RequireUtil.notNull(workflowInstance, "workflowInstance");
final MediaPackage mp = workflowInstance.getMediaPackage();
final WorkflowOperationInstance op = workflowInstance.getCurrentOperation();
final String channelId = StringUtils.trimToEmpty(op.getConfiguration(CHANNEL_ID_KEY));
if ("".equals(channelId)) {
throw new WorkflowOperationException("Unable to publish this mediapackage as the configuration key " + CHANNEL_ID_KEY + " is missing. Unable to determine where to publish these elements.");
}
final String urlPattern = StringUtils.trimToEmpty(op.getConfiguration(URL_PATTERN));
MimeType mimetype = null;
String mimetypeString = StringUtils.trimToEmpty(op.getConfiguration(MIME_TYPE));
if (!"".equals(mimetypeString)) {
try {
mimetype = MimeTypes.parseMimeType(mimetypeString);
} catch (IllegalArgumentException e) {
throw new WorkflowOperationException("Unable to parse the provided configuration for " + MIME_TYPE, e);
}
}
final boolean withPublishedElements = BooleanUtils.toBoolean(StringUtils.trimToEmpty(op.getConfiguration(WITH_PUBLISHED_ELEMENTS)));
boolean checkAvailability = BooleanUtils.toBoolean(StringUtils.trimToEmpty(op.getConfiguration(CHECK_AVAILABILITY)));
if (getPublications(mp, channelId).size() > 0) {
final String rePublishStrategy = StringUtils.trimToEmpty(op.getConfiguration(STRATEGY));
switch(rePublishStrategy) {
case ("fail"):
// fail is a dummy function for further distribution strategies
fail(mp);
break;
case ("merge"):
// nothing to do here. other publication strategies can be added to this list later on
break;
default:
retract(mp, channelId);
}
}
String mode = StringUtils.trimToEmpty(op.getConfiguration(MODE));
if ("".equals(mode)) {
mode = DEFAULT_MODE;
} else if (!ArrayUtils.contains(KNOWN_MODES, mode)) {
logger.error("Unknown value for configuration key mode: '{}'", mode);
throw new IllegalArgumentException("Unknown value for configuration key mode");
}
final String[] sourceFlavors = StringUtils.split(StringUtils.trimToEmpty(op.getConfiguration(SOURCE_FLAVORS)), ",");
final String[] sourceTags = StringUtils.split(StringUtils.trimToEmpty(op.getConfiguration(SOURCE_TAGS)), ",");
String publicationUUID = UUID.randomUUID().toString();
Publication publication = PublicationImpl.publication(publicationUUID, channelId, null, null);
// Configure the element selector
final SimpleElementSelector selector = new SimpleElementSelector();
for (String flavor : sourceFlavors) {
selector.addFlavor(MediaPackageElementFlavor.parseFlavor(flavor));
}
for (String tag : sourceTags) {
selector.addTag(tag);
}
if (sourceFlavors.length > 0 || sourceTags.length > 0) {
if (!withPublishedElements) {
Set<MediaPackageElement> elements = distribute(selector.select(mp, false), mp, channelId, mode, checkAvailability);
if (elements.size() > 0) {
for (MediaPackageElement element : elements) {
// Make sure the mediapackage is prompted to create a new identifier for this element
element.setIdentifier(null);
PublicationImpl.addElementToPublication(publication, element);
}
} else {
logger.info("No element found for distribution in media package '{}'", mp);
return createResult(mp, Action.CONTINUE);
}
} else {
List<MediaPackageElement> publishedElements = new ArrayList<>();
for (Publication alreadyPublished : mp.getPublications()) {
publishedElements.addAll(Arrays.asList(alreadyPublished.getAttachments()));
publishedElements.addAll(Arrays.asList(alreadyPublished.getCatalogs()));
publishedElements.addAll(Arrays.asList(alreadyPublished.getTracks()));
}
for (MediaPackageElement element : selector.select(publishedElements, false)) {
PublicationImpl.addElementToPublication(publication, element);
}
}
}
if (!"".equals(urlPattern)) {
publication.setURI(populateUrlWithVariables(urlPattern, mp, publicationUUID));
}
if (mimetype != null) {
publication.setMimeType(mimetype);
}
mp.add(publication);
return createResult(mp, Action.CONTINUE);
}
use of org.opencastproject.util.MimeType in project opencast by opencast.
the class DublinCoreTest method testClone.
@Test
public void testClone() {
final DublinCoreCatalog dc = DublinCores.mkOpencastEpisode().getCatalog();
final MimeType mimeType = MimeType.mimeType("text", "xml");
dc.setMimeType(MimeType.mimeType("text", "xml"));
dc.setReference(new MediaPackageReferenceImpl("type", "identifier"));
dc.setURI(uri("http://localhost"));
assertNotNull(dc.getMimeType());
assertEquals(mimeType, dc.getMimeType());
// clone
DublinCoreCatalog dcClone = (DublinCoreCatalog) dc.clone();
assertEquals("The mime type should be cloned", dc.getMimeType(), dcClone.getMimeType());
assertEquals("The flavor should be cloned", dc.getFlavor(), dcClone.getFlavor());
assertEquals("The values should be cloned", dc.getValues(), dcClone.getValues());
assertNull("The URI should not be cloned", dcClone.getURI());
assertNull("A media package reference should not be cloned.", dcClone.getReference());
}
Aggregations