Search in sources :

Example 46 with SchedulerException

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

the class AbstractEventEndpoint method updateEventScheduling.

@PUT
@Path("{eventId}/scheduling")
@RestQuery(name = "updateEventScheduling", description = "Updates the scheduling information of an event", returnDescription = "The method doesn't return any content", pathParameters = { @RestParameter(name = "eventId", isRequired = true, description = "The event identifier", type = RestParameter.Type.STRING) }, restParameters = { @RestParameter(name = "scheduling", isRequired = true, description = "The updated scheduling (JSON object)", type = RestParameter.Type.TEXT) }, reponses = { @RestResponse(responseCode = SC_BAD_REQUEST, description = "The required params were missing in the request."), @RestResponse(responseCode = SC_NOT_FOUND, description = "If the event has not been found."), @RestResponse(responseCode = SC_NO_CONTENT, description = "The method doesn't return any content") })
public Response updateEventScheduling(@PathParam("eventId") String eventId, @FormParam("scheduling") String scheduling) throws NotFoundException, UnauthorizedException, SearchIndexException {
    if (StringUtils.isBlank(scheduling))
        return RestUtil.R.badRequest("Missing parameters");
    try {
        final Event event = getEventOrThrowNotFoundException(eventId);
        TechnicalMetadata technicalMetadata = getSchedulerService().getTechnicalMetadata(eventId);
        final org.codehaus.jettison.json.JSONObject schedulingJson = new org.codehaus.jettison.json.JSONObject(scheduling);
        Opt<String> agentId = Opt.none();
        if (schedulingJson.has(SCHEDULING_AGENT_ID_KEY)) {
            agentId = Opt.some(schedulingJson.getString(SCHEDULING_AGENT_ID_KEY));
            logger.trace("Updating agent id of event '{}' from '{}' to '{}'", eventId, technicalMetadata.getAgentId(), agentId);
        }
        Opt<Date> start = Opt.none();
        if (schedulingJson.has(SCHEDULING_START_KEY)) {
            start = Opt.some(new Date(DateTimeSupport.fromUTC(schedulingJson.getString(SCHEDULING_START_KEY))));
            logger.trace("Updating start time of event '{}' id from '{}' to '{}'", eventId, DateTimeSupport.toUTC(technicalMetadata.getStartDate().getTime()), DateTimeSupport.toUTC(start.get().getTime()));
        }
        Opt<Date> end = Opt.none();
        if (schedulingJson.has(SCHEDULING_END_KEY)) {
            end = Opt.some(new Date(DateTimeSupport.fromUTC(schedulingJson.getString(SCHEDULING_END_KEY))));
            logger.trace("Updating end time of event '{}' id from '{}' to '{}'", eventId, DateTimeSupport.toUTC(technicalMetadata.getEndDate().getTime()), DateTimeSupport.toUTC(end.get().getTime()));
        }
        Opt<Map<String, String>> agentConfiguration = Opt.none();
        if (schedulingJson.has(SCHEDULING_AGENT_CONFIGURATION_KEY)) {
            agentConfiguration = Opt.some(JSONUtils.toMap(schedulingJson.getJSONObject(SCHEDULING_AGENT_CONFIGURATION_KEY)));
            logger.trace("Updating agent configuration of event '{}' id from '{}' to '{}'", eventId, technicalMetadata.getCaptureAgentConfiguration(), agentConfiguration);
        }
        Opt<Opt<Boolean>> optOut = Opt.none();
        if (schedulingJson.has(SCHEDULING_OPT_OUT_KEY)) {
            optOut = Opt.some(Opt.some(schedulingJson.getBoolean(SCHEDULING_OPT_OUT_KEY)));
            logger.trace("Updating optout status of event '{}' id from '{}' to '{}'", eventId, event.getOptedOut(), optOut);
        }
        if (start.isNone() && end.isNone() && agentId.isNone() && agentConfiguration.isNone() && optOut.isNone())
            return Response.noContent().build();
        if ((start.isSome() || end.isSome()) && end.getOr(technicalMetadata.getEndDate()).before(start.getOr(technicalMetadata.getStartDate())))
            return RestUtil.R.badRequest("The end date is before the start date");
        getSchedulerService().updateEvent(eventId, start, end, agentId, Opt.<Set<String>>none(), Opt.<MediaPackage>none(), Opt.<Map<String, String>>none(), agentConfiguration, optOut, SchedulerService.ORIGIN);
        return Response.noContent().build();
    } catch (JSONException e) {
        return RestUtil.R.badRequest("The scheduling object is not valid");
    } catch (ParseException e) {
        return RestUtil.R.badRequest("The UTC dates in the scheduling object is not valid");
    } catch (SchedulerException e) {
        logger.error("Unable to update scheduling technical metadata of event {}: {}", eventId, ExceptionUtils.getStackTrace(e));
        throw new WebApplicationException(e, SC_INTERNAL_SERVER_ERROR);
    }
}
Also used : SchedulerException(org.opencastproject.scheduler.api.SchedulerException) WebApplicationException(javax.ws.rs.WebApplicationException) JSONException(org.codehaus.jettison.json.JSONException) Date(java.util.Date) Opt(com.entwinemedia.fn.data.Opt) JSONObject(org.json.simple.JSONObject) Event(org.opencastproject.index.service.impl.index.event.Event) ParseException(java.text.ParseException) Map(java.util.Map) HashMap(java.util.HashMap) TechnicalMetadata(org.opencastproject.scheduler.api.TechnicalMetadata) Path(javax.ws.rs.Path) RestQuery(org.opencastproject.util.doc.rest.RestQuery) PUT(javax.ws.rs.PUT)

