Search in sources :

Example 66 with SchedulerException

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

the class SchedulerRestService method updateEvent.

@PUT
@Path("{id}")
@RestQuery(name = "updaterecordings", description = "Updates specified event", returnDescription = "Status OK is returned if event was successfully updated, NOT FOUND if specified event does not exist or BAD REQUEST if data is missing or invalid", pathParameters = { @RestParameter(name = "id", description = "ID of event to be updated", isRequired = true, type = Type.STRING) }, restParameters = { @RestParameter(name = "start", isRequired = false, description = "Updated start date for event", type = Type.INTEGER), @RestParameter(name = "end", isRequired = false, description = "Updated end date for event", type = Type.INTEGER), @RestParameter(name = "agent", isRequired = false, description = "Updated agent for event", type = Type.STRING), @RestParameter(name = "users", isRequired = false, type = Type.STRING, description = "Updated comma separated list of user ids (speakers/lecturers) for the event"), @RestParameter(name = "mediaPackage", isRequired = false, description = "Updated media package for event", type = Type.TEXT), @RestParameter(name = "wfproperties", isRequired = false, description = "Workflow configuration properties", type = Type.TEXT), @RestParameter(name = "agentparameters", isRequired = false, description = "Updated Capture Agent properties", type = Type.TEXT), @RestParameter(name = "updateOptOut", isRequired = true, defaultValue = "false", description = "Whether to update the opt out status", type = Type.BOOLEAN), @RestParameter(name = "optOut", isRequired = false, description = "Update opt out status", type = Type.BOOLEAN), @RestParameter(name = "origin", isRequired = false, description = "The origin", type = Type.STRING) }, reponses = { @RestResponse(responseCode = HttpServletResponse.SC_OK, description = "Event was successfully updated"), @RestResponse(responseCode = HttpServletResponse.SC_NOT_FOUND, description = "Event with specified ID does not exist"), @RestResponse(responseCode = HttpServletResponse.SC_CONFLICT, description = "Unable to update event, conflicting events found (ConflicsFound)"), @RestResponse(responseCode = HttpServletResponse.SC_CONFLICT, description = "Unable to update event, event locked by a transaction (TransactionLock)"), @RestResponse(responseCode = HttpServletResponse.SC_FORBIDDEN, description = "Event with specified ID cannot be updated"), @RestResponse(responseCode = HttpServletResponse.SC_UNAUTHORIZED, description = "You do not have permission to update the event. Maybe you need to authenticate."), @RestResponse(responseCode = HttpServletResponse.SC_BAD_REQUEST, description = "Data is missing or invalid") })
public Response updateEvent(@PathParam("id") String eventID, @FormParam("start") Long startTime, @FormParam("end") Long endTime, @FormParam("agent") String agentId, @FormParam("users") String users, @FormParam("mediaPackage") String mediaPackageXml, @FormParam("wfproperties") String workflowProperties, @FormParam("agentparameters") String agentParameters, @FormParam("updateOptOut") boolean updateOptOut, @FormParam("optOut") Boolean optOutBoolean, @FormParam("origin") String origin) throws UnauthorizedException {
    if (StringUtils.isBlank(origin))
        origin = SchedulerService.ORIGIN;
    if (startTime != null) {
        if (startTime < 0) {
            logger.debug("Cannot add event with negative start time ({} < 0)", startTime);
            return RestUtil.R.badRequest("Cannot add event with negative start time");
        }
        if (endTime != null && endTime <= startTime) {
            logger.debug("Cannot add event without proper end time ({} <= {})", startTime, endTime);
            return RestUtil.R.badRequest("Cannot add event without proper end time");
        }
    }
    MediaPackage mediaPackage = null;
    if (StringUtils.isNotBlank(mediaPackageXml)) {
        try {
            mediaPackage = MediaPackageParser.getFromXml(mediaPackageXml);
        } catch (Exception e) {
            logger.debug("Could not parse media packagey", e);
            return Response.status(Status.BAD_REQUEST).build();
        }
    }
    Map<String, String> caProperties = null;
    if (StringUtils.isNotBlank(agentParameters)) {
        try {
            Properties prop = parseProperties(agentParameters);
            caProperties = new HashMap<>();
            caProperties.putAll((Map) prop);
        } catch (Exception e) {
            logger.debug("Could not parse capture agent properties: {}", agentParameters, e);
            return Response.status(Status.BAD_REQUEST).build();
        }
    }
    Map<String, String> wfProperties = null;
    if (StringUtils.isNotBlank(workflowProperties)) {
        try {
            Properties prop = parseProperties(workflowProperties);
            wfProperties = new HashMap<>();
            wfProperties.putAll((Map) prop);
        } catch (IOException e) {
            logger.debug("Could not parse workflow configuration properties: {}", workflowProperties, e);
            return Response.status(Status.BAD_REQUEST).build();
        }
    }
    Set<String> userIds = null;
    String[] ids = StringUtils.split(StringUtils.trimToNull(users), ",");
    if (ids != null) {
        userIds = new HashSet<>(Arrays.asList(ids));
    }
    Date startDate = null;
    if (startTime != null) {
        startDate = new DateTime(startTime).toDateTime(DateTimeZone.UTC).toDate();
    }
    Date endDate = null;
    if (endTime != null) {
        endDate = new DateTime(endTime).toDateTime(DateTimeZone.UTC).toDate();
    }
    final Opt<Opt<Boolean>> optOut;
    if (updateOptOut) {
        optOut = Opt.some(Opt.nul(optOutBoolean));
    } else {
        optOut = Opt.none();
    }
    try {
        service.updateEvent(eventID, Opt.nul(startDate), Opt.nul(endDate), Opt.nul(StringUtils.trimToNull(agentId)), Opt.nul(userIds), Opt.nul(mediaPackage), Opt.nul(wfProperties), Opt.nul(caProperties), optOut, origin);
        return Response.ok().build();
    } catch (SchedulerTransactionLockException | SchedulerConflictException e) {
        return Response.status(Status.CONFLICT).entity(generateErrorResponse(e)).type(MediaType.APPLICATION_JSON).build();
    } catch (SchedulerException e) {
        logger.warn("Error updating event with id '{}'", eventID, e);
        return Response.status(Status.FORBIDDEN).build();
    } catch (NotFoundException e) {
        logger.info("Event with id '{}' does not exist.", eventID);
        return Response.status(Status.NOT_FOUND).build();
    } catch (UnauthorizedException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Unable to update event with id '{}'", eventID, e);
        return Response.serverError().build();
    }
}
Also used : SchedulerException(org.opencastproject.scheduler.api.SchedulerException) SchedulerConflictException(org.opencastproject.scheduler.api.SchedulerConflictException) NotFoundException(org.opencastproject.util.NotFoundException) IOException(java.io.IOException) Properties(java.util.Properties) 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) Date(java.util.Date) DateTime(org.joda.time.DateTime) Opt(com.entwinemedia.fn.data.Opt) SchedulerTransactionLockException(org.opencastproject.scheduler.api.SchedulerTransactionLockException) MediaPackage(org.opencastproject.mediapackage.MediaPackage) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) Path(javax.ws.rs.Path) RestQuery(org.opencastproject.util.doc.rest.RestQuery) PUT(javax.ws.rs.PUT)

