Search in sources :

Example 56 with WorkflowInstance

use of org.opencastproject.workflow.api.WorkflowInstance in project opencast by opencast.

the class CommentWorkflowOperationHandlerTest method testDuplicateComments.

@Test
public void testDuplicateComments() throws WorkflowOperationException, EventCommentException {
    // Testing that a duplicate comment won't be created but a different one will still be created.
    Long workflowId = 10L;
    String mediaPackageId = "abc-def";
    String action = "create";
    String reason = "Waiting for Trim";
    String description = "The comment description";
    Organization org = createNiceMock(Organization.class);
    expect(org.getId()).andStubReturn("demo");
    replay(org);
    SecurityService secSrv = createNiceMock(SecurityService.class);
    expect(secSrv.getOrganization()).andStubReturn(org);
    replay(secSrv);
    // Setup WorkflowOperation Instance
    WorkflowOperationInstance workflowOperationInstance = EasyMock.createMock(WorkflowOperationInstance.class);
    EasyMock.expect(workflowOperationInstance.getConfiguration(CommentWorkflowOperationHandler.ACTION)).andReturn(action).anyTimes();
    EasyMock.expect(workflowOperationInstance.getConfiguration(CommentWorkflowOperationHandler.REASON)).andReturn(reason).anyTimes();
    EasyMock.expect(workflowOperationInstance.getConfiguration(CommentWorkflowOperationHandler.DESCRIPTION)).andReturn(description).anyTimes();
    // Setup mediaPackage
    MediaPackage mediaPackage = EasyMock.createMock(MediaPackage.class);
    EasyMock.expect(mediaPackage.getIdentifier()).andReturn(new IdImpl(mediaPackageId)).anyTimes();
    // Setup user
    User creator = EasyMock.createMock(User.class);
    // Setup WorkflowInstance
    WorkflowInstance workflowInstance = EasyMock.createMock(WorkflowInstance.class);
    EasyMock.expect(workflowInstance.getId()).andReturn(workflowId).anyTimes();
    EasyMock.expect(workflowInstance.getCurrentOperation()).andReturn(workflowOperationInstance).anyTimes();
    EasyMock.expect(workflowInstance.getMediaPackage()).andReturn(mediaPackage).anyTimes();
    EasyMock.expect(workflowInstance.getCreator()).andReturn(creator).anyTimes();
    // Test no previous comments
    EventCommentService eventCommentService = EasyMock.createMock(EventCommentService.class);
    EasyMock.expect(eventCommentService.getComments(mediaPackageId)).andReturn(new ArrayList<EventComment>());
    Capture<EventComment> comment = EasyMock.newCapture();
    EasyMock.expect(eventCommentService.updateComment(EasyMock.capture(comment))).andReturn(EventComment.create(Option.option(15L), mediaPackageId, org.getId(), description, creator));
    EasyMock.replay(creator, eventCommentService, mediaPackage, workflowInstance, workflowOperationInstance);
    CommentWorkflowOperationHandler commentWorkflowOperationHandler = new CommentWorkflowOperationHandler();
    commentWorkflowOperationHandler.setEventCommentService(eventCommentService);
    commentWorkflowOperationHandler.setSecurityService(secSrv);
    commentWorkflowOperationHandler.start(workflowInstance, null);
    assertTrue(comment.hasCaptured());
    assertEquals(creator, comment.getValue().getAuthor());
    assertEquals(description, comment.getValue().getText());
    assertEquals(reason, comment.getValue().getReason());
    // Test previous comment with same reason and description
    List<EventComment> comments = new ArrayList<EventComment>();
    comments.add(EventComment.create(Option.option(13L), mediaPackageId, org.getId(), description, creator, reason, true));
    eventCommentService = EasyMock.createMock(EventCommentService.class);
    EasyMock.expect(eventCommentService.getComments(mediaPackageId)).andReturn(comments);
    EasyMock.replay(eventCommentService);
    commentWorkflowOperationHandler = new CommentWorkflowOperationHandler();
    commentWorkflowOperationHandler.setEventCommentService(eventCommentService);
    commentWorkflowOperationHandler.start(workflowInstance, null);
    assertTrue(comment.hasCaptured());
    assertEquals(creator, comment.getValue().getAuthor());
    assertEquals(description, comment.getValue().getText());
    assertEquals(reason, comment.getValue().getReason());
    // Test previous comment with different reasons and descriptions
    comments = new ArrayList<EventComment>();
    comments.add(EventComment.create(Option.option(15L), mediaPackageId, org.getId(), "Different description", creator, reason, true));
    comments.add(EventComment.create(Option.option(15L), mediaPackageId, org.getId(), description, creator, "Different reason", true));
    eventCommentService = EasyMock.createMock(EventCommentService.class);
    EasyMock.expect(eventCommentService.getComments(mediaPackageId)).andReturn(comments);
    comment = EasyMock.newCapture();
    EasyMock.expect(eventCommentService.updateComment(EasyMock.capture(comment))).andReturn(EventComment.create(Option.option(15L), mediaPackageId, org.getId(), description, creator));
    EasyMock.replay(eventCommentService);
    commentWorkflowOperationHandler = new CommentWorkflowOperationHandler();
    commentWorkflowOperationHandler.setEventCommentService(eventCommentService);
    commentWorkflowOperationHandler.setSecurityService(secSrv);
    commentWorkflowOperationHandler.start(workflowInstance, null);
    assertTrue(comment.hasCaptured());
    assertEquals(creator, comment.getValue().getAuthor());
    assertEquals(description, comment.getValue().getText());
    assertEquals(reason, comment.getValue().getReason());
}
Also used : Organization(org.opencastproject.security.api.Organization) User(org.opencastproject.security.api.User) ArrayList(java.util.ArrayList) WorkflowInstance(org.opencastproject.workflow.api.WorkflowInstance) IdImpl(org.opencastproject.mediapackage.identifier.IdImpl) EventComment(org.opencastproject.event.comment.EventComment) WorkflowOperationInstance(org.opencastproject.workflow.api.WorkflowOperationInstance) SecurityService(org.opencastproject.security.api.SecurityService) MediaPackage(org.opencastproject.mediapackage.MediaPackage) EventCommentService(org.opencastproject.event.comment.EventCommentService) Test(org.junit.Test)

