Search in sources :

Example 6 with SchedulerConflictException

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

the class SchedulerServiceImplTest method testTransactionCommitCollision.

@Test
public void testTransactionCommitCollision() 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");
    MediaPackage mp2 = generateEvent(Opt.<String>none());
    try {
        schedSvc.addEvent(start, end, captureDeviceID, userIds, mp2, wfPropertiesUpdated, caProperties, Opt.some(false), Opt.some("existing"), SchedulerService.ORIGIN);
    } catch (SchedulerTransactionLockException e) {
        fail("Transaction create lock not working!");
    }
    /* Test transaction collision of already existing event and new transaction event */
    SchedulerTransaction trx = schedSvc.createTransaction("new");
    assertEquals("new", trx.getSource());
    AQueryBuilder query = assetManager.createQuery();
    AResult result = query.select(query.snapshot(), query.properties()).where(query.organizationId().eq(new DefaultOrganization().getId()).and(query.mediaPackageId(mp.getIdentifier().compact()))).run();
    Opt<ARecord> record = result.getRecords().head();
    assertFalse(record.isSome());
    trx.addEvent(start, end, captureDeviceID, userIds, mp, wfPropertiesUpdated, caProperties, Opt.some(false));
    query = assetManager.createQuery();
    result = query.select(query.snapshot(), query.properties()).where(query.organizationId().eq(new DefaultOrganization().getId()).and(query.mediaPackageId(mp.getIdentifier().compact()))).run();
    record = result.getRecords().head();
    assertTrue(record.isSome());
    try {
        trx.commit();
        fail("Pre-conflict detection not working!");
    } catch (SchedulerConflictException e) {
        assertNotNull(e);
    }
    query = assetManager.createQuery();
    result = query.select(query.snapshot(), query.properties()).where(query.organizationId().eq(new DefaultOrganization().getId()).and(query.mediaPackageId(mp.getIdentifier().compact()))).run();
    record = result.getRecords().head();
    assertTrue(record.isSome());
    try {
        schedSvc.getTransaction(trx.getId());
    } catch (NotFoundException e) {
        fail("Transaction found!");
    }
    /* Test transaction collision of already existing event and new opted out transaction event */
    MediaPackage mp4 = (MediaPackage) mp.clone();
    mp4.setIdentifier(new IdImpl("newuuid"));
    SchedulerTransaction trx2 = schedSvc.createTransaction("optedout");
    assertEquals("optedout", trx2.getSource());
    query = assetManager.createQuery();
    result = query.select(query.snapshot(), query.properties()).where(query.organizationId().eq(new DefaultOrganization().getId()).and(query.mediaPackageId(mp4.getIdentifier().compact()))).run();
    record = result.getRecords().head();
    assertFalse(record.isSome());
    trx2.addEvent(start, end, captureDeviceID, userIds, mp4, wfPropertiesUpdated, caProperties, Opt.some(true));
    query = assetManager.createQuery();
    result = query.select(query.snapshot(), query.properties()).where(query.organizationId().eq(new DefaultOrganization().getId()).and(query.mediaPackageId(mp4.getIdentifier().compact()))).run();
    record = result.getRecords().head();
    assertTrue(record.isSome());
    try {
        trx2.commit();
    } catch (SchedulerConflictException e) {
        fail("Pre-conflict detection not working!");
    }
    /* Test transaction collision of two transaction events */
    schedSvc.removeEvent(mp2.getIdentifier().compact());
    MediaPackage mp3 = generateEvent(Opt.<String>none());
    trx.addEvent(start, end, captureDeviceID, userIds, mp3, wfPropertiesUpdated, caProperties, Opt.some(false));
    try {
        trx.commit();
        fail("Pre-conflict detection not working!");
    } catch (SchedulerConflictException e) {
        assertNotNull(e);
    }
    query = assetManager.createQuery();
    result = query.select(query.snapshot(), query.properties()).where(query.organizationId().eq(new DefaultOrganization().getId()).and(query.mediaPackageId(mp.getIdentifier().compact()))).run();
    record = result.getRecords().head();
    assertTrue(record.isSome());
    try {
        schedSvc.getTransaction(trx.getId());
    } catch (NotFoundException e) {
        fail("Transaction found!");
    }
    /* Test transaction collision of two transaction events but one opted out */
    MediaPackage mp5 = (MediaPackage) mp.clone();
    mp5.setIdentifier(new IdImpl("newuuid2"));
    SchedulerTransaction trx3 = schedSvc.createTransaction("optedout2");
    assertEquals("optedout2", trx3.getSource());
    query = assetManager.createQuery();
    result = query.select(query.snapshot(), query.properties()).where(query.organizationId().eq(new DefaultOrganization().getId()).and(query.mediaPackageId(mp5.getIdentifier().compact()))).run();
    record = result.getRecords().head();
    assertFalse(record.isSome());
    trx3.addEvent(start, end, captureDeviceID, userIds, mp5, wfPropertiesUpdated, caProperties, Opt.some(false));
    query = assetManager.createQuery();
    result = query.select(query.snapshot(), query.properties()).where(query.organizationId().eq(new DefaultOrganization().getId()).and(query.mediaPackageId(mp5.getIdentifier().compact()))).run();
    record = result.getRecords().head();
    assertTrue(record.isSome());
    MediaPackage mp6 = generateEvent(Opt.<String>none());
    trx.addEvent(start, end, captureDeviceID, userIds, mp6, wfPropertiesUpdated, caProperties, Opt.some(true));
    try {
        trx3.commit();
    } catch (SchedulerConflictException e) {
        fail("Pre-conflict detection not working!");
    }
}
Also used : SchedulerConflictException(org.opencastproject.scheduler.api.SchedulerConflictException) AQueryBuilder(org.opencastproject.assetmanager.api.query.AQueryBuilder) NotFoundException(org.opencastproject.util.NotFoundException) SchedulerTransaction(org.opencastproject.scheduler.api.SchedulerService.SchedulerTransaction) Date(java.util.Date) IdImpl(org.opencastproject.mediapackage.identifier.IdImpl) ARecord(org.opencastproject.assetmanager.api.query.ARecord) SchedulerTransactionLockException(org.opencastproject.scheduler.api.SchedulerTransactionLockException) MediaPackage(org.opencastproject.mediapackage.MediaPackage) RichAResult(org.opencastproject.assetmanager.api.query.RichAResult) AResult(org.opencastproject.assetmanager.api.query.AResult) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog) HashSet(java.util.HashSet) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization) Test(org.junit.Test)