Example 67 with SchedulerException

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

the class SchedulerServiceImplTest method testEndDateBeforeStartDate.

@Test
public void testEndDateBeforeStartDate() throws Exception {
    Date start = new Date();
    Date end = new Date(System.currentTimeMillis() + 60000);
    String captureDeviceID = "demo";
    String seriesId = "series1";
    Set<String> userIds = new HashSet<>();
    userIds.add("user1");
    userIds.add("user2");
    MediaPackage mp = generateEvent(Opt.<String>none());
    mp.setSeries(seriesId);
    DublinCoreCatalog event = generateEvent(captureDeviceID, start, end);
    addDublinCore(Opt.<String>none(), mp, event);
    Map<String, String> caProperties = generateCaptureAgentMetadata("demo");
    EasyMock.reset(seriesService);
    EasyMock.expect(seriesService.getSeries(seriesId)).andThrow(new NotFoundException()).once();
    EasyMock.expect(seriesService.isOptOut(EasyMock.anyString())).andReturn(false).anyTimes();
    EasyMock.replay(seriesService);
    try {
        // Store event
        schedSvc.addEvent(end, start, captureDeviceID, userIds, mp, wfProperties, caProperties, Opt.<Boolean>none(), Opt.<String>none(), SchedulerService.ORIGIN);
        fail("Unable to detect end date being before start date during creation of event");
    } catch (IllegalArgumentException e) {
        assertNotNull(e);
    }
    // Store
    schedSvc.addEvent(start, end, captureDeviceID, userIds, mp, wfProperties, caProperties, Opt.<Boolean>none(), Opt.<String>none(), SchedulerService.ORIGIN);
    try {
        // Update end date before start date
        schedSvc.updateEvent(mp.getIdentifier().compact(), Opt.some(end), Opt.some(start), Opt.<String>none(), Opt.<Set<String>>none(), Opt.<MediaPackage>none(), Opt.<Map<String, String>>none(), Opt.<Map<String, String>>none(), Opt.<Opt<Boolean>>none(), SchedulerService.ORIGIN);
        fail("Unable to detect end date being before start date during update of event");
    } catch (SchedulerException e) {
        assertNotNull(e);
    }
}
Also used : SchedulerException(org.opencastproject.scheduler.api.SchedulerException) MediaPackage(org.opencastproject.mediapackage.MediaPackage) NotFoundException(org.opencastproject.util.NotFoundException) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog) Date(java.util.Date) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 68 with SchedulerException

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