Example 57 with WorkflowInstance

use of org.opencastproject.workflow.api.WorkflowInstance in project opencast by opencast.

the class IndexServiceImpl method getCurrentWorkflowInstance.

@Override
public Opt<WorkflowInstance> getCurrentWorkflowInstance(String mpId) throws IndexServiceException {
    WorkflowQuery query = new WorkflowQuery().withMediaPackage(mpId);
    WorkflowSet workflowInstances;
    try {
        workflowInstances = workflowService.getWorkflowInstances(query);
        if (workflowInstances.size() == 0) {
            logger.info("No workflow instance found for mediapackage {}.", mpId);
            return Opt.none();
        }
    } catch (WorkflowDatabaseException e) {
        logger.error("Unable to get workflows for event {} because {}", mpId, getStackTrace(e));
        throw new IndexServiceException("Unable to get current workflow for event " + mpId);
    }
    // Get the newest workflow instance
    // TODO This presuppose knowledge of the Database implementation and should be fixed sooner or later!
    WorkflowInstance workflowInstance = workflowInstances.getItems()[0];
    for (WorkflowInstance instance : workflowInstances.getItems()) {
        if (instance.getId() > workflowInstance.getId())
            workflowInstance = instance;
    }
    return Opt.some(workflowInstance);
}
Also used : WorkflowSet(org.opencastproject.workflow.api.WorkflowSet) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) WorkflowQuery(org.opencastproject.workflow.api.WorkflowQuery) WorkflowInstance(org.opencastproject.workflow.api.WorkflowInstance) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException)

Example 58 with WorkflowInstance

use of org.opencastproject.workflow.api.WorkflowInstance in project opencast by opencast.

the class IndexServiceImpl method removeEvent.

