Search in sources :

Example 21 with Publication

use of org.opencastproject.mediapackage.Publication in project opencast by opencast.

the class YouTubeV3PublicationServiceImpl method process.

/**
 * {@inheritDoc}
 *
 * @see org.opencastproject.job.api.AbstractJobProducer#process(org.opencastproject.job.api.Job)
 */
@Override
protected String process(final Job job) throws Exception {
    Operation op = null;
    try {
        op = Operation.valueOf(job.getOperation());
        List<String> arguments = job.getArguments();
        MediaPackage mediapackage = MediaPackageParser.getFromXml(arguments.get(0));
        switch(op) {
            case Publish:
                Publication publicationElement = publish(job, mediapackage, arguments.get(1));
                return (publicationElement == null) ? null : MediaPackageElementParser.getAsXml(publicationElement);
            case Retract:
                Publication retractedElement = retract(job, mediapackage);
                return (retractedElement == null) ? null : MediaPackageElementParser.getAsXml(retractedElement);
            default:
                throw new IllegalStateException("Don't know how to handle operation '" + job.getOperation() + "'");
        }
    } catch (final IllegalArgumentException e) {
        throw new ServiceRegistryException("This service can't handle operations of type '" + op + "'", e);
    } catch (final IndexOutOfBoundsException e) {
        throw new ServiceRegistryException("This argument list for operation '" + op + "' does not meet expectations", e);
    } catch (final Exception e) {
        throw new ServiceRegistryException("Error handling operation '" + op + "'", e);
    }
}
Also used : MediaPackage(org.opencastproject.mediapackage.MediaPackage) Publication(org.opencastproject.mediapackage.Publication) ServiceRegistryException(org.opencastproject.serviceregistry.api.ServiceRegistryException) PublicationException(org.opencastproject.publication.api.PublicationException) ConfigurationException(org.osgi.service.cm.ConfigurationException) ServiceRegistryException(org.opencastproject.serviceregistry.api.ServiceRegistryException)

Example 22 with Publication

use of org.opencastproject.mediapackage.Publication in project opencast by opencast.

the class DuplicateEventWorkflowOperationHandler method start.