the class SchedulerServiceRemoteImpl method addMultipleEvents.

@Override
public Map<String, Period> addMultipleEvents(RRule rRule, Date start, Date end, Long duration, TimeZone tz, String captureAgentId, Set<String> userIds, MediaPackage templateMp, Map<String, String> wfProperties, Map<String, String> caMetadata, Opt<Boolean> optOut, Opt<String> schedulingSource, String modificationOrigin) throws UnauthorizedException, SchedulerConflictException, SchedulerTransactionLockException, SchedulerException {
    HttpPost post = new HttpPost("/");
    logger.debug("Start adding a new events through remote Schedule Service");
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("rrule", rRule.getValue()));
    params.add(new BasicNameValuePair("start", Long.toString(start.getTime())));
    params.add(new BasicNameValuePair("end", Long.toString(end.getTime())));
    params.add(new BasicNameValuePair("duration", Long.toString(duration)));
    params.add(new BasicNameValuePair("tz", tz.toZoneId().getId()));
    params.add(new BasicNameValuePair("agent", captureAgentId));
    params.add(new BasicNameValuePair("users", StringUtils.join(userIds, ",")));
    params.add(new BasicNameValuePair("templateMp", MediaPackageParser.getAsXml(templateMp)));
    params.add(new BasicNameValuePair("wfproperties", toPropertyString(wfProperties)));
    params.add(new BasicNameValuePair("agentparameters", toPropertyString(caMetadata)));
    if (optOut.isSome())
        params.add(new BasicNameValuePair("optOut", Boolean.toString(optOut.get())));
    if (schedulingSource.isSome())
        params.add(new BasicNameValuePair("source", schedulingSource.get()));
    params.add(new BasicNameValuePair("origin", modificationOrigin));
    post.setEntity(new UrlEncodedFormEntity(params, UTF_8));
    String eventId = templateMp.getIdentifier().compact();
    HttpResponse response = getResponse(post, SC_CREATED, SC_UNAUTHORIZED, SC_CONFLICT);
    try {
        if (response != null && SC_CREATED == response.getStatusLine().getStatusCode()) {
            logger.info("Successfully added events to the scheduler service");
            return null;
        } else if (response != null && SC_CONFLICT == response.getStatusLine().getStatusCode()) {
            String errorJson = EntityUtils.toString(response.getEntity(), UTF_8);
            JSONObject json = (JSONObject) parser.parse(errorJson);
            JSONObject error = (JSONObject) json.get("error");
            String errorCode = (String) error.get("code");
            if (SchedulerTransactionLockException.ERROR_CODE.equals(errorCode)) {
                logger.info("Event is locked by a transaction, unable to add event based on {}", eventId);
                throw new SchedulerTransactionLockException("Event is locked by a transaction, unable to add event " + eventId);
            } else if (SchedulerConflictException.ERROR_CODE.equals(errorCode)) {
                logger.info("Conflicting events found when adding event based on {}", eventId);
                throw new SchedulerConflictException("Conflicting events found when adding event based on" + eventId);
            } else {
                throw new SchedulerException("Unexpected error code " + errorCode);
            }
        } else if (response != null && SC_UNAUTHORIZED == response.getStatusLine().getStatusCode()) {
            logger.info("Unauthorized to create the event");
            throw new UnauthorizedException("Unauthorized to create the event");
        } else {
            throw new SchedulerException("Unable to add event " + eventId + " to the scheduler service");
        }
    } catch (UnauthorizedException e) {
        throw e;
    } catch (SchedulerTransactionLockException e) {
        throw e;
    } catch (SchedulerConflictException e) {
        throw e;
    } catch (Exception e) {
        throw new SchedulerException("Unable to add event " + eventId + " to the scheduler service: " + e);
    } finally {
        closeConnection(response);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) ArrayList(java.util.ArrayList) SchedulerConflictException(org.opencastproject.scheduler.api.SchedulerConflictException) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) SchedulerTransactionLockException(org.opencastproject.scheduler.api.SchedulerTransactionLockException) SchedulerConflictException(org.opencastproject.scheduler.api.SchedulerConflictException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) JSONObject(org.json.simple.JSONObject) SchedulerTransactionLockException(org.opencastproject.scheduler.api.SchedulerTransactionLockException) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException)

