use of org.opencastproject.scheduler.api.SchedulerException in project opencast by opencast.
the class IngestRestService method schedule.
@POST
@Path("schedule/{wdID}")
@RestQuery(name = "schedule", description = "Schedule an event based on the given media package", pathParameters = { @RestParameter(description = "Workflow definition id", isRequired = true, name = "wdID", type = RestParameter.Type.STRING) }, restParameters = { @RestParameter(description = "The media package", isRequired = true, name = "mediaPackage", type = RestParameter.Type.TEXT) }, reponses = { @RestResponse(description = "Event scheduled", responseCode = HttpServletResponse.SC_CREATED), @RestResponse(description = "Media package not valid", responseCode = HttpServletResponse.SC_BAD_REQUEST) }, returnDescription = "")
public Response schedule(@PathParam("wdID") String wdID, MultivaluedMap<String, String> formData) {
if (StringUtils.isBlank(wdID)) {
logger.trace("workflow definition id is not specified");
return Response.status(Response.Status.BAD_REQUEST).build();
}
Map<String, String> wfConfig = getWorkflowConfig(formData);
if (StringUtils.isNotBlank(wdID)) {
wfConfig.put(CaptureParameters.INGEST_WORKFLOW_DEFINITION, wdID);
}
logger.debug("Schedule with workflow definition '{}'", wfConfig.get(WORKFLOW_DEFINITION_ID_PARAM));
String mediaPackageXml = formData.getFirst("mediaPackage");
if (StringUtils.isBlank(mediaPackageXml)) {
logger.debug("Rejected schedule without media package");
return Response.status(Status.BAD_REQUEST).build();
}
MediaPackage mp = null;
try {
mp = factory.newMediaPackageBuilder().loadFromXml(mediaPackageXml);
if (MediaPackageSupport.sanityCheck(mp).isSome()) {
throw new MediaPackageException("Insane media package");
}
} catch (MediaPackageException e) {
logger.debug("Rejected ingest with invalid media package {}", mp);
return Response.status(Status.BAD_REQUEST).build();
}
MediaPackageElement[] mediaPackageElements = mp.getElementsByFlavor(MediaPackageElements.EPISODE);
if (mediaPackageElements.length != 1) {
logger.debug("There can be only one (and exactly one) episode dublin core catalog: https://youtu.be/_J3VeogFUOs");
return Response.status(Status.BAD_REQUEST).build();
}
try {
ingestService.schedule(mp, wdID, wfConfig);
return Response.status(Status.CREATED).build();
} catch (IngestException e) {
return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
} catch (SchedulerConflictException e) {
return Response.status(Status.CONFLICT).entity(e.getMessage()).build();
} catch (NotFoundException | UnauthorizedException | SchedulerException e) {
return Response.serverError().build();
}
}
use of org.opencastproject.scheduler.api.SchedulerException in project opencast by opencast.
the class IndexServiceImpl method createEvent.
@Override
public String createEvent(EventHttpServletRequest eventHttpServletRequest) throws ParseException, IOException, MediaPackageException, IngestException, NotFoundException, SchedulerException, UnauthorizedException {
// Preconditions
if (eventHttpServletRequest.getAcl().isNone()) {
throw new IllegalArgumentException("No access control list available to create new event.");
}
if (eventHttpServletRequest.getMediaPackage().isNone()) {
throw new IllegalArgumentException("No mediapackage available to create new event.");
}
if (eventHttpServletRequest.getMetadataList().isNone()) {
throw new IllegalArgumentException("No metadata list available to create new event.");
}
if (eventHttpServletRequest.getProcessing().isNone()) {
throw new IllegalArgumentException("No processing metadata available to create new event.");
}
if (eventHttpServletRequest.getSource().isNone()) {
throw new IllegalArgumentException("No source field metadata available to create new event.");
}
// Get Workflow
String workflowTemplate = (String) eventHttpServletRequest.getProcessing().get().get("workflow");
if (workflowTemplate == null)
throw new IllegalArgumentException("No workflow template in metadata");
// Get Type of Source
SourceType type = getSourceType(eventHttpServletRequest.getSource().get());
MetadataCollection eventMetadata = eventHttpServletRequest.getMetadataList().get().getMetadataByAdapter(eventCatalogUIAdapter).get();
JSONObject sourceMetadata = (JSONObject) eventHttpServletRequest.getSource().get().get("metadata");
if (sourceMetadata != null && (type.equals(SourceType.SCHEDULE_SINGLE) || type.equals(SourceType.SCHEDULE_MULTIPLE))) {
try {
MetadataField<?> current = eventMetadata.getOutputFields().get("location");
eventMetadata.updateStringField(current, (String) sourceMetadata.get("device"));
} catch (Exception e) {
logger.warn("Unable to parse device {}", sourceMetadata.get("device"));
throw new IllegalArgumentException("Unable to parse device");
}
}
Date currentStartDate = null;
MetadataField<?> starttime = eventMetadata.getOutputFields().get(DublinCore.PROPERTY_TEMPORAL.getLocalName());
if (starttime != null && starttime.isUpdated() && starttime.getValue().isSome()) {
DCMIPeriod period = EncodingSchemeUtils.decodeMandatoryPeriod((DublinCoreValue) starttime.getValue().get());
currentStartDate = period.getStart();
}
MetadataField<?> created = eventMetadata.getOutputFields().get(DublinCore.PROPERTY_CREATED.getLocalName());
if (created == null || !created.isUpdated() || created.getValue().isNone()) {
eventMetadata.removeField(created);
MetadataField<String> newCreated = MetadataUtils.copyMetadataField(created);
if (currentStartDate != null) {
newCreated.setValue(EncodingSchemeUtils.encodeDate(currentStartDate, Precision.Second).getValue());
} else {
newCreated.setValue(EncodingSchemeUtils.encodeDate(new Date(), Precision.Second).getValue());
}
eventMetadata.addField(newCreated);
}
// Get presenter usernames for use as technical presenters
Set<String> presenterUsernames = new HashSet<>();
Opt<Set<String>> technicalPresenters = updatePresenters(eventMetadata);
if (technicalPresenters.isSome()) {
presenterUsernames = technicalPresenters.get();
}
eventHttpServletRequest.getMetadataList().get().add(eventCatalogUIAdapter, eventMetadata);
updateMediaPackageMetadata(eventHttpServletRequest.getMediaPackage().get(), eventHttpServletRequest.getMetadataList().get());
DublinCoreCatalog dc = getDublinCoreCatalog(eventHttpServletRequest);
String captureAgentId = null;
TimeZone tz = null;
org.joda.time.DateTime start = null;
org.joda.time.DateTime end = null;
long duration = 0L;
Properties caProperties = new Properties();
RRule rRule = null;
if (sourceMetadata != null && (type.equals(SourceType.SCHEDULE_SINGLE) || type.equals(SourceType.SCHEDULE_MULTIPLE))) {
Properties configuration;
try {
captureAgentId = (String) sourceMetadata.get("device");
configuration = captureAgentStateService.getAgentConfiguration((String) sourceMetadata.get("device"));
} catch (Exception e) {
logger.warn("Unable to parse device {}: because: {}", sourceMetadata.get("device"), getStackTrace(e));
throw new IllegalArgumentException("Unable to parse device");
}
String durationString = (String) sourceMetadata.get("duration");
if (StringUtils.isBlank(durationString))
throw new IllegalArgumentException("No duration in source metadata");
// Create timezone based on CA's reported TZ.
String agentTimeZone = configuration.getProperty("capture.device.timezone");
if (StringUtils.isNotBlank(agentTimeZone)) {
tz = TimeZone.getTimeZone(agentTimeZone);
dc.set(DublinCores.OC_PROPERTY_AGENT_TIMEZONE, tz.getID());
} else {
// No timezone was present, assume the serve's local timezone.
tz = TimeZone.getDefault();
logger.debug("The field 'capture.device.timezone' has not been set in the agent configuration. The default server timezone will be used.");
}
org.joda.time.DateTime now = new org.joda.time.DateTime(DateTimeZone.UTC);
start = now.withMillis(DateTimeSupport.fromUTC((String) sourceMetadata.get("start")));
end = now.withMillis(DateTimeSupport.fromUTC((String) sourceMetadata.get("end")));
duration = Long.parseLong(durationString);
DublinCoreValue period = EncodingSchemeUtils.encodePeriod(new DCMIPeriod(start.toDate(), start.plus(duration).toDate()), Precision.Second);
String inputs = (String) sourceMetadata.get("inputs");
caProperties.putAll(configuration);
dc.set(DublinCore.PROPERTY_TEMPORAL, period);
caProperties.put(CaptureParameters.CAPTURE_DEVICE_NAMES, inputs);
}
if (type.equals(SourceType.SCHEDULE_MULTIPLE)) {
rRule = new RRule((String) sourceMetadata.get("rrule"));
}
Map<String, String> configuration = new HashMap<>();
if (eventHttpServletRequest.getProcessing().get().get("configuration") != null) {
configuration = new HashMap<>((JSONObject) eventHttpServletRequest.getProcessing().get().get("configuration"));
}
for (Entry<String, String> entry : configuration.entrySet()) {
caProperties.put(WORKFLOW_CONFIG_PREFIX.concat(entry.getKey()), entry.getValue());
}
caProperties.put(CaptureParameters.INGEST_WORKFLOW_DEFINITION, workflowTemplate);
eventHttpServletRequest.setMediaPackage(authorizationService.setAcl(eventHttpServletRequest.getMediaPackage().get(), AclScope.Episode, eventHttpServletRequest.getAcl().get()).getA());
MediaPackage mediaPackage;
switch(type) {
case UPLOAD:
case UPLOAD_LATER:
eventHttpServletRequest.setMediaPackage(updateDublincCoreCatalog(eventHttpServletRequest.getMediaPackage().get(), dc));
configuration.put("workflowDefinitionId", workflowTemplate);
WorkflowInstance ingest = ingestService.ingest(eventHttpServletRequest.getMediaPackage().get(), workflowTemplate, configuration);
return eventHttpServletRequest.getMediaPackage().get().getIdentifier().compact();
case SCHEDULE_SINGLE:
mediaPackage = updateDublincCoreCatalog(eventHttpServletRequest.getMediaPackage().get(), dc);
eventHttpServletRequest.setMediaPackage(mediaPackage);
try {
schedulerService.addEvent(start.toDate(), start.plus(duration).toDate(), captureAgentId, presenterUsernames, mediaPackage, configuration, (Map) caProperties, Opt.<Boolean>none(), Opt.<String>none(), SchedulerService.ORIGIN);
} finally {
for (MediaPackageElement mediaPackageElement : mediaPackage.getElements()) {
try {
workspace.delete(mediaPackage.getIdentifier().toString(), mediaPackageElement.getIdentifier());
} catch (NotFoundException | IOException e) {
logger.warn("Failed to delete media package element", e);
}
}
}
return mediaPackage.getIdentifier().compact();
case SCHEDULE_MULTIPLE:
List<Period> periods = schedulerService.calculatePeriods(rRule, start.toDate(), end.toDate(), duration, tz);
Map<String, Period> scheduled = new LinkedHashMap<>();
scheduled = schedulerService.addMultipleEvents(rRule, start.toDate(), end.toDate(), duration, tz, captureAgentId, presenterUsernames, eventHttpServletRequest.getMediaPackage().get(), configuration, (Map) caProperties, Opt.none(), Opt.none(), SchedulerService.ORIGIN);
return StringUtils.join(scheduled.keySet(), ",");
default:
logger.warn("Unknown source type {}", type);
throw new IllegalArgumentException("Unknown source type");
}
}
use of org.opencastproject.scheduler.api.SchedulerException in project opencast by opencast.
the class IndexServiceImpl method updateEventMetadata.
@Override
public MetadataList updateEventMetadata(String id, MetadataList metadataList, AbstractSearchIndex index) throws 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);
Opt<Set<String>> presenters = Opt.none();
Opt<MetadataCollection> eventCatalog = metadataList.getMetadataByAdapter(getCommonEventCatalogUIAdapter());
if (eventCatalog.isSome()) {
presenters = updatePresenters(eventCatalog.get());
}
updateMediaPackageMetadata(mediaPackage, metadataList);
switch(getEventSource(event)) {
case WORKFLOW:
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());
}
try {
WorkflowInstance instance = workflowInstance.get();
instance.setMediaPackage(mediaPackage);
updateWorkflowInstance(instance);
} catch (WorkflowException e) {
logger.error("Unable to update workflow event {} with metadata {} because {}", id, RestUtils.getJsonStringSilent(metadataList.toJSON()), getStackTrace(e));
throw new IndexServiceException("Unable to update workflow event " + id);
}
break;
case ARCHIVE:
assetManager.takeSnapshot(DEFAULT_OWNER, mediaPackage);
break;
case SCHEDULE:
try {
schedulerService.updateEvent(id, Opt.<Date>none(), Opt.<Date>none(), Opt.<String>none(), presenters, Opt.some(mediaPackage), Opt.<Map<String, String>>none(), Opt.<Map<String, String>>none(), Opt.<Opt<Boolean>>none(), SchedulerService.ORIGIN);
} catch (SchedulerException e) {
logger.error("Unable to update scheduled event {} with metadata {} because {}", id, RestUtils.getJsonStringSilent(metadataList.toJSON()), getStackTrace(e));
throw new IndexServiceException("Unable to update scheduled event " + id);
}
break;
default:
logger.error("Unkown event source!");
}
return metadataList;
}
use of org.opencastproject.scheduler.api.SchedulerException in project opencast by opencast.
the class IndexServiceImpl method removeCatalogByFlavor.
@Override
public void removeCatalogByFlavor(Event event, MediaPackageElementFlavor flavor) throws IndexServiceException, NotFoundException, UnauthorizedException {
MediaPackage mediaPackage = getEventMediapackage(event);
Catalog[] catalogs = mediaPackage.getCatalogs(flavor);
if (catalogs.length == 0) {
throw new NotFoundException(String.format("Cannot find a catalog with flavor '%s' for event with id '%s'.", flavor.toString(), event.getIdentifier()));
}
for (Catalog catalog : catalogs) {
mediaPackage.remove(catalog);
}
switch(getEventSource(event)) {
case WORKFLOW:
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());
}
try {
WorkflowInstance instance = workflowInstance.get();
instance.setMediaPackage(mediaPackage);
updateWorkflowInstance(instance);
} catch (WorkflowException e) {
logger.error("Unable to remove catalog with flavor {} by updating workflow event {} because {}", flavor, event.getIdentifier(), getStackTrace(e));
throw new IndexServiceException("Unable to update workflow event " + event.getIdentifier());
}
break;
case ARCHIVE:
assetManager.takeSnapshot(DEFAULT_OWNER, mediaPackage);
break;
case SCHEDULE:
try {
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);
} catch (SchedulerException e) {
logger.error("Unable to remove catalog with flavor {} by updating scheduled event {} because {}", flavor, event.getIdentifier(), getStackTrace(e));
throw new IndexServiceException("Unable to update scheduled event " + event.getIdentifier());
}
break;
default:
throw new IndexServiceException(String.format("Unable to handle event source type '%s'", getEventSource(event)));
}
}
use of org.opencastproject.scheduler.api.SchedulerException in project opencast by opencast.
the class IndexServiceImpl method getEventMediapackage.
@Override
public MediaPackage getEventMediapackage(Event event) throws IndexServiceException {
switch(getEventSource(event)) {
case WORKFLOW:
Opt<WorkflowInstance> currentWorkflowInstance = getCurrentWorkflowInstance(event.getIdentifier());
if (currentWorkflowInstance.isNone()) {
logger.error("No workflow instance for event {} found!", event.getIdentifier());
throw new IndexServiceException("No workflow instance found for event " + event.getIdentifier());
}
return currentWorkflowInstance.get().getMediaPackage();
case ARCHIVE:
final AQueryBuilder q = assetManager.createQuery();
final AResult r = q.select(q.snapshot()).where(q.mediaPackageId(event.getIdentifier()).and(q.version().isLatest())).run();
if (r.getSize() > 0) {
logger.debug("Found event in archive with id {}", event.getIdentifier());
return enrich(r).getSnapshots().head2().getMediaPackage();
}
logger.error("No event with id {} found from archive!", event.getIdentifier());
throw new IndexServiceException("No archived event found with id " + event.getIdentifier());
case SCHEDULE:
try {
MediaPackage mediaPackage = schedulerService.getMediaPackage(event.getIdentifier());
logger.debug("Found event in scheduler with id {}", event.getIdentifier());
return mediaPackage;
} catch (NotFoundException e) {
logger.error("No scheduled event with id {} found!", event.getIdentifier());
throw new IndexServiceException(e.getMessage(), e);
} catch (UnauthorizedException e) {
logger.error("Unauthorized to get event with id {} from scheduler because {}", event.getIdentifier(), getStackTrace(e));
throw new IndexServiceException(e.getMessage(), e);
} catch (SchedulerException e) {
logger.error("Unable to get event with id {} from scheduler because {}", event.getIdentifier(), getStackTrace(e));
throw new IndexServiceException(e.getMessage(), e);
}
default:
throw new IllegalStateException("Unknown event type!");
}
}
Aggregations