@Override
public WorkflowOperationResult start(final WorkflowInstance workflowInstance, final JobContext context) throws WorkflowOperationException {
    final MediaPackage mediaPackage = workflowInstance.getMediaPackage();
    final WorkflowOperationInstance operation = workflowInstance.getCurrentOperation();
    final String configuredSourceFlavors = trimToEmpty(operation.getConfiguration(SOURCE_FLAVORS_PROPERTY));
    final String configuredSourceTags = trimToEmpty(operation.getConfiguration(SOURCE_TAGS_PROPERTY));
    final String configuredTargetTags = trimToEmpty(operation.getConfiguration(TARGET_TAGS_PROPERTY));
    final int numberOfEvents = Integer.parseInt(operation.getConfiguration(NUMBER_PROPERTY));
    final String configuredPropertyNamespaces = trimToEmpty(operation.getConfiguration(PROPERTY_NAMESPACES_PROPERTY));
    int maxNumberOfEvents = MAX_NUMBER_DEFAULT;
    if (operation.getConfiguration(MAX_NUMBER_PROPERTY) != null) {
        maxNumberOfEvents = Integer.parseInt(operation.getConfiguration(MAX_NUMBER_PROPERTY));
    }
    if (numberOfEvents > maxNumberOfEvents) {
        throw new WorkflowOperationException("Number of events to create exceeds the maximum of " + maxNumberOfEvents + ". Aborting.");
    }
    logger.info("Creating {} new media packages from media package with id {}.", numberOfEvents, mediaPackage.getIdentifier());
    final String[] sourceTags = split(configuredSourceTags, ",");
    final String[] targetTags = split(configuredTargetTags, ",");
    final String[] sourceFlavors = split(configuredSourceFlavors, ",");
    final String[] propertyNamespaces = split(configuredPropertyNamespaces, ",");
    final String copyNumberPrefix = trimToEmpty(operation.getConfiguration(COPY_NUMBER_PREFIX_PROPERTY));
    final SimpleElementSelector elementSelector = new SimpleElementSelector();
    for (String flavor : sourceFlavors) {
        elementSelector.addFlavor(MediaPackageElementFlavor.parseFlavor(flavor));
    }
    final List<String> removeTags = new ArrayList<>();
    final List<String> addTags = new ArrayList<>();
    final 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);
        }
    }
    for (String tag : sourceTags) {
        elementSelector.addTag(tag);
    }
    // Filter elements to copy based on input tags and input flavors
    final Collection<MediaPackageElement> elements = elementSelector.select(mediaPackage, false);
    final Collection<Publication> internalPublications = new HashSet<>();
    for (MediaPackageElement e : mediaPackage.getElements()) {
        if (e instanceof Publication && InternalPublicationChannel.CHANNEL_ID.equals(((Publication) e).getChannel())) {
            internalPublications.add((Publication) e);
        }
        if (MediaPackageElements.EPISODE.equals(e.getFlavor())) {
            // Remove episode DC since we will add a new one (with changed title)
            elements.remove(e);
        }
    }
    final MediaPackageElement[] originalEpisodeDc = mediaPackage.getElementsByFlavor(MediaPackageElements.EPISODE);
    if (originalEpisodeDc.length != 1) {
        throw new WorkflowOperationException("Media package " + mediaPackage.getIdentifier() + " has " + originalEpisodeDc.length + " episode dublin cores while it is expected to have exactly 1. Aborting.");
    }
    for (int i = 0; i < numberOfEvents; i++) {
        final List<URI> temporaryFiles = new ArrayList<>();
        MediaPackage newMp = null;
        try {
            // Clone the media package (without its elements)
            newMp = copyMediaPackage(mediaPackage, i + 1, copyNumberPrefix);
            // Create and add new episode dublin core with changed title
            newMp = copyDublinCore(mediaPackage, originalEpisodeDc[0], newMp, removeTags, addTags, overrideTags, temporaryFiles);
            // Clone regular elements
            for (final MediaPackageElement e : elements) {
                final MediaPackageElement element = (MediaPackageElement) e.clone();
                updateTags(element, removeTags, addTags, overrideTags);
                newMp.add(element);
            }
            // Clone internal publications
            for (final Publication originalPub : internalPublications) {
                copyPublication(originalPub, mediaPackage, newMp, removeTags, addTags, overrideTags, temporaryFiles);
            }
            assetManager.takeSnapshot(AssetManager.DEFAULT_OWNER, newMp);
            // Clone properties of media package
            for (String namespace : propertyNamespaces) {
                copyProperties(namespace, mediaPackage, newMp);
            }
        } finally {
            cleanup(temporaryFiles, Optional.ofNullable(newMp));
        }
    }
    return createResult(mediaPackage, Action.CONTINUE);
}
Also used : ArrayList(java.util.ArrayList) Publication(org.opencastproject.mediapackage.Publication) SimpleElementSelector(org.opencastproject.mediapackage.selector.SimpleElementSelector) URI(java.net.URI) WorkflowOperationInstance(org.opencastproject.workflow.api.WorkflowOperationInstance) MediaPackageElement(org.opencastproject.mediapackage.MediaPackageElement) MediaPackage(org.opencastproject.mediapackage.MediaPackage) WorkflowOperationException(org.opencastproject.workflow.api.WorkflowOperationException) HashSet(java.util.HashSet)

Example 23 with Publication

use of org.opencastproject.mediapackage.Publication 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 24 with Publication

use of org.opencastproject.mediapackage.Publication in project opencast by opencast.

the class EventsEndpoint method eventToJSON.

/**
 * Transform an {@link Event} to Json
 *
 * @param event
 *          The event to transform into json
 * @param withAcl
 *          Whether to add the acl information for the event
 * @param withMetadata
 *          Whether to add all the metadata for the event
 * @param withPublications
 *          Whether to add the publications
 * @param withSignedUrls
 *          Whether to sign the urls if they are protected by stream security.
 * @return The event in json format.
 * @throws IndexServiceException
 *           Thrown if unable to get the metadata for the event.
 * @throws SearchIndexException
 *           Thrown if unable to get event publications from search service
 * @throws NotFoundException
 *           Thrown if unable to find all of the metadata
 */