Example 69 with SchedulerException

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

the class SchedulerServiceRemoteImpl method findConflictingEvents.

@Override
public List<MediaPackage> findConflictingEvents(String captureDeviceID, Date startDate, Date endDate) throws UnauthorizedException, SchedulerException {
    List<NameValuePair> queryStringParams = new ArrayList<NameValuePair>();
    queryStringParams.add(new BasicNameValuePair("agent", captureDeviceID));
    queryStringParams.add(new BasicNameValuePair("start", Long.toString(startDate.getTime())));
    queryStringParams.add(new BasicNameValuePair("end", Long.toString(endDate.getTime())));
    HttpGet get = new HttpGet("conflicts.xml?".concat(URLEncodedUtils.format(queryStringParams, UTF_8)));
    HttpResponse response = getResponse(get, SC_OK, SC_NO_CONTENT);
    try {
        if (response != null) {
            if (SC_OK == response.getStatusLine().getStatusCode()) {
                String mediaPackageXml = EntityUtils.toString(response.getEntity(), UTF_8);
                List<MediaPackage> events = MediaPackageParser.getArrayFromXml(mediaPackageXml);
                logger.info("Successfully get conflicts from the remote scheduler service");
                return events;
            } else if (SC_UNAUTHORIZED == response.getStatusLine().getStatusCode()) {
                logger.info("Unauthorized to search for conflicting events");
                throw new UnauthorizedException("Unauthorized to search for conflicting events");
            } else if (SC_NO_CONTENT == response.getStatusLine().getStatusCode()) {
                return Collections.<MediaPackage>emptyList();
            }
        }
    } catch (UnauthorizedException e) {
        throw e;
    } catch (Exception e) {
        throw new SchedulerException("Unable to get conflicts from remote scheduler service: " + e);
    } finally {
        closeConnection(response);
    }
    throw new SchedulerException("Unable to get conflicts from remote scheduler service");
}
Also used : NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HttpGet(org.apache.http.client.methods.HttpGet) ArrayList(java.util.ArrayList) MediaPackage(org.opencastproject.mediapackage.MediaPackage) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) HttpResponse(org.apache.http.HttpResponse) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) SchedulerTransactionLockException(org.opencastproject.scheduler.api.SchedulerTransactionLockException) SchedulerConflictException(org.opencastproject.scheduler.api.SchedulerConflictException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException)

