Search in sources :

Example 16 with ServiceRegistryException

use of org.opencastproject.serviceregistry.api.ServiceRegistryException in project opencast by opencast.

the class ServiceRegistryJpaImpl method createJob.

/**
 * Creates a job on a remote host.
 */
public Job createJob(String host, String serviceType, String operation, List<String> arguments, String payload, boolean dispatchable, Job parentJob, float jobLoad) throws ServiceRegistryException {
    if (StringUtils.isBlank(host)) {
        throw new IllegalArgumentException("Host can't be null");
    }
    if (StringUtils.isBlank(serviceType)) {
        throw new IllegalArgumentException("Service type can't be null");
    }
    if (StringUtils.isBlank(operation)) {
        throw new IllegalArgumentException("Operation can't be null");
    }
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        ServiceRegistrationJpaImpl creatingService = getServiceRegistration(em, serviceType, host);
        if (creatingService == null) {
            throw new ServiceRegistryException("No service registration exists for type '" + serviceType + "' on host '" + host + "'");
        }
        if (creatingService.getHostRegistration().isMaintenanceMode()) {
            logger.warn("Creating a job from {}, which is currently in maintenance mode.", creatingService.getHost());
        } else if (!creatingService.getHostRegistration().isActive()) {
            logger.warn("Creating a job from {}, which is currently inactive.", creatingService.getHost());
        }
        User currentUser = securityService.getUser();
        Organization currentOrganization = securityService.getOrganization();
        JpaJob jpaJob = new JpaJob(currentUser, currentOrganization, creatingService, operation, arguments, payload, dispatchable, jobLoad);
        // Bind the given parent job to the new job
        if (parentJob != null) {
            // Get the JPA instance of the parent job
            JpaJob jpaParentJob;
            try {
                jpaParentJob = getJpaJob(parentJob.getId());
            } catch (NotFoundException e) {
                logger.error("{} not found in the persistence context", parentJob);
                throw new ServiceRegistryException(e);
            }
            jpaJob.setParentJob(jpaParentJob);
            // Get the JPA instance of the root job
            JpaJob jpaRootJob = jpaParentJob;
            if (parentJob.getRootJobId() != null) {
                try {
                    jpaRootJob = getJpaJob(parentJob.getRootJobId());
                } catch (NotFoundException e) {
                    logger.error("job with id {} not found in the persistence context", parentJob.getRootJobId());
                    throw new ServiceRegistryException(e);
                }
            }
            jpaJob.setRootJob(jpaRootJob);
        }
        // if this job is not dispatchable, it must be handled by the host that has created it
        if (dispatchable) {
            jpaJob.setStatus(Status.QUEUED);
        } else {
            jpaJob.setProcessorServiceRegistration(creatingService);
        }
        em.persist(jpaJob);
        tx.commit();
        setJobUri(jpaJob);
        Job job = jpaJob.toJob();
        return job;
    } catch (RollbackException e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        throw e;
    } finally {
        if (em != null)
            em.close();
    }
}
Also used : EntityTransaction(javax.persistence.EntityTransaction) EntityManager(javax.persistence.EntityManager) User(org.opencastproject.security.api.User) Organization(org.opencastproject.security.api.Organization) NotFoundException(org.opencastproject.util.NotFoundException) ServiceRegistrationJpaImpl(org.opencastproject.serviceregistry.impl.jpa.ServiceRegistrationJpaImpl) JpaJob(org.opencastproject.job.jpa.JpaJob) JpaJob.fnToJob(org.opencastproject.job.jpa.JpaJob.fnToJob) Job(org.opencastproject.job.api.Job) JpaJob(org.opencastproject.job.jpa.JpaJob) RollbackException(javax.persistence.RollbackException) ServiceRegistryException(org.opencastproject.serviceregistry.api.ServiceRegistryException)

Example 17 with ServiceRegistryException

use of org.opencastproject.serviceregistry.api.ServiceRegistryException in project opencast by opencast.

the class MaintenanceCommand method list.

