Search in sources :

Example 91 with AccessControlList

use of org.opencastproject.security.api.AccessControlList in project opencast by opencast.

the class SearchServiceImpl method addSynchronously.

/**
 * Immediately adds the mediapackage to the search index.
 *
 * @param mediaPackage
 *          the media package
 * @throws SearchException
 *           if the media package cannot be added to the search index
 * @throws MediaPackageException
 *           if the mediapckage is invalid
 * @throws IllegalArgumentException
 *           if the mediapackage is <code>null</code>
 * @throws UnauthorizedException
 *           if the user does not have the rights to add the mediapackage
 */
public void addSynchronously(MediaPackage mediaPackage) throws SearchException, MediaPackageException, IllegalArgumentException, UnauthorizedException {
    User currentUser = securityService.getUser();
    String orgAdminRole = securityService.getOrganization().getAdminRole();
    if (!currentUser.hasRole(orgAdminRole) && !currentUser.hasRole(GLOBAL_ADMIN_ROLE) && !authorizationService.hasPermission(mediaPackage, Permissions.Action.WRITE.toString())) {
        throw new UnauthorizedException(currentUser, Permissions.Action.WRITE.toString());
    }
    if (mediaPackage == null) {
        throw new IllegalArgumentException("Unable to add a null mediapackage");
    }
    logger.debug("Attempting to add mediapackage {} to search index", mediaPackage.getIdentifier());
    AccessControlList acl = authorizationService.getActiveAcl(mediaPackage).getA();
    Date now = new Date();
    try {
        if (indexManager.add(mediaPackage, acl, now)) {
            logger.info("Added mediapackage `{}` to the search index, using ACL `{}`", mediaPackage, acl);
        } else {
            logger.warn("Failed to add mediapackage {} to the search index", mediaPackage.getIdentifier());
        }
    } catch (SolrServerException e) {
        throw new SearchException(e);
    }
    try {
        persistence.storeMediaPackage(mediaPackage, acl, now);
    } catch (SearchServiceDatabaseException e) {
        logger.error("Could not store media package to search database {}: {}", mediaPackage.getIdentifier(), e);
        throw new SearchException(e);
    }
}
Also used : AccessControlList(org.opencastproject.security.api.AccessControlList) SearchServiceDatabaseException(org.opencastproject.search.impl.persistence.SearchServiceDatabaseException) User(org.opencastproject.security.api.User) SolrServerException(org.apache.solr.client.solrj.SolrServerException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) SearchException(org.opencastproject.search.api.SearchException) Date(java.util.Date)

Example 92 with AccessControlList

use of org.opencastproject.security.api.AccessControlList 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 93 with AccessControlList

use of org.opencastproject.security.api.AccessControlList 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)

Example 94 with AccessControlList

use of org.opencastproject.security.api.AccessControlList in project opencast by opencast.

the class SchedulerServiceImplTest method beforeClass.