@Override
public boolean removeEvent(String id) throws NotFoundException, UnauthorizedException {
    boolean unauthorizedScheduler = false;
    boolean notFoundScheduler = false;
    boolean removedScheduler = true;
    try {
        schedulerService.removeEvent(id);
    } catch (NotFoundException e) {
        notFoundScheduler = true;
    } catch (UnauthorizedException e) {
        unauthorizedScheduler = true;
    } catch (SchedulerException e) {
        removedScheduler = false;
        logger.error("Unable to remove the event '{}' from scheduler service: {}", id, getStackTrace(e));
    }
    boolean unauthorizedWorkflow = false;
    boolean notFoundWorkflow = false;
    boolean removedWorkflow = true;
    try {
        WorkflowQuery workflowQuery = new WorkflowQuery().withMediaPackage(id);
        WorkflowSet workflowSet = workflowService.getWorkflowInstances(workflowQuery);
        if (workflowSet.size() == 0)
            notFoundWorkflow = true;
        for (WorkflowInstance instance : workflowSet.getItems()) {
            workflowService.stop(instance.getId());
            workflowService.remove(instance.getId());
        }
    } catch (NotFoundException e) {
        notFoundWorkflow = true;
    } catch (UnauthorizedException e) {
        unauthorizedWorkflow = true;
    } catch (WorkflowDatabaseException e) {
        removedWorkflow = false;
        logger.error("Unable to remove the event '{}' because removing workflow failed: {}", id, getStackTrace(e));
    } catch (WorkflowException e) {
        removedWorkflow = false;
        logger.error("Unable to remove the event '{}' because removing workflow failed: {}", id, getStackTrace(e));
    }
    boolean unauthorizedArchive = false;
    boolean notFoundArchive = false;
    boolean removedArchive = true;
    try {
        final AQueryBuilder q = assetManager.createQuery();
        final Predicate p = q.organizationId().eq(securityService.getOrganization().getId()).and(q.mediaPackageId(id));
        final AResult r = q.select(q.nothing()).where(p).run();
        if (r.getSize() > 0)
            q.delete(DEFAULT_OWNER, q.snapshot()).where(p).run();
    } catch (AssetManagerException e) {
        if (e.getCause() instanceof UnauthorizedException) {
            unauthorizedArchive = true;
        } else if (e.getCause() instanceof NotFoundException) {
            notFoundArchive = true;
        } else {
            removedArchive = false;
            logger.error("Unable to remove the event '{}' from the archive: {}", id, getStackTrace(e));
        }
    }
    if (notFoundScheduler && notFoundWorkflow && notFoundArchive)
        throw new NotFoundException("Event id " + id + " not found.");
    if (unauthorizedScheduler || unauthorizedWorkflow || unauthorizedArchive)
        throw new UnauthorizedException("Not authorized to remove event id " + id);
    try {
        eventCommentService.deleteComments(id);
    } catch (EventCommentException e) {
        logger.error("Unable to remove comments for event '{}': {}", id, getStackTrace(e));
    }
    return removedScheduler && removedWorkflow && removedArchive;
}
Also used : WorkflowSet(org.opencastproject.workflow.api.WorkflowSet) WorkflowQuery(org.opencastproject.workflow.api.WorkflowQuery) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) WorkflowException(org.opencastproject.workflow.api.WorkflowException) NotFoundException(org.opencastproject.util.NotFoundException) AQueryBuilder(org.opencastproject.assetmanager.api.query.AQueryBuilder) EventCommentException(org.opencastproject.event.comment.EventCommentException) AssetManagerException(org.opencastproject.assetmanager.api.AssetManagerException) WorkflowInstance(org.opencastproject.workflow.api.WorkflowInstance) Predicate(org.opencastproject.assetmanager.api.query.Predicate) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) AResult(org.opencastproject.assetmanager.api.query.AResult)

Example 59 with WorkflowInstance

use of org.opencastproject.workflow.api.WorkflowInstance in project opencast by opencast.

the class IndexServiceImpl method updateCommentCatalog.