public String list() {
    try {
        StringBuilder sb = new StringBuilder();
        for (ServiceRegistration reg : serviceRegistry.getServiceRegistrations()) {
            sb.append(reg.getServiceType());
            sb.append("@");
            sb.append(reg.getHost());
            if (reg.isInMaintenanceMode()) {
                sb.append(" (maintenance mode)");
            }
            sb.append("\n");
        }
        return sb.toString();
    } catch (ServiceRegistryException e) {
        return "Error: " + e.getMessage() + "\n";
    }
}
Also used : ServiceRegistryException(org.opencastproject.serviceregistry.api.ServiceRegistryException) ServiceRegistration(org.opencastproject.serviceregistry.api.ServiceRegistration)

Example 18 with ServiceRegistryException

use of org.opencastproject.serviceregistry.api.ServiceRegistryException in project opencast by opencast.

the class PartialImportWorkflowOperationHandler method createVideoFromImage.

private Track createVideoFromImage(Attachment image, double time, List<MediaPackageElement> elementsToClean) throws EncoderException, MediaPackageException, WorkflowOperationException, NotFoundException {
    Job imageToVideoJob = composerService.imageToVideo(image, IMAGE_MOVIE_PROFILE, time);
    if (!waitForStatus(imageToVideoJob).isSuccess())
        throw new WorkflowOperationException("Image to video job did not complete successfully");
    // Get the latest copy
    try {
        imageToVideoJob = serviceRegistry.getJob(imageToVideoJob.getId());
    } catch (ServiceRegistryException e) {
        throw new WorkflowOperationException(e);
    }
    Track imageVideo = (Track) MediaPackageElementParser.getFromXml(imageToVideoJob.getPayload());
    elementsToClean.add(imageVideo);
    return imageVideo;
}
Also used : WorkflowOperationException(org.opencastproject.workflow.api.WorkflowOperationException) Job(org.opencastproject.job.api.Job) ServiceRegistryException(org.opencastproject.serviceregistry.api.ServiceRegistryException) Track(org.opencastproject.mediapackage.Track)

Example 19 with ServiceRegistryException

use of org.opencastproject.serviceregistry.api.ServiceRegistryException in project opencast by opencast.

the class PartialImportWorkflowOperationHandler method extractImage.

private Attachment extractImage(Track presentationTrack, double time, List<MediaPackageElement> elementsToClean) throws EncoderException, MediaPackageException, WorkflowOperationException, NotFoundException {
    Job extractImageJob = composerService.image(presentationTrack, PREVIEW_PROFILE, time);
    if (!waitForStatus(extractImageJob).isSuccess())
        throw new WorkflowOperationException("Extract image frame video job did not complete successfully");
    // Get the latest copy
    try {
        extractImageJob = serviceRegistry.getJob(extractImageJob.getId());
    } catch (ServiceRegistryException e) {
        throw new WorkflowOperationException(e);
    }
    Attachment composedImages = (Attachment) MediaPackageElementParser.getArrayFromXml(extractImageJob.getPayload()).get(0);
    elementsToClean.add(composedImages);
    return composedImages;
}
Also used : WorkflowOperationException(org.opencastproject.workflow.api.WorkflowOperationException) Attachment(org.opencastproject.mediapackage.Attachment) Job(org.opencastproject.job.api.Job) ServiceRegistryException(org.opencastproject.serviceregistry.api.ServiceRegistryException)

Example 20 with ServiceRegistryException

use of org.opencastproject.serviceregistry.api.ServiceRegistryException in project opencast by opencast.

the class SegmentPreviewsWorkflowOperationHandler method createPreviews.

/**
 * Encode tracks from MediaPackage using profiles stored in properties and updates current MediaPackage.
 *
 * @param mediaPackage
 * @param properties
 * @return the operation result containing the updated mediapackage
 * @throws EncoderException
 * @throws ExecutionException
 * @throws InterruptedException
 * @throws IOException
 * @throws NotFoundException
 * @throws WorkflowOperationException
 */
