use of org.opencastproject.security.api.UnauthorizedException in project opencast by opencast.
the class SchedulerServiceRemoteImpl method getTechnicalMetadata.
@Override
public TechnicalMetadata getTechnicalMetadata(String eventId) throws NotFoundException, UnauthorizedException, SchedulerException {
HttpGet get = new HttpGet(eventId.concat("/technical.json"));
HttpResponse response = getResponse(get, SC_OK, SC_NOT_FOUND, SC_UNAUTHORIZED);
try {
if (response != null) {
if (SC_NOT_FOUND == response.getStatusLine().getStatusCode()) {
throw new NotFoundException("Event with id '" + eventId + "' not found on remote scheduler service!");
} else if (SC_UNAUTHORIZED == response.getStatusLine().getStatusCode()) {
logger.info("Unauthorized to get the technical metadata of the event {}.", eventId);
throw new UnauthorizedException("Unauthorized to get the technical metadata of the event " + eventId);
} else {
String technicalMetadataJson = EntityUtils.toString(response.getEntity(), UTF_8);
JSONObject json = (JSONObject) parser.parse(technicalMetadataJson);
final String recordingId = (String) json.get("id");
final Date start = new Date(DateTimeSupport.fromUTC((String) json.get("start")));
final Date end = new Date(DateTimeSupport.fromUTC((String) json.get("end")));
final boolean optOut = (Boolean) json.get("optOut");
final String location = (String) json.get("location");
final Set<String> presenters = new HashSet<>();
JSONArray presentersArr = (JSONArray) json.get("presenters");
for (int i = 0; i < presentersArr.size(); i++) {
presenters.add((String) presentersArr.get(i));
}
final Map<String, String> wfProperties = new HashMap<>();
JSONObject wfPropertiesObj = (JSONObject) json.get("wfProperties");
Set<Entry<String, String>> entrySet = wfPropertiesObj.entrySet();
for (Entry<String, String> entry : entrySet) {
wfProperties.put(entry.getKey(), entry.getValue());
}
final Map<String, String> agentConfig = new HashMap<>();
JSONObject agentConfigObj = (JSONObject) json.get("agentConfig");
entrySet = agentConfigObj.entrySet();
for (Entry<String, String> entry : entrySet) {
agentConfig.put(entry.getKey(), entry.getValue());
}
String status = (String) json.get("state");
String lastHeard = (String) json.get("lastHeardFrom");
Recording recording = null;
if (StringUtils.isNotBlank(status) && StringUtils.isNotBlank(lastHeard)) {
recording = new RecordingImpl(recordingId, status, DateTimeSupport.fromUTC(lastHeard));
}
final Opt<Recording> recordingOpt = Opt.nul(recording);
logger.info("Successfully get the technical metadata of event '{}' from the remote scheduler service", eventId);
return new TechnicalMetadataImpl(recordingId, location, start, end, optOut, presenters, wfProperties, agentConfig, recordingOpt);
}
}
} catch (NotFoundException e) {
throw e;
} catch (UnauthorizedException e) {
throw e;
} catch (Exception e) {
throw new SchedulerException("Unable to parse the technical metadata from remote scheduler service: " + e);
} finally {
closeConnection(response);
}
throw new SchedulerException("Unable to get the technical metadata from remote scheduler service");
}
use of org.opencastproject.security.api.UnauthorizedException in project opencast by opencast.
the class SchedulerServiceRemoteImpl method getWorkflowConfig.
@Override
public Map<String, String> getWorkflowConfig(String eventId) throws NotFoundException, UnauthorizedException, SchedulerException {
HttpGet get = new HttpGet(eventId.concat("/workflow.properties"));
HttpResponse response = getResponse(get, SC_OK, SC_NOT_FOUND, SC_UNAUTHORIZED);
try {
if (response != null) {
if (SC_NOT_FOUND == response.getStatusLine().getStatusCode()) {
throw new NotFoundException("Event workflow configuration '" + eventId + "' not found on remote scheduler service!");
} else if (SC_UNAUTHORIZED == response.getStatusLine().getStatusCode()) {
logger.info("Unauthorized to get workflow config of the event {}.", eventId);
throw new UnauthorizedException("Unauthorized to get workflow config of the event " + eventId);
} else {
Properties properties = new Properties();
properties.load(response.getEntity().getContent());
logger.info("Successfully get event workflow configuration {} from the remote scheduler service", eventId);
return new HashMap<String, String>((Map) properties);
}
}
} catch (NotFoundException e) {
throw e;
} catch (UnauthorizedException e) {
throw e;
} catch (Exception e) {
throw new SchedulerException("Unable to parse event workflow configuration from remote scheduler service: " + e);
} finally {
closeConnection(response);
}
throw new SchedulerException("Unable to get event workflow configuration from remote scheduler service");
}
use of org.opencastproject.security.api.UnauthorizedException in project opencast by opencast.
the class SchedulerRestService method getConflictingEventsXml.
@GET
@Produces(MediaType.TEXT_XML)
@Path("conflicts.xml")
@RestQuery(name = "conflictingrecordingsasxml", description = "Searches for conflicting recordings based on parameters", returnDescription = "Returns NO CONTENT if no recordings are in conflict within specified period or list of conflicting recordings in XML", restParameters = { @RestParameter(name = "agent", description = "Device identifier for which conflicts will be searched", isRequired = true, type = Type.STRING), @RestParameter(name = "start", description = "Start time of conflicting period, in milliseconds", isRequired = true, type = Type.INTEGER), @RestParameter(name = "end", description = "End time of conflicting period, in milliseconds", isRequired = true, type = Type.INTEGER), @RestParameter(name = "rrule", description = "Rule for recurrent conflicting, specified as: \"FREQ=WEEKLY;BYDAY=day(s);BYHOUR=hour;BYMINUTE=minute\". FREQ is required. BYDAY may include one or more (separated by commas) of the following: SU,MO,TU,WE,TH,FR,SA.", isRequired = false, type = Type.STRING), @RestParameter(name = "duration", description = "If recurrence rule is specified duration of each conflicting period, in milliseconds", isRequired = false, type = Type.INTEGER), @RestParameter(name = "timezone", description = "The timezone of the capture device", isRequired = false, type = Type.STRING) }, reponses = { @RestResponse(responseCode = HttpServletResponse.SC_NO_CONTENT, description = "No conflicting events found"), @RestResponse(responseCode = HttpServletResponse.SC_OK, description = "Found conflicting events, returned in body of response"), @RestResponse(responseCode = HttpServletResponse.SC_BAD_REQUEST, description = "Missing or invalid parameters") })
public Response getConflictingEventsXml(@QueryParam("agent") String device, @QueryParam("rrule") String rrule, @QueryParam("start") Long startDate, @QueryParam("end") Long endDate, @QueryParam("duration") Long duration, @QueryParam("timezone") String timezone) throws UnauthorizedException {
if (StringUtils.isBlank(device) || startDate == null || endDate == null) {
logger.info("Either agent, start date or end date were not specified");
return Response.status(Status.BAD_REQUEST).build();
}
RRule rule = null;
if (StringUtils.isNotBlank(rrule)) {
if (duration == null || StringUtils.isBlank(timezone)) {
logger.info("Either duration or timezone were not specified");
return Response.status(Status.BAD_REQUEST).build();
}
try {
rule = new RRule(rrule);
rule.validate();
} catch (Exception e) {
logger.info("Unable to parse rrule {}: {}", rrule, getMessage(e));
return Response.status(Status.BAD_REQUEST).build();
}
if (!Arrays.asList(TimeZone.getAvailableIDs()).contains(timezone)) {
logger.info("Unable to parse timezone: {}", timezone);
return Response.status(Status.BAD_REQUEST).build();
}
}
Date start = new DateTime(startDate).toDateTime(DateTimeZone.UTC).toDate();
Date end = new DateTime(endDate).toDateTime(DateTimeZone.UTC).toDate();
try {
List<MediaPackage> events;
if (StringUtils.isNotBlank(rrule)) {
events = service.findConflictingEvents(device, rule, start, end, duration, TimeZone.getTimeZone(timezone));
} else {
events = service.findConflictingEvents(device, start, end);
}
if (!events.isEmpty()) {
return Response.ok(MediaPackageParser.getArrayAsXml(events)).build();
} else {
return Response.noContent().build();
}
} catch (UnauthorizedException e) {
throw e;
} catch (Exception e) {
logger.error("Unable to find conflicting events for {}, {}, {}, {}, {}: {}", device, rrule, start, end, duration, getStackTrace(e));
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
}
use of org.opencastproject.security.api.UnauthorizedException 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);
}
}
}
use of org.opencastproject.security.api.UnauthorizedException in project opencast by opencast.
the class WorkflowServiceImpl method update.
/**
* {@inheritDoc}
*
* @see org.opencastproject.workflow.api.WorkflowService#update(org.opencastproject.workflow.api.WorkflowInstance)
*/
@Override
public void update(final WorkflowInstance workflowInstance) throws WorkflowException, UnauthorizedException {
final Lock lock = updateLock.get(workflowInstance.getId());
lock.lock();
try {
WorkflowInstance originalWorkflowInstance = null;
try {
originalWorkflowInstance = getWorkflowById(workflowInstance.getId());
} catch (NotFoundException e) {
// That's fine, it's a new workflow instance
}
if (originalWorkflowInstance != null) {
try {
assertPermission(originalWorkflowInstance, Permissions.Action.WRITE.toString());
} catch (MediaPackageException e) {
throw new WorkflowParsingException(e);
}
}
MediaPackage updatedMediaPackage = null;
try {
// Before we persist this, extract the metadata
updatedMediaPackage = workflowInstance.getMediaPackage();
populateMediaPackageMetadata(updatedMediaPackage);
String seriesId = updatedMediaPackage.getSeries();
if (seriesId != null && workflowInstance.getCurrentOperation() != null) {
// If the mediapackage contains a series, find the series ACLs and add the security information to the
// mediapackage
AccessControlList acl = seriesService.getSeriesAccessControl(seriesId);
Option<AccessControlList> activeSeriesAcl = authorizationService.getAcl(updatedMediaPackage, AclScope.Series);
if (activeSeriesAcl.isNone() || !AccessControlUtil.equals(activeSeriesAcl.get(), acl))
authorizationService.setAcl(updatedMediaPackage, AclScope.Series, acl);
}
} catch (SeriesException e) {
throw new WorkflowDatabaseException(e);
} catch (NotFoundException e) {
logger.warn("Metadata for mediapackage {} could not be updated because it wasn't found", updatedMediaPackage, e);
} catch (Exception e) {
logger.error("Metadata for mediapackage {} could not be updated", updatedMediaPackage, e);
}
// Synchronize the job status with the workflow
WorkflowState workflowState = workflowInstance.getState();
String xml;
try {
xml = WorkflowParser.toXml(workflowInstance);
} catch (Exception e) {
// Can't happen, since we are converting from an in-memory object
throw new IllegalStateException("In-memory workflow instance could not be serialized", e);
}
Job job = null;
try {
job = serviceRegistry.getJob(workflowInstance.getId());
job.setPayload(xml);
// Synchronize workflow and job state
switch(workflowState) {
case FAILED:
job.setStatus(Status.FAILED);
break;
case FAILING:
break;
case INSTANTIATED:
job.setDispatchable(true);
job.setStatus(Status.QUEUED);
break;
case PAUSED:
job.setStatus(Status.PAUSED);
break;
case RUNNING:
job.setStatus(Status.RUNNING);
break;
case STOPPED:
job.setStatus(Status.CANCELED);
break;
case SUCCEEDED:
job.setStatus(Status.FINISHED);
break;
default:
throw new IllegalStateException("Found a workflow state that is not handled");
}
} catch (ServiceRegistryException e) {
logger.error(e, "Unable to read workflow job %s from service registry", workflowInstance.getId());
throw new WorkflowDatabaseException(e);
} catch (NotFoundException e) {
logger.error("Job for workflow %s not found in service registry", workflowInstance.getId());
throw new WorkflowDatabaseException(e);
}
// Update both workflow and workflow job
try {
job = serviceRegistry.updateJob(job);
messageSender.sendObjectMessage(WorkflowItem.WORKFLOW_QUEUE, MessageSender.DestinationType.Queue, WorkflowItem.updateInstance(workflowInstance));
index(workflowInstance);
} catch (ServiceRegistryException e) {
logger.error("Update of workflow job %s in the service registry failed, service registry and workflow index may be out of sync", workflowInstance.getId());
throw new WorkflowDatabaseException(e);
} catch (NotFoundException e) {
logger.error("Job for workflow %s not found in service registry", workflowInstance.getId());
throw new WorkflowDatabaseException(e);
} catch (Exception e) {
logger.error("Update of workflow job %s in the service registry failed, service registry and workflow index may be out of sync", job.getId());
throw new WorkflowException(e);
}
if (workflowStatsCollect) {
workflowsStatistics.updateWorkflow(getBeanStatistics(), getHoldWorkflows());
}
try {
WorkflowInstance clone = WorkflowParser.parseWorkflowInstance(WorkflowParser.toXml(workflowInstance));
fireListeners(originalWorkflowInstance, clone);
} catch (Exception e) {
// Can't happen, since we are converting from an in-memory object
throw new IllegalStateException("In-memory workflow instance could not be serialized", e);
}
} finally {
lock.unlock();
}
}
Aggregations