@Override
public void updateCommentCatalog(final Event event, final List<EventComment> comments) throws Exception {
    final SecurityContext securityContext = new SecurityContext(securityService, securityService.getOrganization(), securityService.getUser());
    executorService.execute(new Runnable() {

        @Override
        public void run() {
            securityContext.runInContext(new Effect0() {

                @Override
                protected void run() {
                    try {
                        MediaPackage mediaPackage = getEventMediapackage(event);
                        updateMediaPackageCommentCatalog(mediaPackage, comments);
                        switch(getEventSource(event)) {
                            case WORKFLOW:
                                logger.info("Update workflow mediapacakge {} with updated comments catalog.", event.getIdentifier());
                                Opt<WorkflowInstance> workflowInstance = getCurrentWorkflowInstance(event.getIdentifier());
                                if (workflowInstance.isNone()) {
                                    logger.error("No workflow instance for event {} found!", event.getIdentifier());
                                    throw new IndexServiceException("No workflow instance found for event " + event.getIdentifier());
                                }
                                WorkflowInstance instance = workflowInstance.get();
                                instance.setMediaPackage(mediaPackage);
                                updateWorkflowInstance(instance);
                                break;
                            case ARCHIVE:
                                logger.info("Update archive mediapacakge {} with updated comments catalog.", event.getIdentifier());
                                assetManager.takeSnapshot(DEFAULT_OWNER, mediaPackage);
                                break;
                            case SCHEDULE:
                                logger.info("Update scheduled mediapacakge {} with updated comments catalog.", event.getIdentifier());
                                schedulerService.updateEvent(event.getIdentifier(), Opt.<Date>none(), Opt.<Date>none(), Opt.<String>none(), Opt.<Set<String>>none(), Opt.some(mediaPackage), Opt.<Map<String, String>>none(), Opt.<Map<String, String>>none(), Opt.<Opt<Boolean>>none(), SchedulerService.ORIGIN);
                                break;
                            default:
                                logger.error("Unkown event source {}!", event.getSource().toString());
                        }
                    } catch (Exception e) {
                        logger.error("Unable to update event {} comment catalog: {}", event.getIdentifier(), getStackTrace(e));
                    }
                }
            });
        }
    });
}
Also used : Effect0(org.opencastproject.util.data.Effect0) SecurityContext(org.opencastproject.security.util.SecurityContext) MediaPackage(org.opencastproject.mediapackage.MediaPackage) WorkflowInstance(org.opencastproject.workflow.api.WorkflowInstance) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) IngestException(org.opencastproject.ingest.api.IngestException) WebApplicationException(javax.ws.rs.WebApplicationException) MetadataParsingException(org.opencastproject.metadata.dublincore.MetadataParsingException) EventCommentException(org.opencastproject.event.comment.EventCommentException) IOException(java.io.IOException) JSONException(org.codehaus.jettison.json.JSONException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) ParseException(java.text.ParseException) SeriesException(org.opencastproject.series.api.SeriesException) WorkflowException(org.opencastproject.workflow.api.WorkflowException) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) AssetManagerException(org.opencastproject.assetmanager.api.AssetManagerException)

Example 60 with WorkflowInstance

use of org.opencastproject.workflow.api.WorkflowInstance in project opencast by opencast.

the class IndexServiceImpl method startAddAssetWorkflow.

/**
 * Parses the processing information, including the workflowDefinitionId, from the metadataJson and starts the
 * workflow with the passed mediapackage.
 *
 * TODO NOTE: This checks for running workflows, then takes a snapshot prior to starting a new workflow. This causes a
 * potential race condition:
 *
 * 1. An existing workflow is running, the add asset workflow cannot start.
 *
 * 2. The snapshot(4x) archive(3x) is saved and the new workflow is started.
 *
 * 3. Possible race condition: No running workflow, a snapshot is saved but the workflow cannot start because another
 * workflow has started between the time of checking and starting running.
 *
 * 4. If race condition: the Admin UI shows error that the workflow could not start.
 *
 * 5. If race condition: The interim snapshot(4x) archive(3x) is updated(4x-3x) by the running workflow's snapshots
 * and resolves the inconsistency, eventually.
 *
 * Example of processing json:
 *
 * ...., "processing": { "workflow": "full", "configuration": { "videoPreview": "false", "trimHold": "false",
 * "captionHold": "false", "archiveOp": "true", "publishEngage": "true", "publishHarvesting": "true" } }, ....
 *
 * @param metadataJson
 * @param mp
 * @return the created workflow instance id
 * @throws IndexServiceException
 */
