Search in sources :

Example 6 with SimpleElementSelector

use of org.opencastproject.mediapackage.selector.SimpleElementSelector in project opencast by opencast.

the class TagByDublinCoreTermWOH 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 currentOperation = workflowInstance.getCurrentOperation();
    String configuredSourceFlavors = StringUtils.trimToEmpty(currentOperation.getConfiguration(SOURCE_FLAVORS_PROPERTY));
    String configuredSourceTags = StringUtils.trimToEmpty(currentOperation.getConfiguration(SOURCE_TAGS_PROPERTY));
    String configuredCatalog = StringUtils.trimToEmpty(currentOperation.getConfiguration(DCCATALOG_PROPERTY));
    String configuredDCTerm = StringUtils.trimToEmpty(currentOperation.getConfiguration(DCTERM_PROPERTY));
    String configuredDefaultValue = StringUtils.trimToNull(currentOperation.getConfiguration(DEFAULT_VALUE_PROPERTY));
    String configuredMatchValue = StringUtils.trimToEmpty(currentOperation.getConfiguration(MATCH_VALUE_PROPERTY));
    String configuredTargetFlavor = StringUtils.trimToNull(currentOperation.getConfiguration(TARGET_FLAVOR_PROPERTY));
    String configuredTargetTags = StringUtils.trimToEmpty(currentOperation.getConfiguration(TARGET_TAGS_PROPERTY));
    boolean copy = BooleanUtils.toBoolean(currentOperation.getConfiguration(COPY_PROPERTY));
    String[] sourceTags = StringUtils.split(configuredSourceTags, ",");
    String[] targetTags = StringUtils.split(configuredTargetTags, ",");
    String[] sourceFlavors = StringUtils.split(configuredSourceFlavors, ",");
    SimpleElementSelector elementSelector = new SimpleElementSelector();
    for (String flavor : sourceFlavors) {
        elementSelector.addFlavor(MediaPackageElementFlavor.parseFlavor(flavor));
    }
    for (String tag : sourceTags) {
        elementSelector.addTag(tag);
    }
    List<String> removeTags = new ArrayList<>();
    List<String> addTags = new ArrayList<>();
    List<String> overrideTags = new ArrayList<>();
    for (String tag : targetTags) {
        if (tag.startsWith(MINUS)) {
            removeTags.add(tag);
        } else if (tag.startsWith(PLUS)) {
            addTags.add(tag);
        } else {
            overrideTags.add(tag);
        }
    }
    // Find Catalog
    Catalog[] catalogs = mediaPackage.getCatalogs(new MediaPackageElementFlavor("dublincore", StringUtils.lowerCase(configuredCatalog)));
    if (catalogs != null && catalogs.length > 0) {
        Boolean foundValue = false;
        EName dcterm = new EName(TERMS_NS_URI, configuredDCTerm);
        // Find DCTerm
        for (Catalog catalog : catalogs) {
            DublinCoreCatalog dc = DublinCoreUtil.loadDublinCore(workspace, catalog);
            // Match Value
            List<DublinCoreValue> values = dc.get(dcterm);
            if (values.isEmpty()) {
                // Use default
                if (configuredDefaultValue != null) {
                    foundValue = configuredDefaultValue.equals(configuredMatchValue);
                }
            } else {
                foundValue = values.contains(DublinCoreValue.mk(configuredMatchValue));
            }
        }
        if (foundValue) {
            if (copy) {
                logger.info("Retagging mediapackage elements as a copy");
            } else {
                logger.info("Retagging mediapackage elements");
            }
            Collection<MediaPackageElement> elements = elementSelector.select(mediaPackage, false);
            for (MediaPackageElement e : elements) {
                MediaPackageElement element = e;
                if (copy) {
                    element = (MediaPackageElement) e.clone();
                    element.setIdentifier(null);
                    // use the same URI as the original
                    element.setURI(e.getURI());
                }
                if (configuredTargetFlavor != null) {
                    element.setFlavor(MediaPackageElementFlavor.parseFlavor(configuredTargetFlavor));
                }
                if (overrideTags.size() > 0) {
                    element.clearTags();
                    for (String tag : overrideTags) {
                        element.addTag(tag);
                    }
                } else {
                    for (String tag : removeTags) {
                        element.removeTag(tag.substring(MINUS.length()));
                    }
                    for (String tag : addTags) {
                        element.addTag(tag.substring(PLUS.length()));
                    }
                }
                if (copy) {
                    mediaPackage.addDerived(element, e);
                }
            }
        }
    // if foundValue
    }
    return createResult(mediaPackage, Action.CONTINUE);
}
Also used : EName(org.opencastproject.mediapackage.EName) DublinCoreValue(org.opencastproject.metadata.dublincore.DublinCoreValue) ArrayList(java.util.ArrayList) SimpleElementSelector(org.opencastproject.mediapackage.selector.SimpleElementSelector) MediaPackageElementFlavor(org.opencastproject.mediapackage.MediaPackageElementFlavor) Catalog(org.opencastproject.mediapackage.Catalog) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog) WorkflowOperationInstance(org.opencastproject.workflow.api.WorkflowOperationInstance) MediaPackageElement(org.opencastproject.mediapackage.MediaPackageElement) MediaPackage(org.opencastproject.mediapackage.MediaPackage) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog)