private WorkflowOperationResult createPreviews(final MediaPackage mediaPackage, WorkflowOperationInstance operation) throws EncoderException, InterruptedException, ExecutionException, NotFoundException, MediaPackageException, IOException, WorkflowOperationException {
    long totalTimeInQueue = 0;
    // Read the configuration properties
    String sourceVideoFlavor = StringUtils.trimToNull(operation.getConfiguration("source-flavor"));
    String sourceTags = StringUtils.trimToNull(operation.getConfiguration("source-tags"));
    String targetImageTags = StringUtils.trimToNull(operation.getConfiguration("target-tags"));
    String targetImageFlavor = StringUtils.trimToNull(operation.getConfiguration("target-flavor"));
    String encodingProfileName = StringUtils.trimToNull(operation.getConfiguration("encoding-profile"));
    String referenceFlavor = StringUtils.trimToNull(operation.getConfiguration("reference-flavor"));
    String referenceTags = StringUtils.trimToNull(operation.getConfiguration("reference-tags"));
    // Find the encoding profile
    EncodingProfile profile = composerService.getProfile(encodingProfileName);
    if (profile == null)
        throw new IllegalStateException("Encoding profile '" + encodingProfileName + "' was not found");
    List<String> sourceTagSet = asList(sourceTags);
    // Select the tracks based on the tags and flavors
    Set<Track> videoTrackSet = new HashSet<>();
    for (Track track : mediaPackage.getTracksByTags(sourceTagSet)) {
        if (sourceVideoFlavor == null || (track.getFlavor() != null && sourceVideoFlavor.equals(track.getFlavor().toString()))) {
            if (!track.hasVideo())
                continue;
            videoTrackSet.add(track);
        }
    }
    if (videoTrackSet.size() == 0) {
        logger.debug("Mediapackage {} has no suitable tracks to extract images based on tags {} and flavor {}", mediaPackage, sourceTags, sourceVideoFlavor);
        return createResult(mediaPackage, Action.CONTINUE);
    } else {
        // Determine the tagset for the reference
        List<String> referenceTagSet = asList(referenceTags);
        // Determine the reference master
        for (Track t : videoTrackSet) {
            // Try to load the segments catalog
            MediaPackageReference trackReference = new MediaPackageReferenceImpl(t);
            Catalog[] segmentCatalogs = mediaPackage.getCatalogs(MediaPackageElements.SEGMENTS, trackReference);
            Mpeg7Catalog mpeg7 = null;
            if (segmentCatalogs.length > 0) {
                mpeg7 = loadMpeg7Catalog(segmentCatalogs[0]);
                if (segmentCatalogs.length > 1)
                    logger.warn("More than one segments catalog found for track {}. Resuming with the first one ({})", t, mpeg7);
            } else {
                logger.debug("No segments catalog found for track {}", t);
                continue;
            }
            // Check the catalog's consistency
            if (mpeg7.videoContent() == null || mpeg7.videoContent().next() == null) {
                logger.info("Segments catalog {} contains no video content", mpeg7);
                continue;
            }
            Video videoContent = mpeg7.videoContent().next();
            TemporalDecomposition<? extends Segment> decomposition = videoContent.getTemporalDecomposition();
            // Are there any segments?
            if (decomposition == null || !decomposition.hasSegments()) {
                logger.info("Segments catalog {} contains no video content", mpeg7);
                continue;
            }
            // Is a derived track with the configured reference flavor available?
            MediaPackageElement referenceMaster = getReferenceMaster(mediaPackage, t, referenceFlavor, referenceTagSet);
            // Create the preview images according to the mpeg7 segments
            if (t.hasVideo() && mpeg7 != null) {
                Iterator<? extends Segment> segmentIterator = decomposition.segments();
                List<MediaTimePoint> timePointList = new LinkedList<>();
                while (segmentIterator.hasNext()) {
                    Segment segment = segmentIterator.next();
                    MediaTimePoint tp = segment.getMediaTime().getMediaTimePoint();
                    timePointList.add(tp);
                }
                // convert to time array
                double[] timeArray = new double[timePointList.size()];
                for (int i = 0; i < timePointList.size(); i++) timeArray[i] = (double) timePointList.get(i).getTimeInMilliseconds() / 1000;
                Job job = composerService.image(t, profile.getIdentifier(), timeArray);
                if (!waitForStatus(job).isSuccess()) {
                    throw new WorkflowOperationException("Extracting preview image from " + t + " failed");
                }
                // Get the latest copy
                try {
                    job = serviceRegistry.getJob(job.getId());
                } catch (ServiceRegistryException e) {
                    throw new WorkflowOperationException(e);
                }
                // add this receipt's queue time to the total
                totalTimeInQueue += job.getQueueTime();
                List<? extends MediaPackageElement> composedImages = MediaPackageElementParser.getArrayFromXml(job.getPayload());
                Iterator<MediaTimePoint> it = timePointList.iterator();
                for (MediaPackageElement element : composedImages) {
                    Attachment composedImage = (Attachment) element;
                    if (composedImage == null)
                        throw new IllegalStateException("Unable to compose image");
                    // Add the flavor, either from the operation configuration or from the composer
                    if (targetImageFlavor != null) {
                        composedImage.setFlavor(MediaPackageElementFlavor.parseFlavor(targetImageFlavor));
                        logger.debug("Preview image has flavor '{}'", composedImage.getFlavor());
                    }
                    // Set the mimetype
                    if (profile.getMimeType() != null)
                        composedImage.setMimeType(MimeTypes.parseMimeType(profile.getMimeType()));
                    // Add tags
                    for (String tag : asList(targetImageTags)) {
                        logger.trace("Tagging image with '{}'", tag);
                        composedImage.addTag(tag);
                    }
                    // Refer to the original track including a timestamp
                    MediaPackageReferenceImpl ref = new MediaPackageReferenceImpl(referenceMaster);
                    ref.setProperty("time", it.next().toString());
                    composedImage.setReference(ref);
                    // store new image in the mediaPackage
                    mediaPackage.add(composedImage);
                    String fileName = getFileNameFromElements(t, composedImage);
                    composedImage.setURI(workspace.moveTo(composedImage.getURI(), mediaPackage.getIdentifier().toString(), composedImage.getIdentifier(), fileName));
                }
            }
        }
    }
    return createResult(mediaPackage, Action.CONTINUE, totalTimeInQueue);
}
Also used : Attachment(org.opencastproject.mediapackage.Attachment) Segment(org.opencastproject.metadata.mpeg7.Segment) MediaPackageElement(org.opencastproject.mediapackage.MediaPackageElement) WorkflowOperationException(org.opencastproject.workflow.api.WorkflowOperationException) Job(org.opencastproject.job.api.Job) HashSet(java.util.HashSet) MediaTimePoint(org.opencastproject.metadata.mpeg7.MediaTimePoint) EncodingProfile(org.opencastproject.composer.api.EncodingProfile) Catalog(org.opencastproject.mediapackage.Catalog) Mpeg7Catalog(org.opencastproject.metadata.mpeg7.Mpeg7Catalog) LinkedList(java.util.LinkedList) MediaTimePoint(org.opencastproject.metadata.mpeg7.MediaTimePoint) ServiceRegistryException(org.opencastproject.serviceregistry.api.ServiceRegistryException) Mpeg7Catalog(org.opencastproject.metadata.mpeg7.Mpeg7Catalog) MediaPackageReference(org.opencastproject.mediapackage.MediaPackageReference) Video(org.opencastproject.metadata.mpeg7.Video) MediaPackageReferenceImpl(org.opencastproject.mediapackage.MediaPackageReferenceImpl) Track(org.opencastproject.mediapackage.Track)

Aggregations

ServiceRegistryException (org.opencastproject.serviceregistry.api.ServiceRegistryException)99 NotFoundException (org.opencastproject.util.NotFoundException)61 ConfigurationException (org.osgi.service.cm.ConfigurationException)41 InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)30 URISyntaxException (java.net.URISyntaxException)29 Job (org.opencastproject.job.api.Job)29 PersistenceException (javax.persistence.PersistenceException)26 RollbackException (javax.persistence.RollbackException)26 TrustedHttpClientException (org.opencastproject.security.api.TrustedHttpClientException)26 NoResultException (javax.persistence.NoResultException)25 MediaPackageException (org.opencastproject.mediapackage.MediaPackageException)25 IOException (java.io.IOException)24 ArrayList (java.util.ArrayList)24 EntityManager (javax.persistence.EntityManager)22 MediaPackage (org.opencastproject.mediapackage.MediaPackage)20 URI (java.net.URI)16 MediaPackageElement (org.opencastproject.mediapackage.MediaPackageElement)14 DistributionException (org.opencastproject.distribution.api.DistributionException)13 Attachment (org.opencastproject.mediapackage.Attachment)12 WorkflowOperationException (org.opencastproject.workflow.api.WorkflowOperationException)12