Example 7 with SchedulerConflictException

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

the class SchedulerServiceRemoteImpl method updateEvent.

@Override
public void updateEvent(String eventId, Opt<Date> startDateTime, Opt<Date> endDateTime, Opt<String> captureAgentId, Opt<Set<String>> userIds, Opt<MediaPackage> mediaPackage, Opt<Map<String, String>> wfProperties, Opt<Map<String, String>> caMetadata, Opt<Opt<Boolean>> optOut, String origin) throws NotFoundException, UnauthorizedException, SchedulerTransactionLockException, SchedulerConflictException, SchedulerException {
    logger.debug("Start updating event {}.", eventId);
    HttpPut put = new HttpPut("/" + eventId);
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    if (startDateTime.isSome())
        params.add(new BasicNameValuePair("start", Long.toString(startDateTime.get().getTime())));
    if (endDateTime.isSome())
        params.add(new BasicNameValuePair("end", Long.toString(endDateTime.get().getTime())));
    if (captureAgentId.isSome())
        params.add(new BasicNameValuePair("agent", captureAgentId.get()));
    if (userIds.isSome())
        params.add(new BasicNameValuePair("users", StringUtils.join(userIds.get(), ",")));
    if (mediaPackage.isSome())
        params.add(new BasicNameValuePair("mediaPackage", MediaPackageParser.getAsXml(mediaPackage.get())));
    if (wfProperties.isSome())
        params.add(new BasicNameValuePair("wfproperties", toPropertyString(wfProperties.get())));
    if (caMetadata.isSome())
        params.add(new BasicNameValuePair("agentparameters", toPropertyString(caMetadata.get())));
    if (optOut.isSome()) {
        params.add(new BasicNameValuePair("updateOptOut", Boolean.toString(true)));
        if (optOut.get().isSome())
            params.add(new BasicNameValuePair("optOut", Boolean.toString(optOut.get().get())));
    } else {
        params.add(new BasicNameValuePair("updateOptOut", Boolean.toString(false)));
    }
    params.add(new BasicNameValuePair("origin", origin));
    put.setEntity(new UrlEncodedFormEntity(params, UTF_8));
    HttpResponse response = getResponse(put, SC_OK, SC_NOT_FOUND, SC_UNAUTHORIZED, SC_FORBIDDEN, SC_CONFLICT);
    try {
        if (response != null) {
            if (SC_NOT_FOUND == response.getStatusLine().getStatusCode()) {
                logger.info("Event {} was not found by the scheduler service", eventId);
                throw new NotFoundException("Event '" + eventId + "' not found on remote scheduler service!");
            } else if (SC_OK == response.getStatusLine().getStatusCode()) {
                logger.info("Event {} successfully updated with capture agent metadata.", eventId);
                return;
            } 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 update event {}", eventId);
                    throw new SchedulerTransactionLockException("Event is locked by a transaction, unable to update event " + eventId);
                } else if (SchedulerConflictException.ERROR_CODE.equals(errorCode)) {
                    logger.info("Conflicting events found when updating event {}", eventId);
                    throw new SchedulerConflictException("Conflicting events found when updating event " + eventId);
                } else {
                    throw new SchedulerException("Unexpected error code " + errorCode);
                }
            } else if (SC_UNAUTHORIZED == response.getStatusLine().getStatusCode()) {
                logger.info("Unauthorized to update the event {}.", eventId);
                throw new UnauthorizedException("Unauthorized to update the event " + eventId);
            } else if (SC_FORBIDDEN == response.getStatusLine().getStatusCode()) {
                logger.info("Forbidden to update the event {}.", eventId);
                throw new SchedulerException("Event with specified ID cannot be updated");
            } else {
                throw new SchedulerException("Unexpected status code " + response.getStatusLine());
            }
        }
    } catch (NotFoundException e) {
        throw e;
    } catch (UnauthorizedException e) {
        throw e;
    } catch (SchedulerTransactionLockException e) {
        throw e;
    } catch (SchedulerConflictException e) {
        throw e;
    } catch (Exception e) {
        throw new SchedulerException("Unable to update event " + eventId + " to the scheduler service: " + e);
    } finally {
        closeConnection(response);
    }
    throw new SchedulerException("Unable to update  event " + eventId);
}
Also used : SchedulerException(org.opencastproject.scheduler.api.SchedulerException) ArrayList(java.util.ArrayList) SchedulerConflictException(org.opencastproject.scheduler.api.SchedulerConflictException) 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) JSONObject(org.json.simple.JSONObject) SchedulerTransactionLockException(org.opencastproject.scheduler.api.SchedulerTransactionLockException) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException)