Example 7 with SimpleElementSelector

use of org.opencastproject.mediapackage.selector.SimpleElementSelector in project opencast by opencast.

the class CleanupWorkflowOperationHandlerTest method testCreanupWOHwithPreservedFlavorAndCollectionPathPrefix.

@Test
public void testCreanupWOHwithPreservedFlavorAndCollectionPathPrefix() throws WorkflowOperationException, MediaPackageException {
    Map<String, String> wfInstConfig = new Hashtable<>();
    wfInstConfig.put(CleanupWorkflowOperationHandler.PRESERVE_FLAVOR_PROPERTY, "*/source,smil/trimmed,security/*");
    wfInstConfig.put(CleanupWorkflowOperationHandler.DELETE_EXTERNAL, "true");
    MediaPackageBuilder mpBuilder = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder();
    MediaPackage mp = mpBuilder.createNew();
    MediaPackageElement track1 = addElementToMediaPackage(mp, MediaPackageElement.Type.Track, "presenter", "source", null);
    track1.setURI(UrlSupport.uri(HOSTNAME_NODE1, WFR_URL_PREFIX, WorkingFileRepository.COLLECTION_PATH_PREFIX, "asset", mp.getIdentifier().compact(), track1.getIdentifier(), "track.mp4"));
    MediaPackageElement track2 = addElementToMediaPackage(mp, MediaPackageElement.Type.Track, "presentation", "work", null);
    track2.setURI(UrlSupport.uri(HOSTNAME_NODE2, WFR_URL_PREFIX, WorkingFileRepository.COLLECTION_PATH_PREFIX, "compose", mp.getIdentifier().compact(), track2.getIdentifier(), "track.mp4"));
    MediaPackageElement att1 = addElementToMediaPackage(mp, MediaPackageElement.Type.Attachment, "presentation", "preview", null);
    att1.setURI(UrlSupport.uri(HOSTNAME_NODE2, WFR_URL_PREFIX, WorkingFileRepository.COLLECTION_PATH_PREFIX, "compose", mp.getIdentifier().compact(), att1.getIdentifier(), "preview.png"));
    MediaPackageElement att2 = addElementToMediaPackage(mp, MediaPackageElement.Type.Attachment, "smil", "trimmed", null);
    att2.setURI(UrlSupport.uri(HOSTNAME_NODE1, WFR_URL_PREFIX, WorkingFileRepository.COLLECTION_PATH_PREFIX, "silence", mp.getIdentifier().compact(), att2.getIdentifier(), "trimmed.smil"));
    MediaPackageElement cat1 = addElementToMediaPackage(mp, MediaPackageElement.Type.Catalog, "dublincore", "episode", null);
    cat1.setURI(UrlSupport.uri(HOSTNAME_NODE1, WFR_URL_PREFIX, WorkingFileRepository.COLLECTION_PATH_PREFIX, "asset", mp.getIdentifier().compact(), cat1.getIdentifier(), "dublincore.xml"));
    MediaPackageElement cat2 = addElementToMediaPackage(mp, MediaPackageElement.Type.Catalog, "security", "xaml", null);
    cat2.setURI(UrlSupport.uri(HOSTNAME_NODE1, WFR_URL_PREFIX, WorkingFileRepository.COLLECTION_PATH_PREFIX, "security", mp.getIdentifier().compact(), cat2.getIdentifier(), "security.xml"));
    cleanupWOH.start(createWorkflowInstance(wfInstConfig, mp), null);
    Assert.assertEquals("Media package should contain at least tree elements", 3, mp.getElements().length);
    SimpleElementSelector elementSelector = new SimpleElementSelector();
    elementSelector.addFlavor("*/source");
    Assert.assertFalse("Media package doesn't contain an element with a preserved flavor '*/source'", elementSelector.select(mp, false).isEmpty());
    elementSelector = new SimpleElementSelector();
    elementSelector.addFlavor("smil/trimmed");
    Assert.assertFalse("Media package doesn't contain an element with a preserved flavor 'smil/trimmed'", elementSelector.select(mp, false).isEmpty());
    elementSelector = new SimpleElementSelector();
    elementSelector.addFlavor("security/*");
    Assert.assertFalse("Media package doesn't contain an element with a preserved flavor 'security/*'", elementSelector.select(mp, false).isEmpty());
    Assert.assertEquals("At least one file wasn't deleted on remote repository", 3, deletedFilesURIs.size());
}
Also used : MediaPackageBuilder(org.opencastproject.mediapackage.MediaPackageBuilder) Hashtable(java.util.Hashtable) MediaPackageElement(org.opencastproject.mediapackage.MediaPackageElement) MediaPackage(org.opencastproject.mediapackage.MediaPackage) SimpleElementSelector(org.opencastproject.mediapackage.selector.SimpleElementSelector) Test(org.junit.Test)

