Search in sources :

Example 11 with SchedulerConflictException

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

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

the class SchedulerRestService method addEvent.

/**
 * Creates new event based on parameters. All times and dates are in milliseconds.
 */
@POST
@Path("/")
@RestQuery(name = "newrecording", description = "Creates new event with specified parameters", returnDescription = "If an event was successfully created", restParameters = { @RestParameter(name = "start", isRequired = true, type = Type.INTEGER, description = "The start date of the event in milliseconds from 1970-01-01T00:00:00Z"), @RestParameter(name = "end", isRequired = true, type = Type.INTEGER, description = "The end date of the event in milliseconds from 1970-01-01T00:00:00Z"), @RestParameter(name = "agent", isRequired = true, type = Type.STRING, description = "The agent of the event"), @RestParameter(name = "users", isRequired = false, type = Type.STRING, description = "Comma separated list of user ids (speakers/lecturers) for the event"), @RestParameter(name = "mediaPackage", isRequired = true, type = Type.TEXT, description = "The media package of the event"), @RestParameter(name = "wfproperties", isRequired = false, type = Type.TEXT, description = "Workflow " + "configuration keys for the event. Each key will be prefixed by 'org.opencastproject.workflow" + ".config.' and added to the capture agent parameters."), @RestParameter(name = "agentparameters", isRequired = false, type = Type.TEXT, description = "The capture agent properties for the event"), @RestParameter(name = "optOut", isRequired = false, type = Type.BOOLEAN, description = "The opt out status of the event"), @RestParameter(name = "source", isRequired = false, type = Type.STRING, description = "The scheduling source of the event"), @RestParameter(name = "origin", isRequired = false, type = Type.STRING, description = "The origin") }, reponses = { @RestResponse(responseCode = HttpServletResponse.SC_CREATED, description = "Event is successfully created"), @RestResponse(responseCode = HttpServletResponse.SC_CONFLICT, description = "Unable to create event, conflicting events found (ConflicsFound)"), @RestResponse(responseCode = HttpServletResponse.SC_CONFLICT, description = "Unable to create event, event locked by a transaction  (TransactionLock)"), @RestResponse(responseCode = HttpServletResponse.SC_UNAUTHORIZED, description = "You do not have permission to create the event. Maybe you need to authenticate."), @RestResponse(responseCode = HttpServletResponse.SC_BAD_REQUEST, description = "Missing or invalid information for this request") })
public Response addEvent(@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("optOut") Boolean optOut, @FormParam("source") String schedulingSource, @FormParam("origin") String origin) throws UnauthorizedException {
    if (StringUtils.isBlank(origin))
        origin = SchedulerService.ORIGIN;
    if (endTime <= startTime || startTime < 0) {
        logger.debug("Cannot add event without proper start and end time");
        return RestUtil.R.badRequest("Cannot add event without proper start and end time");
    }
    if (StringUtils.isBlank(agentId)) {
        logger.debug("Cannot add event without agent identifier");
        return RestUtil.R.badRequest("Cannot add event without agent identifier");
    }
    if (StringUtils.isBlank(mediaPackageXml)) {
        logger.debug("Cannot add event without media package");
        return RestUtil.R.badRequest("Cannot add event without media package");
    }
    MediaPackage mediaPackage;
    try {
        mediaPackage = MediaPackageParser.getFromXml(mediaPackageXml);
    } catch (MediaPackageException e) {
        logger.debug("Could not parse media package", e);
        return RestUtil.R.badRequest("Could not parse media package");
    }
    String eventId = mediaPackage.getIdentifier().compact();
    Map<String, String> caProperties = new HashMap<>();
    if (StringUtils.isNotBlank(agentParameters)) {
        try {
            Properties prop = parseProperties(agentParameters);
            caProperties.putAll((Map) prop);
        } catch (Exception e) {
            logger.info("Could not parse capture agent properties: {}", agentParameters);
            return RestUtil.R.badRequest("Could not parse capture agent properties");
        }
    }
    Map<String, String> wfProperties = new HashMap<>();
    if (StringUtils.isNotBlank(workflowProperties)) {
        try {
            Properties prop = parseProperties(workflowProperties);
            wfProperties.putAll((Map) prop);
        } catch (IOException e) {
            logger.info("Could not parse workflow configuration properties: {}", workflowProperties);
            return RestUtil.R.badRequest("Could not parse workflow configuration properties");
        }
    }
    Set<String> userIds = new HashSet<>();
    String[] ids = StringUtils.split(users, ",");
    if (ids != null)
        userIds.addAll(Arrays.asList(ids));
    DateTime startDate = new DateTime(startTime).toDateTime(DateTimeZone.UTC);
    DateTime endDate = new DateTime(endTime).toDateTime(DateTimeZone.UTC);
    try {
        service.addEvent(startDate.toDate(), endDate.toDate(), agentId, userIds, mediaPackage, wfProperties, caProperties, Opt.nul(optOut), Opt.nul(schedulingSource), origin);
        return Response.status(Status.CREATED).header("Location", serverUrl + serviceUrl + '/' + eventId + "/mediapackage.xml").build();
    } catch (UnauthorizedException e) {
        throw e;
    } catch (SchedulerTransactionLockException | SchedulerConflictException e) {
        return Response.status(Status.CONFLICT).entity(generateErrorResponse(e)).type(MediaType.APPLICATION_JSON).build();
    } catch (Exception e) {
        logger.error("Unable to create new event with id '{}'", eventId, e);
        return Response.serverError().build();
    }
}
Also used : MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) HashMap(java.util.HashMap) SchedulerConflictException(org.opencastproject.scheduler.api.SchedulerConflictException) 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) DateTime(org.joda.time.DateTime) SchedulerTransactionLockException(org.opencastproject.scheduler.api.SchedulerTransactionLockException) MediaPackage(org.opencastproject.mediapackage.MediaPackage) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) HashSet(java.util.HashSet) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 13 with SchedulerConflictException

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