Example 8 with SchedulerConflictException

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

the class SchedulerServiceRemoteImpl method addEvent.

@Override
public void addEvent(Date startDateTime, Date endDateTime, String captureAgentId, Set<String> userIds, MediaPackage mediaPackage, Map<String, String> wfProperties, Map<String, String> caMetadata, Opt<Boolean> optOut, Opt<String> schedulingSource, String origin) throws UnauthorizedException, SchedulerTransactionLockException, SchedulerConflictException, SchedulerException {
    HttpPost post = new HttpPost("/");
    String eventId = mediaPackage.getIdentifier().compact();
    logger.debug("Start adding a new event {} through remote Schedule Service", eventId);
    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())));
    if (schedulingSource.isSome())
        params.add(new BasicNameValuePair("source", schedulingSource.get()));
    params.add(new BasicNameValuePair("origin", origin));
    post.setEntity(new UrlEncodedFormEntity(params, UTF_8));
    HttpResponse response = getResponse(post, SC_CREATED, SC_UNAUTHORIZED, SC_CONFLICT);
    try {
        if (response != null && SC_CREATED == response.getStatusLine().getStatusCode()) {
            logger.info("Successfully added event {} to the scheduler service", eventId);
            return;
        } 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 {}", 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 {}", eventId);
                throw new SchedulerConflictException("Conflicting events found when adding event " + 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 9 with SchedulerConflictException

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

the class SchedulerServiceImpl method addEventInternal.

private void addEventInternal(Date startDateTime, Date endDateTime, String captureAgentId, Set<String> userIds, MediaPackage mediaPackage, Map<String, String> wfProperties, Map<String, String> caMetadata, String modificationOrigin, Opt<Boolean> optOutStatus, Opt<String> schedulingSource, Opt<String> trxId) throws SchedulerException {
    notNull(startDateTime, "startDateTime");
    notNull(endDateTime, "endDateTime");
    notEmpty(captureAgentId, "captureAgentId");
    notNull(userIds, "userIds");
    notNull(mediaPackage, "mediaPackage");
    notNull(wfProperties, "wfProperties");
    notNull(caMetadata, "caMetadata");
    notEmpty(modificationOrigin, "modificationOrigin");
    notNull(optOutStatus, "optOutStatus");
    notNull(schedulingSource, "schedulingSource");
    notNull(trxId, "trxId");
    if (endDateTime.before(startDateTime))
        throw new IllegalArgumentException("The end date is before the start date");
    final String mediaPackageId = mediaPackage.getIdentifier().compact();
    try {
        AQueryBuilder query = assetManager.createQuery();
        // TODO this query runs twice if called from SchedulerTransactionImpl#addEvent
        AResult result = query.select(query.nothing()).where(withOrganization(query).and(query.mediaPackageId(mediaPackageId).and(query.version().isLatest()))).run();
        Opt<ARecord> record = result.getRecords().head();
        if (record.isSome()) {
            logger.warn("Mediapackage with id '{}' already exists!", mediaPackageId);
            throw new SchedulerConflictException("Mediapackage with id '" + mediaPackageId + "' already exists!");
        }
        Opt<String> seriesId = Opt.nul(StringUtils.trimToNull(mediaPackage.getSeries()));
        // Get opt out status
        boolean optOut = getOptOutStatus(seriesId, optOutStatus);
        if (trxId.isNone()) {
            // Check for locked transactions
            if (schedulingSource.isSome() && persistence.hasTransaction(schedulingSource.get())) {
                logger.warn("Unable to add event '{}', source '{}' is currently locked due to an active transaction!", mediaPackageId, schedulingSource.get());
                throw new SchedulerTransactionLockException("Unable to add event, locked source " + schedulingSource.get());
            }
            // Check for conflicting events if not opted out
            if (!optOut) {
                List<MediaPackage> conflictingEvents = findConflictingEvents(captureAgentId, startDateTime, endDateTime);
                if (conflictingEvents.size() > 0) {
                    logger.info("Unable to add event {}, conflicting events found: {}", mediaPackageId, conflictingEvents);
                    throw new SchedulerConflictException("Unable to add event, conflicting events found for event " + mediaPackageId);
                }
            }
        }
        // Load dublincore and acl for update
        Opt<DublinCoreCatalog> dublinCore = DublinCoreUtil.loadEpisodeDublinCore(workspace, mediaPackage);
        Option<AccessControlList> acl = authorizationService.getAcl(mediaPackage, AclScope.Episode);
        // Get updated agent properties
        Map<String, String> finalCaProperties = getFinalAgentProperties(caMetadata, wfProperties, captureAgentId, seriesId, dublinCore);
        // Persist asset
        String checksum = calculateChecksum(workspace, getEventCatalogUIAdapterFlavors(), startDateTime, endDateTime, captureAgentId, userIds, mediaPackage, dublinCore, wfProperties, finalCaProperties, optOut, acl.toOpt().getOr(new AccessControlList()));
        persistEvent(mediaPackageId, modificationOrigin, checksum, Opt.some(startDateTime), Opt.some(endDateTime), Opt.some(captureAgentId), Opt.some(userIds), Opt.some(mediaPackage), Opt.some(wfProperties), Opt.some(finalCaProperties), Opt.some(optOut), schedulingSource, trxId);
        if (trxId.isNone()) {
            // Send updates
            sendUpdateAddEvent(mediaPackageId, acl.toOpt(), dublinCore, Opt.some(startDateTime), Opt.some(endDateTime), Opt.some(userIds), Opt.some(captureAgentId), Opt.some(finalCaProperties), Opt.some(optOut));
            // Update last modified
            touchLastEntry(captureAgentId);
        }
    } catch (SchedulerException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Failed to create event with id '{}': {}", mediaPackageId, getStackTrace(e));
        throw new SchedulerException(e);
    }
}
Also used : AccessControlList(org.opencastproject.security.api.AccessControlList) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) SchedulerConflictException(org.opencastproject.scheduler.api.SchedulerConflictException) AQueryBuilder(org.opencastproject.assetmanager.api.query.AQueryBuilder) 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) ARecord(org.opencastproject.assetmanager.api.query.ARecord) SchedulerTransactionLockException(org.opencastproject.scheduler.api.SchedulerTransactionLockException) MediaPackage(org.opencastproject.mediapackage.MediaPackage) AResult(org.opencastproject.assetmanager.api.query.AResult) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog)