@BeforeClass
public static void beforeClass() throws Exception {
    wfProperties.put("test", "true");
    wfProperties.put("clear", "all");
    wfPropertiesUpdated.put("test", "false");
    wfPropertiesUpdated.put("skip", "true");
    SecurityService securityService = EasyMock.createNiceMock(SecurityService.class);
    EasyMock.expect(securityService.getUser()).andReturn(new JaxbUser("admin", "provider", new DefaultOrganization(), new JaxbRole("admin", new DefaultOrganization(), "test"))).anyTimes();
    EasyMock.expect(securityService.getOrganization()).andReturn(new DefaultOrganization()).anyTimes();
    schedulerDatabase = new SchedulerServiceDatabaseImpl();
    schedulerDatabase.setEntityManagerFactory(mkEntityManagerFactory(SchedulerServiceDatabaseImpl.PERSISTENCE_UNIT));
    schedulerDatabase.setSecurityService(securityService);
    schedulerDatabase.activate(null);
    workspace = new UnitTestWorkspace();
    MessageSender messageSender = EasyMock.createNiceMock(MessageSender.class);
    final BaseMessage baseMessageMock = EasyMock.createNiceMock(BaseMessage.class);
    MessageReceiver messageReceiver = EasyMock.createNiceMock(MessageReceiver.class);
    EasyMock.expect(messageReceiver.receiveSerializable(EasyMock.anyString(), EasyMock.anyObject(MessageSender.DestinationType.class))).andStubReturn(new FutureTask<>(new Callable<Serializable>() {

        @Override
        public Serializable call() throws Exception {
            return baseMessageMock;
        }
    }));
    AuthorizationService authorizationService = EasyMock.createNiceMock(AuthorizationService.class);
    acl = new AccessControlList(new AccessControlEntry("ROLE_ADMIN", "write", true), new AccessControlEntry("ROLE_ADMIN", "read", true), new AccessControlEntry("ROLE_USER", "read", true));
    EasyMock.expect(authorizationService.getAcl(EasyMock.anyObject(MediaPackage.class), EasyMock.anyObject(AclScope.class))).andReturn(Option.some(acl)).anyTimes();
    OrganizationDirectoryService orgDirectoryService = EasyMock.createNiceMock(OrganizationDirectoryService.class);
    EasyMock.expect(orgDirectoryService.getOrganizations()).andReturn(Arrays.asList((Organization) new DefaultOrganization())).anyTimes();
    EventCatalogUIAdapter episodeAdapter = EasyMock.createMock(EventCatalogUIAdapter.class);
    EasyMock.expect(episodeAdapter.getFlavor()).andReturn(new MediaPackageElementFlavor("dublincore", "episode")).anyTimes();
    EasyMock.expect(episodeAdapter.getOrganization()).andReturn(new DefaultOrganization().getId()).anyTimes();
    EventCatalogUIAdapter extendedAdapter = EasyMock.createMock(EventCatalogUIAdapter.class);
    EasyMock.expect(extendedAdapter.getFlavor()).andReturn(new MediaPackageElementFlavor("extended", "episode")).anyTimes();
    EasyMock.expect(extendedAdapter.getOrganization()).andReturn(new DefaultOrganization().getId()).anyTimes();
    BundleContext bundleContext = EasyMock.createNiceMock(BundleContext.class);
    EasyMock.expect(bundleContext.getProperty(EasyMock.anyString())).andReturn("adminuser").anyTimes();
    ComponentContext componentContext = EasyMock.createNiceMock(ComponentContext.class);
    EasyMock.expect(componentContext.getBundleContext()).andReturn(bundleContext).anyTimes();
    EasyMock.replay(messageSender, baseMessageMock, messageReceiver, authorizationService, securityService, extendedAdapter, episodeAdapter, orgDirectoryService, componentContext, bundleContext);
    testConflictHandler = new TestConflictHandler();
    schedSvc = new SchedulerServiceImpl();
    schedSvc.setAuthorizationService(authorizationService);
    schedSvc.setSecurityService(securityService);
    schedSvc.setPersistence(schedulerDatabase);
    schedSvc.setWorkspace(workspace);
    schedSvc.setMessageSender(messageSender);
    schedSvc.setMessageReceiver(messageReceiver);
    schedSvc.setConflictHandler(testConflictHandler);
    schedSvc.addCatalogUIAdapter(episodeAdapter);
    schedSvc.addCatalogUIAdapter(extendedAdapter);
    schedSvc.setOrgDirectoryService(orgDirectoryService);
    schedSvc.activate(componentContext);
}
Also used : AccessControlList(org.opencastproject.security.api.AccessControlList) ComponentContext(org.osgi.service.component.ComponentContext) MessageSender(org.opencastproject.message.broker.api.MessageSender) AccessControlEntry(org.opencastproject.security.api.AccessControlEntry) JaxbUser(org.opencastproject.security.api.JaxbUser) MediaPackageElementFlavor(org.opencastproject.mediapackage.MediaPackageElementFlavor) Callable(java.util.concurrent.Callable) JaxbRole(org.opencastproject.security.api.JaxbRole) SchedulerServiceDatabaseImpl(org.opencastproject.scheduler.impl.persistence.SchedulerServiceDatabaseImpl) BaseMessage(org.opencastproject.message.broker.api.BaseMessage) MessageReceiver(org.opencastproject.message.broker.api.MessageReceiver) AuthorizationService(org.opencastproject.security.api.AuthorizationService) SecurityService(org.opencastproject.security.api.SecurityService) EventCatalogUIAdapter(org.opencastproject.metadata.dublincore.EventCatalogUIAdapter) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization) OrganizationDirectoryService(org.opencastproject.security.api.OrganizationDirectoryService) BundleContext(org.osgi.framework.BundleContext) BeforeClass(org.junit.BeforeClass)

Example 95 with AccessControlList

use of org.opencastproject.security.api.AccessControlList in project opencast by opencast.