protected JValue eventToJSON(Event event, Boolean withAcl, Boolean withMetadata, Boolean withPublications, Boolean withSignedUrls) throws IndexServiceException, SearchIndexException, NotFoundException {
    List<Field> fields = new ArrayList<>();
    if (event.getArchiveVersion() != null)
        fields.add(f("archive_version", v(event.getArchiveVersion())));
    fields.add(f("created", v(event.getCreated(), Jsons.BLANK)));
    fields.add(f("creator", v(event.getCreator(), Jsons.BLANK)));
    fields.add(f("contributor", arr($(event.getContributors()).map(Functions.stringToJValue))));
    fields.add(f("description", v(event.getDescription(), Jsons.BLANK)));
    fields.add(f("has_previews", v(event.hasPreview())));
    fields.add(f("identifier", v(event.getIdentifier(), BLANK)));
    fields.add(f("location", v(event.getLocation(), BLANK)));
    fields.add(f("presenter", arr($(event.getPresenters()).map(Functions.stringToJValue))));
    List<JValue> publicationIds = new ArrayList<>();
    if (event.getPublications() != null) {
        for (Publication publication : event.getPublications()) {
            publicationIds.add(v(publication.getChannel()));
        }
    }
    fields.add(f("publication_status", arr(publicationIds)));
    fields.add(f("processing_state", v(event.getWorkflowState(), BLANK)));
    fields.add(f("start", v(event.getTechnicalStartTime(), BLANK)));
    if (event.getTechnicalEndTime() != null) {
        long duration = new DateTime(event.getTechnicalEndTime()).getMillis() - new DateTime(event.getTechnicalStartTime()).getMillis();
        fields.add(f("duration", v(duration)));
    }
    if (StringUtils.trimToNull(event.getSubject()) != null) {
        fields.add(f("subjects", arr(splitSubjectIntoArray(event.getSubject()))));
    } else {
        fields.add(f("subjects", arr()));
    }
    fields.add(f("title", v(event.getTitle(), BLANK)));
    if (withAcl != null && withAcl) {
        AccessControlList acl = getAclFromEvent(event);
        fields.add(f("acl", arr(AclUtils.serializeAclToJson(acl))));
    }
    if (withMetadata != null && withMetadata) {
        try {
            Opt<MetadataList> metadata = getEventMetadata(event);
            if (metadata.isSome()) {
                fields.add(f("metadata", metadata.get().toJSON()));
            }
        } catch (Exception e) {
            logger.error("Unable to get metadata for event '{}' because: {}", event.getIdentifier(), ExceptionUtils.getStackTrace(e));
            throw new IndexServiceException("Unable to add metadata to event", e);
        }
    }
    if (withPublications != null && withPublications) {
        List<JValue> publications = getPublications(event, withSignedUrls);
        fields.add(f("publications", arr(publications)));
    }
    return obj(fields);
}
Also used : AccessControlList(org.opencastproject.security.api.AccessControlList) ArrayList(java.util.ArrayList) Publication(org.opencastproject.mediapackage.Publication) DateTime(org.joda.time.DateTime) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) IngestException(org.opencastproject.ingest.api.IngestException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) ConfigurationException(org.osgi.service.cm.ConfigurationException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) ParseException(org.json.simple.parser.ParseException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) MetadataList(org.opencastproject.index.service.catalog.adapter.MetadataList) Field(com.entwinemedia.fn.data.json.Field) MetadataField(org.opencastproject.metadata.dublincore.MetadataField) JValue(com.entwinemedia.fn.data.json.JValue) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException)

Example 25 with Publication

use of org.opencastproject.mediapackage.Publication in project opencast by opencast.

the class TestEventEndpoint method createEvent.