Example 70 with SchedulerException

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

the class SchedulerServiceRemoteImpl method addTransactionEvent.

private void addTransactionEvent(String id, Date startDateTime, Date endDateTime, String captureAgentId, Set<String> userIds, MediaPackage mediaPackage, Map<String, String> wfProperties, Map<String, String> caMetadata, Opt<Boolean> optOut) throws NotFoundException, UnauthorizedException, SchedulerException {
    HttpPut put = new HttpPut(UrlSupport.concat("transaction", id, "add"));
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("start", Long.toString(startDateTime.getTime())));
    params.add(new BasicNameValuePair("end", Long.toString(endDateTime.getTime())));
    params.add(new BasicNameValuePair("agent", captureAgentId));
    params.add(new BasicNameValuePair("users", StringUtils.join(userIds, ",")));
    params.add(new BasicNameValuePair("mediaPackage", MediaPackageParser.getAsXml(mediaPackage)));
    params.add(new BasicNameValuePair("wfproperties", toPropertyString(wfProperties)));
    params.add(new BasicNameValuePair("agentparameters", toPropertyString(caMetadata)));
    if (optOut.isSome())
        params.add(new BasicNameValuePair("optOut", Boolean.toString(optOut.get())));
    put.setEntity(new UrlEncodedFormEntity(params, UTF_8));
    final String eventId = mediaPackage.getIdentifier().compact();
    HttpResponse response = getResponse(put, SC_OK, SC_NOT_FOUND, SC_CONFLICT, SC_UNAUTHORIZED);
    try {
        if (response != null && SC_OK == response.getStatusLine().getStatusCode()) {
            logger.info("Successfully added event '{}' to scheduler transaction '{}' on the scheduler service", eventId, id);
            return;
        } else if (response != null && SC_UNAUTHORIZED == response.getStatusLine().getStatusCode()) {
            logger.info("Unauthorized to add event '{}' to scheduler transaction '{}'", eventId, id);
            throw new UnauthorizedException("Unauthorized to add event to scheduler transaction");
        } else if (response != null && SC_NOT_FOUND == response.getStatusLine().getStatusCode()) {
            logger.info("Scheduler transaction '{}' not found", id);
            throw new NotFoundException("Not found scheduler transaction " + id);
        }
    } catch (NotFoundException e) {
        throw e;
    } catch (UnauthorizedException e) {
        throw e;
    } catch (Exception e) {
        throw new SchedulerException("Unable to add event to scheduler transaction '" + id + "' on the scheduler service: " + e);
    } finally {
        closeConnection(response);
    }
    throw new SchedulerException("Unable to add event to scheduler transaction '" + id + "' on the scheduler service");
}
Also used : SchedulerException(org.opencastproject.scheduler.api.SchedulerException) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) HttpResponse(org.apache.http.HttpResponse) NotFoundException(org.opencastproject.util.NotFoundException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) HttpPut(org.apache.http.client.methods.HttpPut) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) SchedulerTransactionLockException(org.opencastproject.scheduler.api.SchedulerTransactionLockException) SchedulerConflictException(org.opencastproject.scheduler.api.SchedulerConflictException) 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