Search in sources :

Example 41 with SchedulerException

use of org.opencastproject.scheduler.api.SchedulerException in project opencast by opencast.

the class SchedulerRestService method rollbackTransaction.

@POST
@Path("/transaction/{id}/rollback")
@RestQuery(name = "rollbacktransaction", description = "Rolls back the scheduler transaction with specified id", returnDescription = "Successfully rolled back scheduler transaction", reponses = { @RestResponse(responseCode = SC_OK, description = "Successfully rolled back scheduler transaction"), @RestResponse(responseCode = SC_NOT_FOUND, description = "Scheduler transaction with specified ID does not exist"), @RestResponse(responseCode = SC_UNAUTHORIZED, description = "You do not have permission to rollback the scheduler transaction. Maybe you need to authenticate.") }, pathParameters = { @RestParameter(name = "id", type = RestParameter.Type.STRING, isRequired = true, description = "ID of scheduler transaction") })
public Response rollbackTransaction(@PathParam("id") String transactionId) throws UnauthorizedException, NotFoundException {
    try {
        SchedulerTransaction transaction = service.getTransaction(transactionId);
        transaction.rollback();
        return Response.ok().build();
    } catch (SchedulerException e) {
        logger.error("Unable to rollback scheduler transaction '{}': {}", transactionId, getStackTrace(e));
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : SchedulerException(org.opencastproject.scheduler.api.SchedulerException) WebApplicationException(javax.ws.rs.WebApplicationException) SchedulerTransaction(org.opencastproject.scheduler.api.SchedulerService.SchedulerTransaction) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 42 with SchedulerException

use of org.opencastproject.scheduler.api.SchedulerException in project opencast by opencast.

the class SchedulerRestService method startCapture.

@POST
@Path("capture/{agent}")
@RestQuery(name = "startcapture", description = "Create an immediate event", returnDescription = "If events were successfully generated, status CREATED is returned", pathParameters = { @RestParameter(name = "agent", isRequired = true, type = Type.STRING, description = "The agent identifier") }, restParameters = { @RestParameter(name = "workflowDefinitionId", isRequired = false, type = Type.STRING, description = "The workflow definition id to use") }, reponses = { @RestResponse(responseCode = HttpServletResponse.SC_CREATED, description = "Recording started"), @RestResponse(responseCode = HttpServletResponse.SC_NOT_FOUND, description = "There is no such agent"), @RestResponse(responseCode = HttpServletResponse.SC_CONFLICT, description = "The agent is already recording"), @RestResponse(responseCode = HttpServletResponse.SC_UNAUTHORIZED, description = "You do not have permission to start this immediate capture. Maybe you need to authenticate."), @RestResponse(responseCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE, description = "The agent is not ready to communicate") })
public Response startCapture(@PathParam("agent") String agentId, @FormParam("workflowDefinitionId") String wfId) throws NotFoundException, UnauthorizedException {
    if (service == null || agentService == null || prolongingService == null)
        return Response.serverError().status(Response.Status.SERVICE_UNAVAILABLE).entity("Scheduler service is unavailable, please wait...").build();
    // Lookup the agent. If it doesn't exist, add a temporary registration
    boolean adHocRegistration = false;
    try {
        agentService.getAgent(agentId);
    } catch (NotFoundException e) {
        Properties adHocProperties = new Properties();
        adHocProperties.put(AGENT_REGISTRATION_TYPE, AGENT_REGISTRATION_TYPE_ADHOC);
        agentService.setAgentConfiguration(agentId, adHocProperties);
        agentService.setAgentState(agentId, AgentState.CAPTURING);
        adHocRegistration = true;
        logger.info("Temporarily registered agent '{}' for ad-hoc recording", agentId);
    }
    try {
        Date now = new Date();
        Date temporaryEndDate = DateTime.now().plus(prolongingService.getInitialTime()).toDate();
        try {
            List<MediaPackage> events = service.findConflictingEvents(agentId, now, temporaryEndDate);
            if (!events.isEmpty()) {
                logger.info("An already existing event is in a conflict with the the one to be created on the agent {}!", agentId);
                return Response.status(Status.CONFLICT).build();
            }
        } catch (SchedulerException e) {
            logger.error("Unable to create immediate event on agent {}: {}", agentId, e);
            throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
        }
        String workflowId = defaultWorkflowDefinitionId;
        if (StringUtils.isNotBlank(wfId))
            workflowId = wfId;
        Map<String, String> caProperties = new HashMap<>();
        caProperties.put("org.opencastproject.workflow.definition", workflowId);
        caProperties.put("event.location", agentId);
        caProperties.put("event.title", "Capture now event");
        // caProperties.put("org.opencastproject.workflow.config.captionHold", "false");
        // caProperties.put("org.opencastproject.workflow.config.archiveOp", "true");
        // caProperties.put("org.opencastproject.workflow.config.trimHold", "false");
        // TODO default metadata? configurable?
        // A temporal with start and end period is needed! As well PROPERTY_SPATIAL is needed
        DublinCoreCatalog eventCatalog = DublinCores.mkOpencastEpisode().getCatalog();
        eventCatalog.set(PROPERTY_TITLE, "Capture now event");
        eventCatalog.set(PROPERTY_TEMPORAL, EncodingSchemeUtils.encodePeriod(new DCMIPeriod(now, temporaryEndDate), Precision.Second));
        eventCatalog.set(PROPERTY_SPATIAL, agentId);
        eventCatalog.set(PROPERTY_CREATED, EncodingSchemeUtils.encodeDate(new Date(), Precision.Minute));
        // eventCatalog.set(PROPERTY_CREATOR, "demo");
        // eventCatalog.set(PROPERTY_SUBJECT, "demo");
        // eventCatalog.set(PROPERTY_LANGUAGE, "demo");
        // eventCatalog.set(PROPERTY_CONTRIBUTOR, "demo");
        // eventCatalog.set(PROPERTY_DESCRIPTION, "demo");
        // TODO workflow properties
        Map<String, String> wfProperties = new HashMap<>();
        MediaPackage mediaPackage = null;
        try {
            mediaPackage = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder().createNew();
            mediaPackage = addCatalog(workspace, IOUtils.toInputStream(eventCatalog.toXmlString(), "UTF-8"), "dublincore.xml", MediaPackageElements.EPISODE, mediaPackage);
            prolongingService.schedule(agentId);
            service.addEvent(now, temporaryEndDate, agentId, Collections.<String>emptySet(), mediaPackage, wfProperties, caProperties, Opt.<Boolean>none(), Opt.<String>none(), SchedulerService.ORIGIN);
            return Response.status(Status.CREATED).header("Location", serverUrl + serviceUrl + '/' + mediaPackage.getIdentifier().compact() + ".xml").build();
        } catch (Exception e) {
            prolongingService.stop(agentId);
            if (e instanceof UnauthorizedException)
                throw (UnauthorizedException) e;
            logger.error("Unable to create immediate event on agent {}: {}", agentId, e);
            throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
        } finally {
            if (mediaPackage != null) {
                for (MediaPackageElement elem : $(mediaPackage.getElements()).bind(MediaPackageSupport.Filters.byFlavor(MediaPackageElements.EPISODE).toFn())) {
                    try {
                        workspace.delete(elem.getURI());
                    } catch (NotFoundException e) {
                        logger.warn("Unable to find (and hence, delete), this mediapackage '{}' element '{}'", mediaPackage.getIdentifier(), elem.getIdentifier());
                    } catch (IOException e) {
                        chuck(e);
                    }
                }
            }
        }
    } catch (Throwable t) {
        throw t;
    } finally {
        if (adHocRegistration) {
            agentService.removeAgent(agentId);
            logger.info("Removed temporary registration for agent '{}'", agentId);
        }
    }
}
Also used : SchedulerException(org.opencastproject.scheduler.api.SchedulerException) WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) DCMIPeriod(org.opencastproject.metadata.dublincore.DCMIPeriod) NotFoundException(org.opencastproject.util.NotFoundException) IOException(java.io.IOException) Properties(java.util.Properties) Date(java.util.Date) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) SchedulerConflictException(org.opencastproject.scheduler.api.SchedulerConflictException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) SchedulerTransactionLockException(org.opencastproject.scheduler.api.SchedulerTransactionLockException) ParseException(java.text.ParseException) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) MediaPackageElement(org.opencastproject.mediapackage.MediaPackageElement) MediaPackage(org.opencastproject.mediapackage.MediaPackage) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 43 with SchedulerException