Example 47 with SchedulerException

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

the class AbstractEventEndpoint method getEventWorkflows.

@GET
@Path("{eventId}/workflows.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "geteventworkflows", description = "Returns all the data related to the workflows tab in the event details modal as JSON", returnDescription = "All the data related to the event workflows tab as JSON", pathParameters = { @RestParameter(name = "eventId", description = "The event id", isRequired = true, type = RestParameter.Type.STRING) }, reponses = { @RestResponse(description = "Returns all the data related to the event workflows tab as JSON", responseCode = HttpServletResponse.SC_OK), @RestResponse(description = "No event with this identifier was found.", responseCode = HttpServletResponse.SC_NOT_FOUND) })
public Response getEventWorkflows(@PathParam("eventId") String id) throws UnauthorizedException, SearchIndexException, JobEndpointException {
    Opt<Event> optEvent = getIndexService().getEvent(id, getIndex());
    if (optEvent.isNone())
        return notFound("Cannot find an event with id '%s'.", id);
    try {
        if (!optEvent.get().hasRecordingStarted()) {
            List<Field> fields = new ArrayList<Field>();
            Map<String, String> workflowConfig = getSchedulerService().getWorkflowConfig(id);
            for (Entry<String, String> entry : workflowConfig.entrySet()) {
                fields.add(f(entry.getKey(), v(entry.getValue(), Jsons.BLANK)));
            }
            Map<String, String> agentConfiguration = getSchedulerService().getCaptureAgentConfiguration(id);
            return okJson(obj(f("workflowId", v(agentConfiguration.get(CaptureParameters.INGEST_WORKFLOW_DEFINITION), Jsons.BLANK)), f("configuration", obj(fields))));
        } else {
            return okJson(getJobService().getTasksAsJSON(new WorkflowQuery().withMediaPackage(id)));
        }
    } catch (NotFoundException e) {
        return notFound("Cannot find workflows for event %s", id);
    } catch (SchedulerException e) {
        logger.error("Unable to get workflow data for event with id {}", id);
        throw new WebApplicationException(e, SC_INTERNAL_SERVER_ERROR);
    }
}
Also used : Field(com.entwinemedia.fn.data.json.Field) WorkflowQuery(org.opencastproject.workflow.api.WorkflowQuery) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) WebApplicationException(javax.ws.rs.WebApplicationException) ArrayList(java.util.ArrayList) Event(org.opencastproject.index.service.impl.index.event.Event) NotFoundException(org.opencastproject.util.NotFoundException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 48 with SchedulerException

use of org.opencastproject.scheduler.api.SchedulerException 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 49 with SchedulerException

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

the class IndexServiceImpl method updateEventAcl.

@Override
public AccessControlList updateEventAcl(String id, AccessControlList acl, AbstractSearchIndex index) throws IllegalArgumentException, IndexServiceException, SearchIndexException, NotFoundException, UnauthorizedException {
    Opt<Event> optEvent = getEvent(id, index);
    if (optEvent.isNone())
        throw new NotFoundException("Cannot find an event with id " + id);
    Event event = optEvent.get();
    MediaPackage mediaPackage = getEventMediapackage(event);
    switch(getEventSource(event)) {
        case WORKFLOW:
            // Not updating the acl as the workflow might have already passed the point of distribution.
            throw new IllegalArgumentException("Unable to update the ACL of this event as it is currently processing.");
        case ARCHIVE:
            mediaPackage = authorizationService.setAcl(mediaPackage, AclScope.Episode, acl).getA();
            assetManager.takeSnapshot(DEFAULT_OWNER, mediaPackage);
            return acl;
        case SCHEDULE:
            mediaPackage = authorizationService.setAcl(mediaPackage, AclScope.Episode, acl).getA();
            try {
                schedulerService.updateEvent(id, 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);
            } catch (SchedulerException e) {
                throw new IndexServiceException("Unable to update the acl for the scheduled event", e);
            }
            return acl;
        default:
            logger.error("Unknown event source '{}' unable to update ACL!", getEventSource(event));
            throw new IndexServiceException(String.format("Unable to update the ACL as '{}' is an unknown event source.", getEventSource(event)));
    }
}
Also used : SchedulerException(org.opencastproject.scheduler.api.SchedulerException) MediaPackage(org.opencastproject.mediapackage.MediaPackage) Event(org.opencastproject.index.service.impl.index.event.Event) NotFoundException(org.opencastproject.util.NotFoundException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException)

Example 50 with SchedulerException

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

the class SchedulerServiceImpl method removeTransactionsAfterRestart.

/**
 * Remove incomplete transactions after a restart
 */
private void removeTransactionsAfterRestart() {
    logger.info("Checking for incomplete transactions from a shutdown or restart.");
    for (final Organization org : orgDirectoryService.getOrganizations()) {
        SecurityUtil.runAs(securityService, org, SecurityUtil.createSystemUser(systemUserName, org), new Effect0() {

            private void rollbackTransaction(String transactionID) throws NotFoundException, UnauthorizedException, SchedulerException {
                SchedulerTransaction transaction = getTransaction(transactionID);
                logger.info("Rolling back transaction with id: {}", transactionID);
                transaction.rollback();
                logger.info("Finished rolling back transaction with id: {}", transactionID);
            }

            @Override
            protected void run() {
                try {
                    for (String transactionID : persistence.getTransactions()) {
                        try {
                            rollbackTransaction(transactionID);
                        } catch (NotFoundException e) {
                            logger.info("Unable to find the transaction with id {}, so it wasn't rolled back.", transactionID);
                        } catch (UnauthorizedException e) {
                            logger.error("Unable to delete transaction with id: {} using organization {} because: {}", new Object[] { transactionID, org, getStackTrace(e) });
                        } catch (Exception e) {
                            logger.error("Unable to rollback transaction because: {}", getStackTrace(e));
                        }
                    }
                } catch (SchedulerServiceDatabaseException e) {
                    logger.error("Unable to get transactions to cleanup incomplete transactions because: {}", getStackTrace(e));
                }
            }
        });
    }
    logger.info("Finished checking for incomplete transactions from a shutdown or a restart.");
}
Also used : Organization(org.opencastproject.security.api.Organization) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) Effect0(org.opencastproject.util.data.Effect0) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) Log.getHumanReadableTimeString(org.opencastproject.util.Log.getHumanReadableTimeString) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) SchedulerConflictException(org.opencastproject.scheduler.api.SchedulerConflictException) IOException(java.io.IOException) ServiceException(org.osgi.framework.ServiceException) SchedulerTransactionLockException(org.opencastproject.scheduler.api.SchedulerTransactionLockException) ConfigurationException(org.osgi.service.cm.ConfigurationException) SeriesException(org.opencastproject.series.api.SeriesException) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) ValidationException(net.fortuna.ical4j.model.ValidationException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException)

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