the class SchedulerUtilTest method testCalculateChecksum.

@Test
public void testCalculateChecksum() throws Exception {
    String extendedFlavorType = "extended";
    DublinCoreCatalog dc = SchedulerServiceImplTest.generateExtendedEvent(Opt.<String>none(), extendedFlavorType);
    FileUtils.writeStringToFile(workspaceFile, dc.toXmlString(), "UTF-8");
    List<MediaPackageElementFlavor> catalogAdapterFlavors = new ArrayList<>();
    catalogAdapterFlavors.add(new MediaPackageElementFlavor(extendedFlavorType, "episode"));
    AccessControlList acl = new AccessControlList(new AccessControlEntry("ROLE_ADMIN", "write", true));
    Date start = new Date(DateTimeSupport.fromUTC("2008-03-16T14:00:00Z"));
    Date end = new Date(DateTimeSupport.fromUTC("2008-03-16T15:00:00Z"));
    String captureDeviceID = "demo";
    String seriesId = "series1";
    Set<String> userIds = new HashSet<>();
    userIds.add("user2");
    userIds.add("user1");
    MediaPackage mp = SchedulerServiceImplTest.generateEvent(Opt.<String>none());
    mp.setSeries(seriesId);
    DublinCoreCatalog event = SchedulerServiceImplTest.generateEvent(captureDeviceID, start, end);
    event.set(PROPERTY_CREATED, EncodingSchemeUtils.encodeDate(start, Precision.Minute));
    String catalogId = UUID.randomUUID().toString();
    MediaPackageElement catalog = mp.add(new URI("location" + catalogId), Type.Catalog, event.getFlavor());
    catalog.setIdentifier(catalogId);
    String extendedCatalogId = UUID.randomUUID().toString();
    MediaPackageElement extendedCatalog = mp.add(new URI("location" + extendedCatalogId), Type.Catalog, dc.getFlavor());
    extendedCatalog.setIdentifier(extendedCatalogId);
    Map<String, String> caProperties = SchedulerServiceImplTest.generateCaptureAgentMetadata("demo");
    Map<String, String> wfProperties = new HashMap<String, String>();
    wfProperties.put("test", "true");
    wfProperties.put("clear", "all");
    String expectedChecksum = "91f54dbcb65d2759e79f1da9edce7915";
    String checksum = SchedulerUtil.calculateChecksum(workspace, catalogAdapterFlavors, start, end, captureDeviceID, userIds, mp, Opt.some(event), wfProperties, caProperties, false, acl);
    Assert.assertEquals(expectedChecksum, checksum);
    // change start date
    start = new Date();
    checksum = SchedulerUtil.calculateChecksum(workspace, catalogAdapterFlavors, start, end, captureDeviceID, userIds, mp, Opt.some(event), wfProperties, caProperties, false, acl);
    Assert.assertNotEquals(expectedChecksum, checksum);
    // change end date
    start = new Date(DateTimeSupport.fromUTC("2008-03-16T14:00:00Z"));
    end = new Date();
    checksum = SchedulerUtil.calculateChecksum(workspace, catalogAdapterFlavors, start, end, captureDeviceID, userIds, mp, Opt.some(event), wfProperties, caProperties, false, acl);
    Assert.assertNotEquals(expectedChecksum, checksum);
    // change device
    end = new Date(DateTimeSupport.fromUTC("2008-03-16T15:00:00Z"));
    captureDeviceID = "demo1";
    checksum = SchedulerUtil.calculateChecksum(workspace, catalogAdapterFlavors, start, end, captureDeviceID, userIds, mp, Opt.some(event), wfProperties, caProperties, false, acl);
    Assert.assertNotEquals(expectedChecksum, checksum);
    // change users
    captureDeviceID = "demo";
    userIds.add("test");
    checksum = SchedulerUtil.calculateChecksum(workspace, catalogAdapterFlavors, start, end, captureDeviceID, userIds, mp, Opt.some(event), wfProperties, caProperties, false, acl);
    Assert.assertNotEquals(expectedChecksum, checksum);
    // change episode dublincore
    userIds.remove("test");
    catalog.setChecksum(null);
    event.set(PROPERTY_CREATED, EncodingSchemeUtils.encodeDate(end, Precision.Minute));
    checksum = SchedulerUtil.calculateChecksum(workspace, catalogAdapterFlavors, start, end, captureDeviceID, userIds, mp, Opt.some(event), wfProperties, caProperties, false, acl);
    Assert.assertNotEquals(expectedChecksum, checksum);
    // change extended dublincore
    catalog.setChecksum(null);
    event.set(PROPERTY_CREATED, EncodingSchemeUtils.encodeDate(start, Precision.Minute));
    extendedCatalog.setChecksum(null);
    dc.set(PROPERTY_CREATED, EncodingSchemeUtils.encodeDate(start, Precision.Minute));
    FileUtils.writeStringToFile(workspaceFile, dc.toXmlString(), "UTF-8");
    checksum = SchedulerUtil.calculateChecksum(workspace, catalogAdapterFlavors, start, end, captureDeviceID, userIds, mp, Opt.some(event), wfProperties, caProperties, false, acl);
    Assert.assertNotEquals(expectedChecksum, checksum);
    // change wf properties
    extendedCatalog.setChecksum(null);
    dc.remove(PROPERTY_CREATED);
    FileUtils.writeStringToFile(workspaceFile, dc.toXmlString(), "UTF-8");
    wfProperties.put("change", "change");
    checksum = SchedulerUtil.calculateChecksum(workspace, catalogAdapterFlavors, start, end, captureDeviceID, userIds, mp, Opt.some(event), wfProperties, caProperties, false, acl);
    Assert.assertNotEquals(expectedChecksum, checksum);
    // change ca properties
    wfProperties.remove("change");
    caProperties.put("change", "change");
    checksum = SchedulerUtil.calculateChecksum(workspace, catalogAdapterFlavors, start, end, captureDeviceID, userIds, mp, Opt.some(event), wfProperties, caProperties, false, acl);
    Assert.assertNotEquals(expectedChecksum, checksum);
    // change opt out status
    caProperties.remove("change");
    checksum = SchedulerUtil.calculateChecksum(workspace, catalogAdapterFlavors, start, end, captureDeviceID, userIds, mp, Opt.some(event), wfProperties, caProperties, true, acl);
    Assert.assertNotEquals(expectedChecksum, checksum);
    checksum = SchedulerUtil.calculateChecksum(workspace, catalogAdapterFlavors, start, end, captureDeviceID, userIds, mp, Opt.some(event), wfProperties, caProperties, false, acl);
    Assert.assertEquals(expectedChecksum, checksum);
    // change access control list
    checksum = SchedulerUtil.calculateChecksum(workspace, catalogAdapterFlavors, start, end, captureDeviceID, userIds, mp, Opt.some(event), wfProperties, caProperties, false, new AccessControlList(new AccessControlEntry("ROLE_ADMIN", "write", false)));
    Assert.assertNotEquals(expectedChecksum, checksum);
}
Also used : AccessControlList(org.opencastproject.security.api.AccessControlList) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) AccessControlEntry(org.opencastproject.security.api.AccessControlEntry) MediaPackageElementFlavor(org.opencastproject.mediapackage.MediaPackageElementFlavor) URI(java.net.URI) Date(java.util.Date) MediaPackageElement(org.opencastproject.mediapackage.MediaPackageElement) MediaPackage(org.opencastproject.mediapackage.MediaPackage) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog) HashSet(java.util.HashSet) Test(org.junit.Test)

Aggregations

AccessControlList (org.opencastproject.security.api.AccessControlList)108 NotFoundException (org.opencastproject.util.NotFoundException)46 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)38 AccessControlEntry (org.opencastproject.security.api.AccessControlEntry)30 MediaPackage (org.opencastproject.mediapackage.MediaPackage)27 Test (org.junit.Test)26 IOException (java.io.IOException)22 Organization (org.opencastproject.security.api.Organization)22 User (org.opencastproject.security.api.User)21 DublinCoreCatalog (org.opencastproject.metadata.dublincore.DublinCoreCatalog)19 ArrayList (java.util.ArrayList)18 SeriesException (org.opencastproject.series.api.SeriesException)18 ManagedAcl (org.opencastproject.authorization.xacml.manager.api.ManagedAcl)16 MediaPackageException (org.opencastproject.mediapackage.MediaPackageException)16 Date (java.util.Date)15 SchedulerException (org.opencastproject.scheduler.api.SchedulerException)14 Path (javax.ws.rs.Path)13 RestQuery (org.opencastproject.util.doc.rest.RestQuery)13 WebApplicationException (javax.ws.rs.WebApplicationException)12 File (java.io.File)10