the class SchedulerServiceImplTest method testPersistence.

@Test
public void testPersistence() 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);
    String catalogId = 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);
    assertEquals("mod0", schedSvc.getScheduleLastModified(captureDeviceID));
    // Store event
    schedSvc.addEvent(start, end, captureDeviceID, userIds, mp, wfProperties, caProperties, Opt.<Boolean>none(), Opt.<String>none(), SchedulerService.ORIGIN);
    try {
        MediaPackage mp2 = (MediaPackage) mp.clone();
        mp2.setIdentifier(new UUIDIdBuilderImpl().createNew());
        schedSvc.addEvent(start, end, captureDeviceID, userIds, mp2, wfProperties, caProperties, Opt.<Boolean>none(), Opt.<String>none(), SchedulerService.ORIGIN);
        Assert.fail();
    } catch (SchedulerConflictException e) {
        Assert.assertNotNull(e);
    }
    MediaPackage mediaPackage = schedSvc.getMediaPackage(mp.getIdentifier().compact());
    assertEquals(seriesId, mediaPackage.getSeries());
    DublinCoreCatalog eventLoaded = schedSvc.getDublinCore(mp.getIdentifier().compact());
    assertEquals(event.getFirst(PROPERTY_TITLE), eventLoaded.getFirst(PROPERTY_TITLE));
    // the returned map is of type com.entwinemedia.fn.data.ImmutableMapWrapper which
    // does not delegate equals and hashcode so it is necessary to create a HashMap from it
    TechnicalMetadata technicalMetadata = schedSvc.getTechnicalMetadata(mp.getIdentifier().compact());
    assertEquals(mp.getIdentifier().compact(), technicalMetadata.getEventId());
    assertEquals(captureDeviceID, technicalMetadata.getAgentId());
    assertEquals(start, technicalMetadata.getStartDate());
    assertEquals(end, technicalMetadata.getEndDate());
    assertEquals(false, technicalMetadata.isOptOut());
    assertEquals(userIds, technicalMetadata.getPresenters());
    assertTrue(technicalMetadata.getRecording().isNone());
    assertTrue(technicalMetadata.getCaptureAgentConfiguration().size() >= caProperties.size());
    assertEquals(wfProperties, new HashMap<>(schedSvc.getWorkflowConfig(mp.getIdentifier().compact())));
    String lastModified = schedSvc.getScheduleLastModified(captureDeviceID);
    assertNotEquals("mod0", lastModified);
    eventLoaded.set(PROPERTY_TITLE, "Something more");
    addDublinCore(Opt.some(catalogId), mp, eventLoaded);
    userIds.add("user3");
    userIds.remove("user1");
    mp.setSeries("series2");
    // Update event
    schedSvc.updateEvent(mp.getIdentifier().compact(), Opt.<Date>none(), Opt.<Date>none(), Opt.<String>none(), Opt.some(userIds), Opt.some(mp), Opt.some(wfProperties), Opt.some(caProperties), Opt.some(Opt.some(true)), SchedulerService.ORIGIN);
    mediaPackage = schedSvc.getMediaPackage(mp.getIdentifier().compact());
    assertEquals("series2", mediaPackage.getSeries());
    DublinCoreCatalog eventReloaded = schedSvc.getDublinCore(mp.getIdentifier().compact());
    assertEquals("Something more", eventReloaded.getFirst(PROPERTY_TITLE));
    technicalMetadata = schedSvc.getTechnicalMetadata(mp.getIdentifier().compact());
    assertEquals(mp.getIdentifier().compact(), technicalMetadata.getEventId());
    assertEquals(captureDeviceID, technicalMetadata.getAgentId());
    assertEquals(start, technicalMetadata.getStartDate());
    assertEquals(end, technicalMetadata.getEndDate());
    assertEquals(true, technicalMetadata.isOptOut());
    assertEquals(userIds, technicalMetadata.getPresenters());
    assertTrue(technicalMetadata.getRecording().isNone());
    assertTrue(technicalMetadata.getCaptureAgentConfiguration().size() >= caProperties.size());
    String updatedLastModified = schedSvc.getScheduleLastModified(captureDeviceID);
    assertNotEquals("mod0", updatedLastModified);
    assertNotEquals(lastModified, updatedLastModified);
    assertTrue(schedSvc.getCaptureAgentConfiguration(mp.getIdentifier().compact()).size() >= caProperties.size());
}
Also used : MediaPackage(org.opencastproject.mediapackage.MediaPackage) SchedulerConflictException(org.opencastproject.scheduler.api.SchedulerConflictException) NotFoundException(org.opencastproject.util.NotFoundException) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog) Date(java.util.Date) TechnicalMetadata(org.opencastproject.scheduler.api.TechnicalMetadata) HashSet(java.util.HashSet) UUIDIdBuilderImpl(org.opencastproject.mediapackage.identifier.UUIDIdBuilderImpl) Test(org.junit.Test)