use of org.opencastproject.scheduler.api.SchedulerException in project opencast by opencast.

the class SchedulerRestService method commitTransaction.

@POST
@Path("/transaction/{id}/commit")
@RestQuery(name = "committransaction", description = "Commits the scheduler transaction with specified id", returnDescription = "Successfully committed scheduler transaction", reponses = { @RestResponse(responseCode = SC_OK, description = "Successfully committed scheduler transaction"), @RestResponse(responseCode = SC_NOT_FOUND, description = "Scheduler transaction with specified ID does not exist"), @RestResponse(responseCode = SC_UNAUTHORIZED, description = "You do not have permission to commit the scheduler transaction. Maybe you need to authenticate.") }, pathParameters = { @RestParameter(name = "id", type = RestParameter.Type.STRING, isRequired = true, description = "ID of scheduler transaction") })
public Response commitTransaction(@PathParam("id") String transactionId) throws UnauthorizedException, NotFoundException {
    try {
        SchedulerTransaction transaction = service.getTransaction(transactionId);
        transaction.commit();
        return Response.ok().build();
    } catch (SchedulerException e) {
        logger.error("Unable to commit scheduler transaction '{}': {}", transactionId, getStackTrace(e));
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : SchedulerException(org.opencastproject.scheduler.api.SchedulerException) WebApplicationException(javax.ws.rs.WebApplicationException) SchedulerTransaction(org.opencastproject.scheduler.api.SchedulerService.SchedulerTransaction) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 44 with SchedulerException

use of org.opencastproject.scheduler.api.SchedulerException in project opencast by opencast.

the class IngestServiceImpl method getWorkflowDefinition.

private WorkflowDefinition getWorkflowDefinition(String workflowDefinitionID, MediaPackage mediapackage) throws NotFoundException, WorkflowDatabaseException, IngestException {
    // If the workflow definition and instance ID are null, use the default, or throw if there is none
    if (isBlank(workflowDefinitionID)) {
        String mediaPackageId = mediapackage.getIdentifier().compact();
        if (schedulerService != null) {
            logger.info("Determining workflow template for ingested mediapckage {} from capture event {}", mediapackage, mediaPackageId);
            try {
                Map<String, String> recordingProperties = schedulerService.getCaptureAgentConfiguration(mediaPackageId);
                workflowDefinitionID = recordingProperties.get(CaptureParameters.INGEST_WORKFLOW_DEFINITION);
                if (isBlank(workflowDefinitionID)) {
                    workflowDefinitionID = defaultWorkflowDefinionId;
                    logger.debug("No workflow set. Falling back to default.");
                }
                if (isBlank(workflowDefinitionID)) {
                    throw new IngestException("No value found for key '" + CaptureParameters.INGEST_WORKFLOW_DEFINITION + "' from capture event configuration of scheduler event '" + mediaPackageId + "'");
                }
                logger.info("Ingested event {} will be processed using workflow '{}'", mediapackage, workflowDefinitionID);
            } catch (NotFoundException e) {
                logger.warn("Specified capture event {} was not found", mediaPackageId);
            } catch (UnauthorizedException e) {
                throw new IllegalStateException(e);
            } catch (SchedulerException e) {
                logger.warn("Unable to get the workflow definition id from scheduler event {}: {}", mediaPackageId, ExceptionUtils.getMessage(e));
                throw new IngestException(e);
            }
        } else {
            logger.warn("Scheduler service not bound, unable to determine the workflow template to use for ingested mediapckage {}", mediapackage);
        }
    } else {
        logger.info("Ingested mediapackage {} is processed using workflow template '{}', specified during ingest", mediapackage, workflowDefinitionID);
    }
    // Use the default workflow definition if nothing was determined
    if (isBlank(workflowDefinitionID) && defaultWorkflowDefinionId != null) {
        logger.info("Using default workflow definition '{}' to process ingested mediapackage {}", defaultWorkflowDefinionId, mediapackage);
        workflowDefinitionID = defaultWorkflowDefinionId;
    }
    // Check if the workflow definition is valid
    if (StringUtils.isNotBlank(workflowDefinitionID) && StringUtils.isNotBlank(defaultWorkflowDefinionId)) {
        try {
            workflowService.getWorkflowDefinitionById(workflowDefinitionID);
        } catch (WorkflowDatabaseException e) {
            throw new IngestException(e);
        } catch (NotFoundException nfe) {
            logger.warn("Workflow definition {} not found, using default workflow {} instead", workflowDefinitionID, defaultWorkflowDefinionId);
            workflowDefinitionID = defaultWorkflowDefinionId;
        }
    }
    // Have we been able to find a workflow definition id?
    if (isBlank(workflowDefinitionID)) {
        ingestStatistics.failed();
        throw new IllegalStateException("Can not ingest a workflow without a workflow definition or an existing instance. No default definition is specified");
    }
    // Let's make sure the workflow definition exists
    return workflowService.getWorkflowDefinitionById(workflowDefinitionID);
}
Also used : WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) IngestException(org.opencastproject.ingest.api.IngestException)

Example 45 with SchedulerException

use of org.opencastproject.scheduler.api.SchedulerException in project opencast by opencast.

the class AbstractEventEndpoint method applyAclToEvent.

@POST
@Path("{eventId}/access")
@RestQuery(name = "applyAclToEvent", description = "Immediate application of an ACL to an event", returnDescription = "Status code", pathParameters = { @RestParameter(name = "eventId", isRequired = true, description = "The event ID", type = STRING) }, restParameters = { @RestParameter(name = "acl", isRequired = true, description = "The ACL to apply", type = STRING) }, reponses = { @RestResponse(responseCode = SC_OK, description = "The ACL has been successfully applied"), @RestResponse(responseCode = SC_BAD_REQUEST, description = "Unable to parse the given ACL"), @RestResponse(responseCode = SC_NOT_FOUND, description = "The the event has not been found"), @RestResponse(responseCode = SC_UNAUTHORIZED, description = "Not authorized to perform this action"), @RestResponse(responseCode = SC_INTERNAL_SERVER_ERROR, description = "Internal error") })
public Response applyAclToEvent(@PathParam("eventId") String eventId, @FormParam("acl") String acl) throws NotFoundException, UnauthorizedException, SearchIndexException, IndexServiceException {
    final AccessControlList accessControlList;
    try {
        accessControlList = AccessControlParser.parseAcl(acl);
    } catch (Exception e) {
        logger.warn("Unable to parse ACL '{}'", acl);
        return badRequest();
    }
    try {
        final Opt<Event> optEvent = getIndexService().getEvent(eventId, getIndex());
        if (optEvent.isNone()) {
            logger.warn("Unable to find the event '{}'", eventId);
            return notFound();
        }
        Source eventSource = getIndexService().getEventSource(optEvent.get());
        if (eventSource == Source.ARCHIVE) {
            if (getAclService().applyAclToEpisode(eventId, accessControlList, Option.<ConfiguredWorkflowRef>none())) {
                return ok();
            } else {
                logger.warn("Unable to find the event '{}'", eventId);
                return notFound();
            }
        } else if (eventSource == Source.WORKFLOW) {
            logger.warn("An ACL cannot be edited while an event is part of a current workflow because it might" + " lead to inconsistent ACLs i.e. changed after distribution so that the old ACL is still " + "being used by the distribution channel.");
            JSONObject json = new JSONObject();
            json.put("Error", "Unable to edit an ACL for a current workflow.");
            return conflict(json.toJSONString());
        } else {
            MediaPackage mediaPackage = getIndexService().getEventMediapackage(optEvent.get());
            mediaPackage = getAuthorizationService().setAcl(mediaPackage, AclScope.Episode, accessControlList).getA();
            getSchedulerService().updateEvent(eventId, Opt.<Date>none(), Opt.<Date>none(), Opt.<String>none(), Opt.<Set<String>>none(), some(mediaPackage), Opt.<Map<String, String>>none(), Opt.<Map<String, String>>none(), Opt.<Opt<Boolean>>none(), SchedulerService.ORIGIN);
            return ok();
        }
    } catch (AclServiceException e) {
        logger.error("Error applying acl '{}' to event '{}' because: {}", accessControlList, eventId, ExceptionUtils.getStackTrace(e));
        return serverError();
    } catch (SchedulerException e) {
        logger.error("Error applying ACL to scheduled event {} because {}", eventId, ExceptionUtils.getStackTrace(e));
        return serverError();
    }
}
Also used : AccessControlList(org.opencastproject.security.api.AccessControlList) AclServiceException(org.opencastproject.authorization.xacml.manager.api.AclServiceException) Set(java.util.Set) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) WebApplicationException(javax.ws.rs.WebApplicationException) EventCommentException(org.opencastproject.event.comment.EventCommentException) JSONException(org.codehaus.jettison.json.JSONException) JobEndpointException(org.opencastproject.adminui.exception.JobEndpointException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) ParseException(java.text.ParseException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) AclServiceException(org.opencastproject.authorization.xacml.manager.api.AclServiceException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) WorkflowStateException(org.opencastproject.workflow.api.WorkflowStateException) Source(org.opencastproject.index.service.api.IndexService.Source) Date(java.util.Date) Opt(com.entwinemedia.fn.data.Opt) JSONObject(org.json.simple.JSONObject) MediaPackage(org.opencastproject.mediapackage.MediaPackage) Event(org.opencastproject.index.service.impl.index.event.Event) Map(java.util.Map) HashMap(java.util.HashMap) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Aggregations