private Event createEvent(String id, String title, Source source) throws URISyntaxException {
    Event event = EasyMock.createNiceMock(Event.class);
    EasyMock.expect(event.getIdentifier()).andReturn(id).anyTimes();
    EasyMock.expect(event.getTitle()).andReturn(title).anyTimes();
    EasyMock.expect(event.getSeriesId()).andReturn("seriesId").anyTimes();
    EasyMock.expect(event.getReviewStatus()).andReturn(ReviewStatus.UNSENT.toString()).anyTimes();
    EasyMock.expect(event.getEventStatus()).andReturn("EVENTS.EVENTS.STATUS.ARCHIVE").anyTimes();
    EasyMock.expect(event.getOptedOut()).andReturn(true).anyTimes();
    EasyMock.expect(event.getRecordingStartDate()).andReturn("2013-03-20T04:00:00Z").anyTimes();
    EasyMock.expect(event.getRecordingEndDate()).andReturn("2013-03-20T05:00:00Z").anyTimes();
    EasyMock.expect(event.getTechnicalStartTime()).andReturn("2013-03-20T04:00:00Z").anyTimes();
    EasyMock.expect(event.getTechnicalEndTime()).andReturn("2013-03-20T05:00:00Z").anyTimes();
    EasyMock.expect(event.getWorkflowState()).andReturn(WorkflowInstance.WorkflowState.SUCCEEDED.name()).anyTimes();
    List<Publication> publist = new ArrayList<>();
    publist.add(new PublicationImpl("engage", "rest", new URI("engage.html?e=p-1"), MimeType.mimeType("text", "xml")));
    EasyMock.expect(event.getPublications()).andReturn(publist).anyTimes();
    EasyMock.expect(event.getAccessPolicy()).andReturn("{\"acl\":{\"ace\":[{\"allow\":true,\"action\":\"read\",\"role\":\"ROLE_ADMIN\"},{\"allow\":true,\"action\":\"write\",\"role\":\"ROLE_ADMIN\"}]}}\"").anyTimes();
    EasyMock.expect(event.hasRecordingStarted()).andReturn(true);
    // Simulate different event sources
    switch(source) {
        case ARCHIVE:
            EasyMock.expect(event.getArchiveVersion()).andReturn(1000L).anyTimes();
            break;
        case SCHEDULE:
            EasyMock.expect(event.getWorkflowId()).andReturn(1000L).anyTimes();
            break;
        default:
    }
    EasyMock.replay(event);
    return event;
}
Also used : PublicationImpl(org.opencastproject.mediapackage.PublicationImpl) ArrayList(java.util.ArrayList) Event(org.opencastproject.index.service.impl.index.event.Event) Publication(org.opencastproject.mediapackage.Publication) URI(java.net.URI)

Aggregations

Publication (org.opencastproject.mediapackage.Publication)37 MediaPackage (org.opencastproject.mediapackage.MediaPackage)21 ArrayList (java.util.ArrayList)17 MediaPackageElement (org.opencastproject.mediapackage.MediaPackageElement)15 Job (org.opencastproject.job.api.Job)12 URI (java.net.URI)11 WorkflowOperationException (org.opencastproject.workflow.api.WorkflowOperationException)9 HashSet (java.util.HashSet)8 SimpleElementSelector (org.opencastproject.mediapackage.selector.SimpleElementSelector)7 PublicationException (org.opencastproject.publication.api.PublicationException)7 Test (org.junit.Test)6 MediaPackageException (org.opencastproject.mediapackage.MediaPackageException)5 Ignore (org.junit.Ignore)4 DistributionException (org.opencastproject.distribution.api.DistributionException)4 Attachment (org.opencastproject.mediapackage.Attachment)4 MediaPackageElementFlavor (org.opencastproject.mediapackage.MediaPackageElementFlavor)4 PublicationImpl (org.opencastproject.mediapackage.PublicationImpl)4 Track (org.opencastproject.mediapackage.Track)4 NotFoundException (org.opencastproject.util.NotFoundException)4 Event (org.opencastproject.index.service.impl.index.event.Event)3