Example 8 with SimpleElementSelector

use of org.opencastproject.mediapackage.selector.SimpleElementSelector in project opencast by opencast.

the class AssetManagerSnapshotWorkflowOperationHandler method getMediaPackageForArchival.

protected MediaPackage getMediaPackageForArchival(MediaPackage current, List<String> tags, String[] sourceFlavors) throws MediaPackageException {
    MediaPackage mp = (MediaPackage) current.clone();
    Collection<MediaPackageElement> keep;
    if (tags.isEmpty() && sourceFlavors.length < 1) {
        keep = new ArrayList<>(Arrays.asList(current.getElementsByTags(tags)));
    } else {
        SimpleElementSelector simpleElementSelector = new SimpleElementSelector();
        for (String flavor : sourceFlavors) {
            simpleElementSelector.addFlavor(flavor);
        }
        for (String tag : tags) {
            simpleElementSelector.addTag(tag);
        }
        keep = simpleElementSelector.select(current, false);
    }
    // Also archive the publication elements
    for (Publication publication : current.getPublications()) {
        keep.add(publication);
    }
    // Mark everything that is set for removal
    List<MediaPackageElement> removals = new ArrayList<MediaPackageElement>();
    for (MediaPackageElement element : mp.getElements()) {
        if (!keep.contains(element)) {
            removals.add(element);
        }
    }
    // Fix references and flavors
    for (MediaPackageElement element : mp.getElements()) {
        if (removals.contains(element))
            continue;
        // Is the element referencing anything?
        MediaPackageReference reference = element.getReference();
        if (reference != null) {
            Map<String, String> referenceProperties = reference.getProperties();
            MediaPackageElement referencedElement = mp.getElementByReference(reference);
            // if we are distributing the referenced element, everything is fine. Otherwise...
            if (referencedElement != null && removals.contains(referencedElement)) {
                // Follow the references until we find a flavor
                MediaPackageElement parent;
                while ((parent = current.getElementByReference(reference)) != null) {
                    if (parent.getFlavor() != null && element.getFlavor() == null) {
                        element.setFlavor(parent.getFlavor());
                    }
                    if (parent.getReference() == null) {
                        break;
                    }
                    reference = parent.getReference();
                }
                // Done. Let's cut the path but keep references to the mediapackage itself
                if (reference != null && reference.getType().equals(MediaPackageReference.TYPE_MEDIAPACKAGE))
                    element.setReference(reference);
                else if (reference != null && (referenceProperties == null || referenceProperties.size() == 0))
                    element.clearReference();
                else {
                    // Ok, there is more to that reference than just pointing at an element. Let's keep the original,
                    // you never know.
                    removals.remove(referencedElement);
                    referencedElement.setURI(null);
                    referencedElement.setChecksum(null);
                }
            }
        }
    }
    // Remove everything we don't want to add to publish
    for (MediaPackageElement element : removals) {
        mp.remove(element);
    }
    return mp;
}
Also used : MediaPackageReference(org.opencastproject.mediapackage.MediaPackageReference) MediaPackageElement(org.opencastproject.mediapackage.MediaPackageElement) MediaPackage(org.opencastproject.mediapackage.MediaPackage) ArrayList(java.util.ArrayList) Publication(org.opencastproject.mediapackage.Publication) SimpleElementSelector(org.opencastproject.mediapackage.selector.SimpleElementSelector)