Example 10 with SchedulerConflictException

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

the class SchedulerServiceImpl method updateEventInternal.

private void updateEventInternal(final String mpId, String modificationOrigin, Opt<Date> startDateTime, Opt<Date> endDateTime, Opt<String> captureAgentId, Opt<Set<String>> userIds, Opt<MediaPackage> mediaPackage, Opt<Map<String, String>> wfProperties, Opt<Map<String, String>> caMetadata, Opt<Opt<Boolean>> optOutOption, Opt<String> trxId) throws NotFoundException, SchedulerException {
    notEmpty(mpId, "mpId");
    notEmpty(modificationOrigin, "modificationOrigin");
    notNull(startDateTime, "startDateTime");
    notNull(endDateTime, "endDateTime");
    notNull(captureAgentId, "captureAgentId");
    notNull(userIds, "userIds");
    notNull(mediaPackage, "mediaPackage");
    notNull(wfProperties, "wfProperties");
    notNull(caMetadata, "caMetadata");
    notNull(optOutOption, "optOutStatus");
    notNull(trxId, "trxId");
    try {
        AQueryBuilder query = assetManager.createQuery();
        Props p = new Props(query);
        ASelectQuery select = query.select(query.snapshot(), p.start().target(), p.end().target(), query.propertiesOf(WORKFLOW_NAMESPACE, CA_NAMESPACE), p.agent().target(), p.source().target(), p.checksum().target(), p.optOut().target(), p.presenters().target()).where(withOrganization(query).and(query.mediaPackageId(mpId).and(query.version().isLatest()).and(query.hasPropertiesOf(p.namespace()))));
        Opt<ARecord> optEvent = select.run().getRecords().head();
        if (optEvent.isNone())
            throw new NotFoundException("No event found while updating event " + mpId);
        ARecord record = optEvent.get();
        if (record.getSnapshot().isNone())
            throw new NotFoundException("No mediapackage found while updating event " + mpId);
        Opt<DublinCoreCatalog> dublinCoreOpt = loadEpisodeDublinCoreFromAsset(record.getSnapshot().get());
        if (dublinCoreOpt.isNone())
            throw new NotFoundException("No dublincore found while updating event " + mpId);
        verifyActive(mpId, record);
        Date start = record.getProperties().apply(Properties.getDate(START_DATE_CONFIG));
        Date end = record.getProperties().apply(Properties.getDate(END_DATE_CONFIG));
        if ((startDateTime.isSome() || endDateTime.isSome()) && endDateTime.getOr(end).before(startDateTime.getOr(start)))
            throw new SchedulerException("The end date is before the start date");
        String agentId = record.getProperties().apply(Properties.getString(AGENT_CONFIG));
        Opt<String> seriesId = Opt.nul(record.getSnapshot().get().getMediaPackage().getSeries());
        boolean oldOptOut = record.getProperties().apply(Properties.getBoolean(OPTOUT_CONFIG));
        // Get opt out status
        Opt<Boolean> optOut = Opt.none();
        for (Opt<Boolean> optOutToUpdate : optOutOption) {
            optOut = Opt.some(getOptOutStatus(seriesId, optOutToUpdate));
        }
        if (trxId.isNone()) {
            // Check for locked transactions
            Opt<String> source = record.getProperties().apply(Properties.getStringOpt(SOURCE_CONFIG));
            if (source.isSome() && persistence.hasTransaction(source.get())) {
                logger.warn("Unable to update event '{}', source '{}' is currently locked due to an active transaction!", mpId, source.get());
                throw new SchedulerTransactionLockException("Unable to update event, locked source " + source.get());
            }
            // Set to opted out
            boolean isNewOptOut = optOut.isSome() && optOut.get();
            // Changed to ready for recording
            boolean readyForRecording = optOut.isSome() && !optOut.get();
            // Has a conflict related property be changed?
            boolean propertyChanged = captureAgentId.isSome() || startDateTime.isSome() || endDateTime.isSome();
            // Check for conflicting events
            if (!isNewOptOut && (readyForRecording || (propertyChanged && !oldOptOut))) {
                List<MediaPackage> conflictingEvents = $(findConflictingEvents(captureAgentId.getOr(agentId), startDateTime.getOr(start), endDateTime.getOr(end))).filter(new Fn<MediaPackage, Boolean>() {

                    @Override
                    public Boolean apply(MediaPackage mp) {
                        return !mpId.equals(mp.getIdentifier().compact());
                    }
                }).toList();
                if (conflictingEvents.size() > 0) {
                    logger.info("Unable to update event {}, conflicting events found: {}", mpId, conflictingEvents);
                    throw new SchedulerConflictException("Unable to update event, conflicting events found for event " + mpId);
                }
            }
        }
        Set<String> presenters = getPresenters(record.getProperties().apply(getStringOpt(PRESENTERS_CONFIG)).getOr(""));
        Map<String, String> wfProps = record.getProperties().filter(filterByNamespace._2(WORKFLOW_NAMESPACE)).group(toKey, toValue);
        Map<String, String> caProperties = record.getProperties().filter(filterByNamespace._2(CA_NAMESPACE)).group(toKey, toValue);
        boolean propertiesChanged = false;
        boolean dublinCoreChanged = false;
        // Get workflow properties
        for (Map<String, String> wfPropsToUpdate : wfProperties) {
            propertiesChanged = true;
            wfProps = wfPropsToUpdate;
        }
        // Get capture agent properties
        for (Map<String, String> caMetadataToUpdate : caMetadata) {
            propertiesChanged = true;
            caProperties = caMetadataToUpdate;
        }
        if (captureAgentId.isSome())
            propertiesChanged = true;
        Opt<AccessControlList> acl = Opt.none();
        Opt<DublinCoreCatalog> dublinCore = Opt.none();
        Opt<AccessControlList> aclOld = loadEpisodeAclFromAsset(record.getSnapshot().get());
        for (MediaPackage mpToUpdate : mediaPackage) {
            // Check for series change
            if (ne(record.getSnapshot().get().getMediaPackage().getSeries(), mpToUpdate.getSeries())) {
                propertiesChanged = true;
                seriesId = Opt.nul(mpToUpdate.getSeries());
            }
            // Check for ACL change and send update
            Option<AccessControlList> aclNew = authorizationService.getAcl(mpToUpdate, AclScope.Episode);
            if (aclNew.isSome()) {
                if (aclOld.isNone() || !AccessControlUtil.equals(aclNew.get(), aclOld.get())) {
                    acl = aclNew.toOpt();
                }
            }
            // Check for dublin core change and send update
            Opt<DublinCoreCatalog> dublinCoreNew = DublinCoreUtil.loadEpisodeDublinCore(workspace, mpToUpdate);
            if (dublinCoreNew.isSome() && !DublinCoreUtil.equals(dublinCoreOpt.get(), dublinCoreNew.get())) {
                dublinCoreChanged = true;
                propertiesChanged = true;
                dublinCore = dublinCoreNew;
            }
        }
        Opt<Map<String, String>> finalCaProperties = Opt.none();
        if (propertiesChanged) {
            finalCaProperties = Opt.some(getFinalAgentProperties(caProperties, wfProps, captureAgentId.getOr(agentId), seriesId, some(dublinCore.getOr(dublinCoreOpt.get()))));
        }
        String checksum = calculateChecksum(workspace, getEventCatalogUIAdapterFlavors(), startDateTime.getOr(start), endDateTime.getOr(end), captureAgentId.getOr(agentId), userIds.getOr(presenters), mediaPackage.getOr(record.getSnapshot().get().getMediaPackage()), some(dublinCore.getOr(dublinCoreOpt.get())), wfProperties.getOr(wfProps), finalCaProperties.getOr(caProperties), optOut.getOr(oldOptOut), acl.getOr(aclOld.getOr(new AccessControlList())));
        if (trxId.isNone()) {
            String oldChecksum = record.getProperties().apply(Properties.getString(CHECKSUM));
            if (checksum.equals(oldChecksum)) {
                logger.debug("Updated event {} has same checksum, ignore update", mpId);
                return;
            }
        }
        // Update asset
        persistEvent(mpId, modificationOrigin, checksum, startDateTime, endDateTime, captureAgentId, userIds, mediaPackage, wfProperties, finalCaProperties, optOut, Opt.<String>none(), trxId);
        if (trxId.isNone()) {
            // Send updates
            sendUpdateAddEvent(mpId, acl, dublinCore, startDateTime, endDateTime, userIds, Opt.some(agentId), finalCaProperties, optOut);
            // Update last modified
            if (propertiesChanged || dublinCoreChanged || optOutOption.isSome() || startDateTime.isSome() || endDateTime.isSome()) {
                touchLastEntry(agentId);
                for (String agent : captureAgentId) {
                    touchLastEntry(agent);
                }
            }
        }
    } catch (NotFoundException e) {
        throw e;
    } catch (SchedulerException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Failed to update event with id '{}': {}", mpId, getStackTrace(e));
        throw new SchedulerException(e);
    }
}
Also used : AccessControlList(org.opencastproject.security.api.AccessControlList) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) AQueryBuilder(org.opencastproject.assetmanager.api.query.AQueryBuilder) NotFoundException(org.opencastproject.util.NotFoundException) Log.getHumanReadableTimeString(org.opencastproject.util.Log.getHumanReadableTimeString) ARecord(org.opencastproject.assetmanager.api.query.ARecord) SchedulerTransactionLockException(org.opencastproject.scheduler.api.SchedulerTransactionLockException) Fn(com.entwinemedia.fn.Fn) SchedulerConflictException(org.opencastproject.scheduler.api.SchedulerConflictException) Date(java.util.Date) 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) MediaPackage(org.opencastproject.mediapackage.MediaPackage) ASelectQuery(org.opencastproject.assetmanager.api.query.ASelectQuery) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap)

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