private String startAddAssetWorkflow(JSONObject metadataJson, MediaPackage mediaPackage) throws IndexServiceException {
    String wfId = null;
    String mpId = mediaPackage.getIdentifier().toString();
    JSONObject processing = (JSONObject) metadataJson.get("processing");
    if (processing == null)
        throw new IllegalArgumentException("No processing field in metadata");
    String workflowDefId = (String) processing.get("workflow");
    if (workflowDefId == null)
        throw new IllegalArgumentException("No workflow definition field in processing metadata");
    JSONObject configJson = (JSONObject) processing.get("configuration");
    try {
        // 1. Check if any active workflows are running for this mediapackage id
        WorkflowSet workflowSet = workflowService.getWorkflowInstances(new WorkflowQuery().withMediaPackage(mpId));
        for (WorkflowInstance wf : Arrays.asList(workflowSet.getItems())) {
            if (wf.isActive()) {
                logger.warn("Unable to start new workflow '{}' on archived media package '{}', existing workfow {} is running", workflowDefId, mediaPackage, wf.getId());
                throw new IllegalArgumentException("A workflow is already active for mp " + mpId + ", cannot start this workflow.");
            }
        }
        // 2. Save the snapshot
        assetManager.takeSnapshot(DEFAULT_OWNER, mediaPackage);
        // 3. start the new workflow on the snapshot
        // Workflow params are assumed to be String (not mixed with Number)
        Map<String, String> params = new HashMap<String, String>();
        if (configJson != null) {
            for (Object key : configJson.keySet()) {
                params.put((String) key, (String) configJson.get(key));
            }
        }
        Set<String> mpIds = new HashSet<String>();
        mpIds.add(mpId);
        final Workflows workflows = new Workflows(assetManager, workspace, workflowService);
        List<WorkflowInstance> wfList = workflows.applyWorkflowToLatestVersion(mpIds, ConfiguredWorkflow.workflow(workflowService.getWorkflowDefinitionById(workflowDefId), params)).toList();
        wfId = wfList.size() > 0 ? Long.toString(wfList.get(0).getId()) : "Unknown";
        logger.info("Asset update and publish workflow {} scheduled for mp {}", wfId, mpId);
    } catch (AssetManagerException e) {
        logger.warn("Unable to start workflow '{}' on archived media package '{}': {}", workflowDefId, mediaPackage, getStackTrace(e));
        throw new IndexServiceException("Unable to start workflow " + workflowDefId + " on " + mpId);
    } catch (WorkflowDatabaseException e) {
        logger.warn("Unable to load workflow '{}' from workflow service: {}", wfId, getStackTrace(e));
    } catch (NotFoundException e) {
        logger.warn("Workflow '{}' not found", wfId);
    }
    return wfId;
}
Also used : WorkflowSet(org.opencastproject.workflow.api.WorkflowSet) WorkflowQuery(org.opencastproject.workflow.api.WorkflowQuery) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) Workflows(org.opencastproject.assetmanager.util.Workflows) NotFoundException(org.opencastproject.util.NotFoundException) AssetManagerException(org.opencastproject.assetmanager.api.AssetManagerException) WorkflowInstance(org.opencastproject.workflow.api.WorkflowInstance) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) JSONObject(org.json.simple.JSONObject) JSONObject(org.json.simple.JSONObject) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) HashSet(java.util.HashSet)

Aggregations

WorkflowInstance (org.opencastproject.workflow.api.WorkflowInstance)94 Test (org.junit.Test)48 MediaPackage (org.opencastproject.mediapackage.MediaPackage)40 NotFoundException (org.opencastproject.util.NotFoundException)26 WorkflowOperationInstance (org.opencastproject.workflow.api.WorkflowOperationInstance)24 HashMap (java.util.HashMap)22 WorkflowDatabaseException (org.opencastproject.workflow.api.WorkflowDatabaseException)20 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)19 ArrayList (java.util.ArrayList)16 WorkflowQuery (org.opencastproject.workflow.api.WorkflowQuery)16 IOException (java.io.IOException)15 Organization (org.opencastproject.security.api.Organization)15 WorkflowSet (org.opencastproject.workflow.api.WorkflowSet)14 WorkflowException (org.opencastproject.workflow.api.WorkflowException)13 SchedulerException (org.opencastproject.scheduler.api.SchedulerException)12 WorkflowDefinitionImpl (org.opencastproject.workflow.api.WorkflowDefinitionImpl)12 WorkflowOperationResult (org.opencastproject.workflow.api.WorkflowOperationResult)11 MediaPackageException (org.opencastproject.mediapackage.MediaPackageException)10 IndexServiceException (org.opencastproject.index.service.exception.IndexServiceException)9 ServiceRegistryException (org.opencastproject.serviceregistry.api.ServiceRegistryException)9