Example 9 with SimpleElementSelector

use of org.opencastproject.mediapackage.selector.SimpleElementSelector in project opencast by opencast.

the class PublishOaiPmhWorkflowOperationHandler method start.

/**
 * {@inheritDoc}
 *
 * @see org.opencastproject.workflow.api.WorkflowOperationHandler#start(org.opencastproject.workflow.api.WorkflowInstance,
 *      JobContext)
 */
@Override
public WorkflowOperationResult start(final WorkflowInstance workflowInstance, JobContext context) throws WorkflowOperationException {
    logger.debug("Running distribution workflow operation");
    MediaPackage mediaPackage = workflowInstance.getMediaPackage();
    // Check which tags have been configured
    String downloadTags = StringUtils.trimToEmpty(workflowInstance.getCurrentOperation().getConfiguration(DOWNLOAD_TAGS));
    String downloadFlavors = StringUtils.trimToEmpty(workflowInstance.getCurrentOperation().getConfiguration(DOWNLOAD_FLAVORS));
    String streamingTags = StringUtils.trimToEmpty(workflowInstance.getCurrentOperation().getConfiguration(STREAMING_TAGS));
    String streamingFlavors = StringUtils.trimToEmpty(workflowInstance.getCurrentOperation().getConfiguration(STREAMING_FLAVORS));
    boolean checkAvailability = option(workflowInstance.getCurrentOperation().getConfiguration(CHECK_AVAILABILITY)).bind(trimToNone).map(toBool).getOrElse(true);
    String repository = StringUtils.trimToNull(workflowInstance.getCurrentOperation().getConfiguration(REPOSITORY));
    Opt<String> externalChannel = getOptConfig(workflowInstance.getCurrentOperation(), EXTERNAL_CHANNEL_NAME);
    Opt<String> externalTempalte = getOptConfig(workflowInstance.getCurrentOperation(), EXTERNAL_TEMPLATE);
    Opt<MimeType> externalMimetype = getOptConfig(workflowInstance.getCurrentOperation(), EXTERNAL_MIME_TYPE).bind(MimeTypes.toMimeType);
    if (repository == null)
        throw new IllegalArgumentException("No repository has been specified");
    String[] sourceDownloadTags = StringUtils.split(downloadTags, ",");
    String[] sourceDownloadFlavors = StringUtils.split(downloadFlavors, ",");
    String[] sourceStreamingTags = StringUtils.split(streamingTags, ",");
    String[] sourceStreamingFlavors = StringUtils.split(streamingFlavors, ",");
    if (sourceDownloadTags.length == 0 && sourceDownloadFlavors.length == 0 && sourceStreamingTags.length == 0 && sourceStreamingFlavors.length == 0) {
        logger.warn("No tags or flavors have been specified, so nothing will be published to the engage");
        return createResult(mediaPackage, Action.CONTINUE);
    }
    final SimpleElementSelector downloadElementSelector = new SimpleElementSelector();
    for (String flavor : sourceDownloadFlavors) {
        downloadElementSelector.addFlavor(MediaPackageElementFlavor.parseFlavor(flavor));
    }
    for (String tag : sourceDownloadTags) {
        downloadElementSelector.addTag(tag);
    }
    final Collection<MediaPackageElement> downloadElements = downloadElementSelector.select(mediaPackage, false);
    final Collection<MediaPackageElement> streamingElements;
    if (distributeStreaming) {
        final SimpleElementSelector streamingElementSelector = new SimpleElementSelector();
        for (String flavor : sourceStreamingFlavors) {
            streamingElementSelector.addFlavor(MediaPackageElementFlavor.parseFlavor(flavor));
        }
        for (String tag : sourceStreamingTags) {
            streamingElementSelector.addTag(tag);
        }
        streamingElements = streamingElementSelector.select(mediaPackage, false);
    } else {
        streamingElements = list();
    }
    try {
        Set<String> downloadElementIds = new HashSet<>();
        Set<String> streamingElementIds = new HashSet<>();
        // Look for elements matching the tag
        for (MediaPackageElement elem : downloadElements) {
            downloadElementIds.add(elem.getIdentifier());
        }
        for (MediaPackageElement elem : streamingElements) {
            streamingElementIds.add(elem.getIdentifier());
        }
        // Also distribute the security configuration
        // -----
        // This was removed in the meantime by a fix for MH-8515, but could now be used again.
        // -----
        Attachment[] securityAttachments = mediaPackage.getAttachments(MediaPackageElements.XACML_POLICY);
        if (securityAttachments != null && securityAttachments.length > 0) {
            for (Attachment a : securityAttachments) {
                downloadElementIds.add(a.getIdentifier());
                streamingElementIds.add(a.getIdentifier());
            }
        }
        Job publishJob = null;
        try {
            publishJob = publicationService.publish(mediaPackage, repository, downloadElementIds, streamingElementIds, checkAvailability);
        } catch (MediaPackageException e) {
            throw new WorkflowOperationException("Error parsing media package", e);
        } catch (PublicationException e) {
            throw new WorkflowOperationException("Error parsing media package", e);
        }
        // Wait until the publication job has returned
        if (!waitForStatus(publishJob).isSuccess())
            throw new WorkflowOperationException("Mediapackage " + mediaPackage.getIdentifier() + " could not be published to OAI-PMH repository " + repository);
        // The job has passed
        Job job = serviceRegistry.getJob(publishJob.getId());
        // If there is no payload, then the item has not been published.
        if (job.getPayload() == null) {
            logger.warn("Publish to OAI-PMH repository '{}' failed, no payload from publication job: {}", repository, job);
            return createResult(mediaPackage, Action.CONTINUE);
        }
        Publication newElement = null;
        try {
            newElement = (Publication) MediaPackageElementParser.getFromXml(job.getPayload());
        } catch (MediaPackageException e) {
            throw new WorkflowOperationException(e);
        }
        if (newElement == null) {
            logger.warn("Publication to OAI-PMH repository '{}' failed, unable to parse the payload '{}' from job '{}' to a mediapackage element", repository, job.getPayload(), job.toString());
            return createResult(mediaPackage, Action.CONTINUE);
        }
        for (Publication existingPublication : $(mediaPackage.getPublications()).find(ofChannel(newElement.getChannel()).toFn())) {
            mediaPackage.remove(existingPublication);
        }
        mediaPackage.add(newElement);
        if (externalChannel.isSome() && externalMimetype.isSome() && externalTempalte.isSome()) {
            String template = externalTempalte.get().replace("{event}", mediaPackage.getIdentifier().compact());
            if (StringUtils.isNotBlank(mediaPackage.getSeries()))
                template = template.replace("{series}", mediaPackage.getSeries());
            Publication externalElement = PublicationImpl.publication(UUID.randomUUID().toString(), externalChannel.get(), URI.create(template), externalMimetype.get());
            for (Publication existingPublication : $(mediaPackage.getPublications()).find(ofChannel(externalChannel.get()).toFn())) {
                mediaPackage.remove(existingPublication);
            }
            mediaPackage.add(externalElement);
        }
        logger.debug("Publication to OAI-PMH repository '{}' operation completed", repository);
    } catch (Exception e) {
        if (e instanceof WorkflowOperationException) {
            throw (WorkflowOperationException) e;
        } else {
            throw new WorkflowOperationException(e);
        }
    }
    return createResult(mediaPackage, Action.CONTINUE);
}
Also used : MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) PublicationException(org.opencastproject.publication.api.PublicationException) Publication(org.opencastproject.mediapackage.Publication) Attachment(org.opencastproject.mediapackage.Attachment) SimpleElementSelector(org.opencastproject.mediapackage.selector.SimpleElementSelector) MimeType(org.opencastproject.util.MimeType) PublicationException(org.opencastproject.publication.api.PublicationException) WorkflowOperationException(org.opencastproject.workflow.api.WorkflowOperationException) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) MediaPackageElement(org.opencastproject.mediapackage.MediaPackageElement) MediaPackage(org.opencastproject.mediapackage.MediaPackage) WorkflowOperationException(org.opencastproject.workflow.api.WorkflowOperationException) Job(org.opencastproject.job.api.Job) HashSet(java.util.HashSet)