SchedulerException (org.opencastproject.scheduler.api.SchedulerException)83 NotFoundException (org.opencastproject.util.NotFoundException)76 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)68 SchedulerConflictException (org.opencastproject.scheduler.api.SchedulerConflictException)62 SchedulerTransactionLockException (org.opencastproject.scheduler.api.SchedulerTransactionLockException)60 HttpResponse (org.apache.http.HttpResponse)32 MediaPackageException (org.opencastproject.mediapackage.MediaPackageException)30 IOException (java.io.IOException)29 SeriesException (org.opencastproject.series.api.SeriesException)27 ValidationException (net.fortuna.ical4j.model.ValidationException)26 ServiceException (org.osgi.framework.ServiceException)26 ConfigurationException (org.osgi.service.cm.ConfigurationException)26 AQueryBuilder (org.opencastproject.assetmanager.api.query.AQueryBuilder)22 MediaPackage (org.opencastproject.mediapackage.MediaPackage)22 Date (java.util.Date)21 HttpGet (org.apache.http.client.methods.HttpGet)19 ARecord (org.opencastproject.assetmanager.api.query.ARecord)19 AResult (org.opencastproject.assetmanager.api.query.AResult)19 ArrayList (java.util.ArrayList)16 Log.getHumanReadableTimeString (org.opencastproject.util.Log.getHumanReadableTimeString)16