Example 14 with SchedulerConflictException

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

the class SchedulerServiceImplTest method testTransactionConflicts.

@Test
public void testTransactionConflicts() 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");
    try {
        schedSvc.addEvent(start, end, captureDeviceID, userIds, mp, wfPropertiesUpdated, caProperties, Opt.<Boolean>none(), Opt.some("new"), SchedulerService.ORIGIN);
    } catch (SchedulerTransactionLockException e) {
        fail("Transaction create lock not working!");
    }
    Assert.assertFalse(schedSvc.hasActiveTransaction(mp.getIdentifier().compact()));
    SchedulerTransaction trx = schedSvc.createTransaction("new");
    assertEquals("new", trx.getSource());
    SchedulerTransaction trx2 = schedSvc.createTransaction("new2");
    assertEquals("new2", trx2.getSource());
    try {
        schedSvc.createTransaction("new");
        fail("Duplicated transaction created!");
    } catch (SchedulerConflictException e) {
        assertNotNull(e);
    }
    try {
        schedSvc.updateEvent(mp.getIdentifier().compact(), Opt.<Date>none(), Opt.<Date>none(), Opt.<String>none(), Opt.<Set<String>>none(), Opt.<MediaPackage>none(), Opt.<Map<String, String>>none(), Opt.<Map<String, String>>none(), Opt.some(Opt.some(false)), SchedulerService.ORIGIN);
        fail("Transaction update lock not working!");
    } catch (SchedulerTransactionLockException e) {
        assertNotNull(e);
    }
    try {
        schedSvc.removeEvent(mp.getIdentifier().compact());
        fail("Transaction delete lock not working!");
    } catch (SchedulerTransactionLockException e) {
        assertNotNull(e);
    }
    try {
        MediaPackage mp2 = generateEvent(Opt.<String>none());
        schedSvc.addEvent(start, end, captureDeviceID, userIds, mp2, wfPropertiesUpdated, caProperties, Opt.<Boolean>none(), Opt.some("new"), SchedulerService.ORIGIN);
        fail("Transaction create lock not working!");
    } catch (SchedulerTransactionLockException e) {
        assertNotNull(e);
    }
    SchedulerTransaction trx3 = schedSvc.getTransaction(trx.getId());
    assertEquals(trx, trx3);
    mp = generateEvent(Opt.<String>none());
    event = generateEvent(captureDeviceID, new Date(), end);
    addDublinCore(Opt.<String>none(), mp, event);
    trx.addEvent(start, end, captureDeviceID, userIds, mp, wfPropertiesUpdated, caProperties, Opt.<Boolean>none());
    Assert.assertTrue(schedSvc.hasActiveTransaction(mp.getIdentifier().compact()));
    trx.commit();
    Assert.assertFalse(schedSvc.hasActiveTransaction(mp.getIdentifier().compact()));
    try {
        MediaPackage mp2 = generateEvent(Opt.<String>none());
        Date startDate = new Date(System.currentTimeMillis() + 600000);
        Date endDate = new Date(System.currentTimeMillis() + 660000);
        schedSvc.addEvent(startDate, endDate, captureDeviceID, userIds, mp2, wfPropertiesUpdated, caProperties, Opt.<Boolean>none(), Opt.some("new"), SchedulerService.ORIGIN);
    } catch (SchedulerTransactionLockException e) {
        fail("Transaction create lock not working!");
    }
}
Also used : SchedulerTransactionLockException(org.opencastproject.scheduler.api.SchedulerTransactionLockException) MediaPackage(org.opencastproject.mediapackage.MediaPackage) SchedulerConflictException(org.opencastproject.scheduler.api.SchedulerConflictException) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog) SchedulerTransaction(org.opencastproject.scheduler.api.SchedulerService.SchedulerTransaction) Date(java.util.Date) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 15 with SchedulerConflictException

use of org.opencastproject.scheduler.api.SchedulerConflictException 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)

Aggregations

SchedulerConflictException (org.opencastproject.scheduler.api.SchedulerConflictException)17 NotFoundException (org.opencastproject.util.NotFoundException)13 SchedulerException (org.opencastproject.scheduler.api.SchedulerException)12 SchedulerTransactionLockException (org.opencastproject.scheduler.api.SchedulerTransactionLockException)12 MediaPackage (org.opencastproject.mediapackage.MediaPackage)11 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)11 Date (java.util.Date)8 DublinCoreCatalog (org.opencastproject.metadata.dublincore.DublinCoreCatalog)8 MediaPackageException (org.opencastproject.mediapackage.MediaPackageException)7 IOException (java.io.IOException)6 HashSet (java.util.HashSet)6 ArrayList (java.util.ArrayList)5 Test (org.junit.Test)5 AQueryBuilder (org.opencastproject.assetmanager.api.query.AQueryBuilder)5 Path (javax.ws.rs.Path)4 HttpResponse (org.apache.http.HttpResponse)4 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)4 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)4 JSONObject (org.json.simple.JSONObject)4 ARecord (org.opencastproject.assetmanager.api.query.ARecord)4