Example 10 with SimpleElementSelector

use of org.opencastproject.mediapackage.selector.SimpleElementSelector in project opencast by opencast.

the class PublishEngageWorkflowOperationHandler method start.

/**
 * {@inheritDoc}
 *
 * @see org.opencastproject.workflow.api.WorkflowOperationHandler#start(org.opencastproject.workflow.api.WorkflowInstance,
 *      JobContext)
 */
@Override
public WorkflowOperationResult start(final WorkflowInstance workflowInstance, JobContext context) throws WorkflowOperationException {
    logger.debug("Running engage publication workflow operation");
    MediaPackage mediaPackage = workflowInstance.getMediaPackage();
    WorkflowOperationInstance op = workflowInstance.getCurrentOperation();
    // Check which tags have been configured
    String downloadSourceTags = StringUtils.trimToEmpty(op.getConfiguration(DOWNLOAD_SOURCE_TAGS));
    String downloadTargetTags = StringUtils.trimToEmpty(op.getConfiguration(DOWNLOAD_TARGET_TAGS));
    String downloadSourceFlavors = StringUtils.trimToEmpty(op.getConfiguration(DOWNLOAD_SOURCE_FLAVORS));
    String downloadTargetSubflavor = StringUtils.trimToNull(op.getConfiguration(DOWNLOAD_TARGET_SUBFLAVOR));
    String streamingSourceTags = StringUtils.trimToEmpty(op.getConfiguration(STREAMING_SOURCE_TAGS));
    String streamingTargetTags = StringUtils.trimToEmpty(op.getConfiguration(STREAMING_TARGET_TAGS));
    String streamingSourceFlavors = StringUtils.trimToEmpty(op.getConfiguration(STREAMING_SOURCE_FLAVORS));
    String streamingTargetSubflavor = StringUtils.trimToNull(op.getConfiguration(STREAMING_TARGET_SUBFLAVOR));
    String republishStrategy = StringUtils.trimToEmpty(op.getConfiguration(STRATEGY));
    boolean checkAvailability = option(op.getConfiguration(CHECK_AVAILABILITY)).bind(trimToNone).map(toBool).getOrElse(true);
    String[] sourceDownloadTags = StringUtils.split(downloadSourceTags, ",");
    String[] targetDownloadTags = StringUtils.split(downloadTargetTags, ",");
    String[] sourceDownloadFlavors = StringUtils.split(downloadSourceFlavors, ",");
    String[] sourceStreamingTags = StringUtils.split(streamingSourceTags, ",");
    String[] targetStreamingTags = StringUtils.split(streamingTargetTags, ",");
    String[] sourceStreamingFlavors = StringUtils.split(streamingSourceFlavors, ",");
    if (sourceDownloadTags.length == 0 && sourceDownloadFlavors.length == 0 && sourceStreamingTags.length == 0 && sourceStreamingFlavors.length == 0) {
        logger.warn("No tags or flavors have been specified, so nothing will be published to the engage publication channel");
        return createResult(mediaPackage, Action.CONTINUE);
    }
    // Parse the download target flavor
    MediaPackageElementFlavor downloadSubflavor = null;
    if (downloadTargetSubflavor != null) {
        try {
            downloadSubflavor = MediaPackageElementFlavor.parseFlavor(downloadTargetSubflavor);
        } catch (IllegalArgumentException e) {
            throw new WorkflowOperationException(e);
        }
    }
    // Parse the streaming target flavor
    MediaPackageElementFlavor streamingSubflavor = null;
    if (streamingTargetSubflavor != null) {
        try {
            streamingSubflavor = MediaPackageElementFlavor.parseFlavor(streamingTargetSubflavor);
        } catch (IllegalArgumentException e) {
            throw new WorkflowOperationException(e);
        }
    }
    // Configure the download element selector
    SimpleElementSelector downloadElementSelector = new SimpleElementSelector();
    for (String flavor : sourceDownloadFlavors) {
        downloadElementSelector.addFlavor(MediaPackageElementFlavor.parseFlavor(flavor));
    }
    for (String tag : sourceDownloadTags) {
        downloadElementSelector.addTag(tag);
    }
    // Configure the streaming element selector
    SimpleElementSelector streamingElementSelector = new SimpleElementSelector();
    for (String flavor : sourceStreamingFlavors) {
        streamingElementSelector.addFlavor(MediaPackageElementFlavor.parseFlavor(flavor));
    }
    for (String tag : sourceStreamingTags) {
        streamingElementSelector.addTag(tag);
    }
    // Select the appropriate elements for download and streaming
    Collection<MediaPackageElement> downloadElements = downloadElementSelector.select(mediaPackage, false);
    Collection<MediaPackageElement> streamingElements = streamingElementSelector.select(mediaPackage, false);
    try {
        Set<String> downloadElementIds = new HashSet<String>();
        Set<String> streamingElementIds = new HashSet<String>();
        // Look for elements matching the tag
        for (MediaPackageElement elem : downloadElements) {
            downloadElementIds.add(elem.getIdentifier());
        }
        for (MediaPackageElement elem : streamingElements) {
            streamingElementIds.add(elem.getIdentifier());
        }
        // Also distribute the security configuration
        // -----
        // This was removed in the meantime by a fix for MH-8515, but could now be used again.
        // -----
        Attachment[] securityAttachments = mediaPackage.getAttachments(MediaPackageElements.XACML_POLICY);
        if (securityAttachments != null && securityAttachments.length > 0) {
            for (Attachment a : securityAttachments) {
                downloadElementIds.add(a.getIdentifier());
                streamingElementIds.add(a.getIdentifier());
            }
        }
        removePublicationElement(mediaPackage);
        switch(republishStrategy) {
            case ("merge"):
                // nothing to do here. other publication strategies can be added to this list later on
                break;
            default:
                retractFromEngage(mediaPackage);
        }
        List<Job> jobs = new ArrayList<Job>();
        // distribute Elements
        try {
            if (downloadElementIds.size() > 0) {
                Job job = downloadDistributionService.distribute(CHANNEL_ID, mediaPackage, downloadElementIds, checkAvailability);
                if (job != null) {
                    jobs.add(job);
                }
            }
            if (distributeStreaming) {
                for (String elementId : streamingElementIds) {
                    Job job = streamingDistributionService.distribute(CHANNEL_ID, mediaPackage, elementId);
                    if (job != null) {
                        jobs.add(job);
                    }
                }
            }
        } catch (DistributionException e) {
            throw new WorkflowOperationException(e);
        }
        if (jobs.size() < 1) {
            logger.info("No mediapackage element was found for distribution to engage");
            return createResult(mediaPackage, Action.CONTINUE);
        }
        // Wait until all distribution jobs have returned
        if (!waitForStatus(jobs.toArray(new Job[jobs.size()])).isSuccess())
            throw new WorkflowOperationException("One of the distribution jobs did not complete successfully");
        logger.debug("Distribute of mediapackage {} completed", mediaPackage);
        String engageUrlString = null;
        try {
            MediaPackage mediaPackageForSearch = getMediaPackageForSearchIndex(mediaPackage, jobs, downloadSubflavor, targetDownloadTags, downloadElementIds, streamingSubflavor, streamingElementIds, targetStreamingTags);
            // MH-10216, check if only merging into existing mediapackage
            removePublicationElement(mediaPackage);
            switch(republishStrategy) {
                case ("merge"):
                    // merge() returns merged mediapackage or null mediaPackage is not published
                    mediaPackageForSearch = merge(mediaPackageForSearch);
                    if (mediaPackageForSearch == null) {
                        logger.info("Skipping republish for {} since it is not currently published", mediaPackage.getIdentifier().toString());
                        return createResult(mediaPackage, Action.SKIP);
                    }
                    break;
                default:
            }
            if (!isPublishable(mediaPackageForSearch))
                throw new WorkflowOperationException("Media package does not meet criteria for publication");
            logger.info("Publishing media package {} to search index", mediaPackageForSearch);
            URL engageBaseUrl = null;
            engageUrlString = StringUtils.trimToNull(workflowInstance.getOrganization().getProperties().get(ENGAGE_URL_PROPERTY));
            if (engageUrlString != null) {
                engageBaseUrl = new URL(engageUrlString);
            } else {
                engageBaseUrl = serverUrl;
                logger.info("Using 'server.url' as a fallback for the non-existing organization level key '{}' for the publication url", ENGAGE_URL_PROPERTY);
            }
            // create the publication URI (used by Admin UI for event details link)
            URI engageUri = this.createEngageUri(engageBaseUrl.toURI(), mediaPackage);
            // Create new distribution element
            Publication publicationElement = PublicationImpl.publication(UUID.randomUUID().toString(), CHANNEL_ID, engageUri, MimeTypes.parseMimeType("text/html"));
            mediaPackage.add(publicationElement);
            // Adding media package to the search index
            Job publishJob = null;
            try {
                publishJob = searchService.add(mediaPackageForSearch);
                if (!waitForStatus(publishJob).isSuccess()) {
                    throw new WorkflowOperationException("Mediapackage " + mediaPackageForSearch.getIdentifier() + " could not be published");
                }
            } catch (SearchException e) {
                throw new WorkflowOperationException("Error publishing media package", e);
            } catch (MediaPackageException e) {
                throw new WorkflowOperationException("Error parsing media package", e);
            }
            logger.debug("Publishing of mediapackage {} completed", mediaPackage);
            return createResult(mediaPackage, Action.CONTINUE);
        } catch (MalformedURLException e) {
            logger.error("{} is malformed: {}", ENGAGE_URL_PROPERTY, engageUrlString);
            throw new WorkflowOperationException(e);
        } catch (Throwable t) {
            if (t instanceof WorkflowOperationException)
                throw (WorkflowOperationException) t;
            else
                throw new WorkflowOperationException(t);
        }
    } catch (Exception e) {
        if (e instanceof WorkflowOperationException) {
            throw (WorkflowOperationException) e;
        } else {
            throw new WorkflowOperationException(e);
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) ArrayList(java.util.ArrayList) SearchException(org.opencastproject.search.api.SearchException) Attachment(org.opencastproject.mediapackage.Attachment) SimpleElementSelector(org.opencastproject.mediapackage.selector.SimpleElementSelector) URI(java.net.URI) URL(java.net.URL) WorkflowOperationInstance(org.opencastproject.workflow.api.WorkflowOperationInstance) MediaPackageElement(org.opencastproject.mediapackage.MediaPackageElement) WorkflowOperationException(org.opencastproject.workflow.api.WorkflowOperationException) Job(org.opencastproject.job.api.Job) HashSet(java.util.HashSet) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) Publication(org.opencastproject.mediapackage.Publication) MediaPackageElementFlavor(org.opencastproject.mediapackage.MediaPackageElementFlavor) ServiceRegistryException(org.opencastproject.serviceregistry.api.ServiceRegistryException) WorkflowOperationException(org.opencastproject.workflow.api.WorkflowOperationException) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) DistributionException(org.opencastproject.distribution.api.DistributionException) SearchException(org.opencastproject.search.api.SearchException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) MalformedURLException(java.net.MalformedURLException) MediaPackage(org.opencastproject.mediapackage.MediaPackage) DistributionException(org.opencastproject.distribution.api.DistributionException)

Aggregations

SimpleElementSelector (org.opencastproject.mediapackage.selector.SimpleElementSelector)16 MediaPackage (org.opencastproject.mediapackage.MediaPackage)15 MediaPackageElement (org.opencastproject.mediapackage.MediaPackageElement)15 WorkflowOperationInstance (org.opencastproject.workflow.api.WorkflowOperationInstance)8 ArrayList (java.util.ArrayList)7 Publication (org.opencastproject.mediapackage.Publication)7 WorkflowOperationException (org.opencastproject.workflow.api.WorkflowOperationException)7 MediaPackageElementFlavor (org.opencastproject.mediapackage.MediaPackageElementFlavor)5 Job (org.opencastproject.job.api.Job)4 MediaPackageException (org.opencastproject.mediapackage.MediaPackageException)4 URI (java.net.URI)3 HashSet (java.util.HashSet)3 MalformedURLException (java.net.MalformedURLException)2 Hashtable (java.util.Hashtable)2 Test (org.junit.Test)2 Attachment (org.opencastproject.mediapackage.Attachment)2 Catalog (org.opencastproject.mediapackage.Catalog)2 MediaPackageBuilder (org.opencastproject.mediapackage.MediaPackageBuilder)2 MediaPackageReference (org.opencastproject.mediapackage.MediaPackageReference)2 Track (org.opencastproject.mediapackage.Track)2