Search in sources :

Example 1 with Id

use of org.opencastproject.mediapackage.identifier.Id in project opencast by opencast.

the class IndexServiceImplTest method testCreateEventInputNormalExpectsCreatedEvent.

@Test
public void testCreateEventInputNormalExpectsCreatedEvent() throws Exception {
    String expectedTitle = "Test Event Creation";
    String username = "akm220";
    String org = "mh_default_org";
    String[] creators = new String[] {};
    Id mpId = new IdImpl("mp-id");
    String testResourceLocation = "/events/create-event.json";
    JSONObject metadataJson = (JSONObject) parser.parse(IOUtils.toString(IndexServiceImplTest.class.getResourceAsStream(testResourceLocation)));
    Capture<Catalog> result = EasyMock.newCapture();
    Capture<String> mediapackageIdResult = EasyMock.newCapture();
    Capture<String> catalogIdResult = EasyMock.newCapture();
    Capture<String> filenameResult = EasyMock.newCapture();
    Capture<InputStream> catalogResult = EasyMock.newCapture();
    Capture<String> mediapackageTitleResult = EasyMock.newCapture();
    SecurityService securityService = setupSecurityService(username, org);
    Workspace workspace = EasyMock.createMock(Workspace.class);
    EasyMock.expect(workspace.put(EasyMock.capture(mediapackageIdResult), EasyMock.capture(catalogIdResult), EasyMock.capture(filenameResult), EasyMock.capture(catalogResult))).andReturn(new URI("catalog.xml"));
    EasyMock.replay(workspace);
    // Create Common Event Catalog UI Adapter
    CommonEventCatalogUIAdapter commonEventCatalogUIAdapter = setupCommonCatalogUIAdapter(workspace).getA();
    // Setup mediapackage.
    MediaPackage mediapackage = EasyMock.createMock(MediaPackage.class);
    mediapackage.add(EasyMock.capture(result));
    EasyMock.expectLastCall();
    EasyMock.expect(mediapackage.getCatalogs(EasyMock.anyObject(MediaPackageElementFlavor.class))).andReturn(new Catalog[] {});
    EasyMock.expect(mediapackage.getIdentifier()).andReturn(mpId).anyTimes();
    EasyMock.expect(mediapackage.getCreators()).andReturn(creators);
    mediapackage.addCreator("");
    EasyMock.expectLastCall();
    mediapackage.setTitle(EasyMock.capture(mediapackageTitleResult));
    EasyMock.expectLastCall();
    EasyMock.expect(mediapackage.getElements()).andReturn(new MediaPackageElement[] {}).anyTimes();
    EasyMock.expect(mediapackage.getCatalogs(EasyMock.anyObject(MediaPackageElementFlavor.class))).andReturn(new Catalog[] {}).anyTimes();
    EasyMock.expect(mediapackage.getSeries()).andReturn(null).anyTimes();
    mediapackage.setSeries(EasyMock.anyString());
    mediapackage.setSeriesTitle(EasyMock.anyString());
    EasyMock.expectLastCall();
    EasyMock.replay(mediapackage);
    IngestService ingestService = setupIngestService(mediapackage, Capture.<InputStream>newInstance());
    // Setup Authorization Service
    Tuple<MediaPackage, Attachment> returnValue = new Tuple<MediaPackage, Attachment>(mediapackage, null);
    AuthorizationService authorizationService = EasyMock.createMock(AuthorizationService.class);
    EasyMock.expect(authorizationService.setAcl(EasyMock.anyObject(MediaPackage.class), EasyMock.anyObject(AclScope.class), EasyMock.anyObject(AccessControlList.class))).andReturn(returnValue);
    EasyMock.replay(authorizationService);
    // Run Test
    IndexServiceImpl indexServiceImpl = new IndexServiceImpl();
    indexServiceImpl.setAuthorizationService(setupAuthorizationService(mediapackage));
    indexServiceImpl.setIngestService(ingestService);
    indexServiceImpl.setCommonEventCatalogUIAdapter(commonEventCatalogUIAdapter);
    indexServiceImpl.addCatalogUIAdapter(commonEventCatalogUIAdapter);
    indexServiceImpl.setUserDirectoryService(noUsersUserDirectoryService);
    indexServiceImpl.setSecurityService(securityService);
    indexServiceImpl.setWorkspace(workspace);
    indexServiceImpl.createEvent(metadataJson, mediapackage);
    assertTrue("The catalog must be added to the mediapackage", result.hasCaptured());
    assertEquals("The catalog should have been added to the correct mediapackage", mpId.toString(), mediapackageIdResult.getValue());
    assertTrue("The catalog should have a new id", catalogIdResult.hasCaptured());
    assertTrue("The catalog should have a new filename", filenameResult.hasCaptured());
    assertTrue("The catalog should have been added to the input stream", catalogResult.hasCaptured());
    assertTrue("The mediapackage should have had its title updated", catalogResult.hasCaptured());
    assertEquals("The mediapackage title should have been updated.", expectedTitle, mediapackageTitleResult.getValue());
    assertTrue("The catalog should have been created", catalogResult.hasCaptured());
}
Also used : AccessControlList(org.opencastproject.security.api.AccessControlList) Attachment(org.opencastproject.mediapackage.Attachment) AclScope(org.opencastproject.security.api.AclScope) URI(java.net.URI) IdImpl(org.opencastproject.mediapackage.identifier.IdImpl) SecurityService(org.opencastproject.security.api.SecurityService) MediaPackageElement(org.opencastproject.mediapackage.MediaPackageElement) CommonEventCatalogUIAdapter(org.opencastproject.index.service.catalog.adapter.events.CommonEventCatalogUIAdapter) IngestService(org.opencastproject.ingest.api.IngestService) InputStream(java.io.InputStream) MediaPackageElementFlavor(org.opencastproject.mediapackage.MediaPackageElementFlavor) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog) Catalog(org.opencastproject.mediapackage.Catalog) JSONObject(org.json.simple.JSONObject) AuthorizationService(org.opencastproject.security.api.AuthorizationService) MediaPackage(org.opencastproject.mediapackage.MediaPackage) Id(org.opencastproject.mediapackage.identifier.Id) Tuple(org.opencastproject.util.data.Tuple) Workspace(org.opencastproject.workspace.api.Workspace) Test(org.junit.Test)

Example 2 with Id

use of org.opencastproject.mediapackage.identifier.Id in project opencast by opencast.

the class DublinCoreCatalogUIAdapterTest method setUp.

@Before
public void setUp() throws URISyntaxException, NotFoundException, IOException, ListProviderException {
    startDateTimeDurationCatalog = new FileInputStream(new File(getClass().getResource("/catalog-adapter/start-date-time-duration.xml").toURI()));
    dc = DublinCores.read(startDateTimeDurationCatalog);
    metadata = new DublinCoreMetadataCollection();
    startDateMetadataField = MetadataField.createTemporalStartDateMetadata(TEMPORAL_DUBLIN_CORE_KEY, Opt.some("startDate"), "START_DATE_LABEL", false, false, "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Opt.<Integer>none(), Opt.<String>none());
    durationMetadataField = MetadataField.createDurationMetadataField(TEMPORAL_DUBLIN_CORE_KEY, Opt.some("duration"), "DURATION_LABEL", false, false, Opt.<Integer>none(), Opt.<String>none());
    TreeMap<String, String> collection = new TreeMap<String, String>();
    collection.put("Entry 1", "Value 1");
    collection.put("Entry 2", "Value 2");
    collection.put("Entry 3", "Value 3");
    BundleContext bundleContext = EasyMock.createNiceMock(BundleContext.class);
    EasyMock.replay(bundleContext);
    listProvidersService = EasyMock.createMock(ListProvidersService.class);
    EasyMock.expect(listProvidersService.getList(EasyMock.anyString(), EasyMock.anyObject(ResourceListQueryImpl.class), EasyMock.anyObject(Organization.class), EasyMock.anyBoolean())).andReturn(collection).anyTimes();
    EasyMock.replay(listProvidersService);
    Properties props = new Properties();
    InputStream in = getClass().getResourceAsStream("/catalog-adapter/event.properties");
    props.load(in);
    in.close();
    eventProperties = PropertiesUtil.toDictionary(props);
    mediaPackageElementFlavor = new MediaPackageElementFlavor(FLAVOR_STRING.split("/")[0], FLAVOR_STRING.split("/")[1]);
    eventDublincoreURI = getClass().getResource("/catalog-adapter/dublincore.xml").toURI();
    outputCatalog = testFolder.newFile("out.xml");
    Capture<String> mediapackageIDCapture = EasyMock.newCapture();
    Capture<String> catalogIDCapture = EasyMock.newCapture();
    Capture<String> filenameCapture = EasyMock.newCapture();
    writtenCatalog = EasyMock.newCapture();
    workspace = EasyMock.createMock(Workspace.class);
    EasyMock.expect(workspace.read(eventDublincoreURI)).andAnswer(() -> new FileInputStream(new File(eventDublincoreURI)));
    EasyMock.expect(workspace.put(EasyMock.capture(mediapackageIDCapture), EasyMock.capture(catalogIDCapture), EasyMock.capture(filenameCapture), EasyMock.capture(writtenCatalog))).andReturn(outputCatalog.toURI());
    EasyMock.replay(workspace);
    Catalog eventCatalog = EasyMock.createMock(Catalog.class);
    EasyMock.expect(eventCatalog.getIdentifier()).andReturn("CatalogID").anyTimes();
    EasyMock.expect(eventCatalog.getURI()).andReturn(eventDublincoreURI).anyTimes();
    eventCatalog.setURI(outputCatalog.toURI());
    EasyMock.expectLastCall();
    eventCatalog.setChecksum(null);
    EasyMock.expectLastCall();
    EasyMock.replay(eventCatalog);
    Catalog[] catalogs = { eventCatalog };
    Id id = EasyMock.createMock(Id.class);
    EasyMock.replay(id);
    mediapackage = EasyMock.createMock(MediaPackage.class);
    EasyMock.expect(mediapackage.getCatalogs(mediaPackageElementFlavor)).andReturn(catalogs).anyTimes();
    EasyMock.expect(mediapackage.getIdentifier()).andReturn(id).anyTimes();
    EasyMock.replay(mediapackage);
    dictionary = new Hashtable<String, String>();
    dictionary.put(CONF_ORGANIZATION_KEY, ORGANIZATION_STRING);
    dictionary.put(CONF_FLAVOR_KEY, FLAVOR_STRING);
    dictionary.put(CONF_TITLE_KEY, TITLE_STRING);
    dictionary.put(MetadataField.CONFIG_PROPERTY_PREFIX + ".title." + MetadataField.CONFIG_INPUT_ID_KEY, title);
    dictionary.put(MetadataField.CONFIG_PROPERTY_PREFIX + ".title." + MetadataField.CONFIG_LABEL_KEY, label);
    dictionary.put(MetadataField.CONFIG_PROPERTY_PREFIX + ".title." + MetadataField.CONFIG_TYPE_KEY, type);
    dictionary.put(MetadataField.CONFIG_PROPERTY_PREFIX + ".title." + MetadataField.CONFIG_READ_ONLY_KEY, readOnly);
    dictionary.put(MetadataField.CONFIG_PROPERTY_PREFIX + ".title." + MetadataField.CONFIG_REQUIRED_KEY, required);
    dictionary.put(MetadataField.CONFIG_PROPERTY_PREFIX + ".title." + MetadataField.CONFIG_LIST_PROVIDER_KEY, listProvider);
    dictionary.put(MetadataField.CONFIG_PROPERTY_PREFIX + ".title." + MetadataField.CONFIG_COLLECTION_ID_KEY, collectionID);
}
Also used : ListProvidersService(org.opencastproject.index.service.resources.list.api.ListProvidersService) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) TreeMap(java.util.TreeMap) Properties(java.util.Properties) MediaPackageElementFlavor(org.opencastproject.mediapackage.MediaPackageElementFlavor) FileInputStream(java.io.FileInputStream) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog) Catalog(org.opencastproject.mediapackage.Catalog) MediaPackage(org.opencastproject.mediapackage.MediaPackage) Id(org.opencastproject.mediapackage.identifier.Id) File(java.io.File) BundleContext(org.osgi.framework.BundleContext) Workspace(org.opencastproject.workspace.api.Workspace) Before(org.junit.Before)

Example 3 with Id

use of org.opencastproject.mediapackage.identifier.Id in project opencast by opencast.

the class SchedulerServiceImpl method addMultipleEventInternal.

private Map<String, Period> addMultipleEventInternal(List<Period> periods, String captureAgentId, Set<String> userIds, MediaPackage templateMp, Map<String, String> wfProperties, Map<String, String> caMetadata, String modificationOrigin, Opt<Boolean> optOutStatus, Opt<String> schedulingSource, Opt<String> trxId) throws SchedulerException {
    notNull(periods, "periods");
    requireTrue(periods.size() > 0, "periods");
    notEmpty(captureAgentId, "captureAgentId");
    notNull(userIds, "userIds");
    notNull(templateMp, "mediaPackages");
    notNull(wfProperties, "wfProperties");
    notNull(caMetadata, "caMetadata");
    notEmpty(modificationOrigin, "modificationOrigin");
    notNull(optOutStatus, "optOutStatus");
    notNull(schedulingSource, "schedulingSource");
    notNull(trxId, "trxId");
    Map<String, Period> scheduledEvents = new LinkedHashMap<>();
    try {
        LinkedList<Id> ids = new LinkedList<>();
        AQueryBuilder qb = assetManager.createQuery();
        Predicate p = null;
        // While we don't have a list of IDs equal to the number of periods
        while (ids.size() <= periods.size()) {
            // Create a list of IDs equal to the number of periods, along with a set of AM predicates
            while (ids.size() <= periods.size()) {
                Id id = new IdImpl(UUID.randomUUID().toString());
                ids.add(id);
                Predicate np = qb.mediaPackageId(id.compact());
                // Haha, p = np jokes with the AM query language. Ha. Haha. Ha.  (Sob...)
                if (null == p) {
                    p = np;
                } else {
                    p = p.or(np);
                }
            }
            // Select the list of ids which alread exist.  Hint: this needs to be zero
            AResult result = qb.select(qb.nothing()).where(withOrganization(qb).and(p).and(qb.version().isLatest())).run();
            // If there is conflict, clear the list and start over
            if (result.getTotalSize() > 0) {
                ids.clear();
            }
        }
        Opt<String> seriesId = Opt.nul(StringUtils.trimToNull(templateMp.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 events, source '{}' is currently locked due to an active transaction!", 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(periods, captureAgentId, TimeZone.getDefault());
                if (conflictingEvents.size() > 0) {
                    logger.info("Unable to add events, conflicting events found: {}", conflictingEvents);
                    throw new SchedulerConflictException("Unable to add event, conflicting events found");
                }
            }
        }
        // counter for index into the list of mediapackages
        int counter = 0;
        for (Period event : periods) {
            MediaPackage mediaPackage = (MediaPackage) templateMp.clone();
            Date startDate = new Date(event.getStart().getTime());
            Date endDate = new Date(event.getEnd().getTime());
            Id id = ids.get(counter);
            // Get, or make, the DC catalog
            DublinCoreCatalog dc;
            Opt<DublinCoreCatalog> dcOpt = DublinCoreUtil.loadEpisodeDublinCore(workspace, templateMp);
            if (dcOpt.isSome()) {
                dc = dcOpt.get();
                dc = (DublinCoreCatalog) dc.clone();
                // make sure to bind the OC_PROPERTY namespace
                dc.addBindings(XmlNamespaceContext.mk(XmlNamespaceBinding.mk(DublinCores.OC_PROPERTY_NS_PREFIX, DublinCores.OC_PROPERTY_NS_URI)));
            } else {
                dc = DublinCores.mkOpencastEpisode().getCatalog();
            }
            // Set the new media package identifier
            mediaPackage.setIdentifier(id);
            // Update dublincore title and temporal
            String newTitle = dc.getFirst(DublinCore.PROPERTY_TITLE) + String.format(" %0" + Integer.toString(periods.size()).length() + "d", ++counter);
            dc.set(DublinCore.PROPERTY_TITLE, newTitle);
            DublinCoreValue eventTime = EncodingSchemeUtils.encodePeriod(new DCMIPeriod(startDate, endDate), Precision.Second);
            dc.set(DublinCore.PROPERTY_TEMPORAL, eventTime);
            mediaPackage = updateDublincCoreCatalog(mediaPackage, dc);
            mediaPackage.setTitle(newTitle);
            String mediaPackageId = mediaPackage.getIdentifier().compact();
            // Converting from iCal4j DateTime objects to plain Date objects to prevent AMQ issues below
            Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
            cal.setTime(event.getStart());
            Date startDateTime = cal.getTime();
            cal.setTime(event.getEnd());
            Date endDateTime = cal.getTime();
            // 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);
            }
            scheduledEvents.put(mediaPackageId, event);
            for (MediaPackageElement mediaPackageElement : mediaPackage.getElements()) {
                try {
                    workspace.delete(mediaPackage.getIdentifier().toString(), mediaPackageElement.getIdentifier());
                } catch (NotFoundException | IOException e) {
                    logger.warn("Failed to delete media package element", e);
                }
            }
        }
        return scheduledEvents;
    } catch (SchedulerException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Failed to create events: {}", 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) IdImpl(org.opencastproject.mediapackage.identifier.IdImpl) LinkedHashMap(java.util.LinkedHashMap) Predicate(org.opencastproject.assetmanager.api.query.Predicate) SchedulerTransactionLockException(org.opencastproject.scheduler.api.SchedulerTransactionLockException) MediaPackageElement(org.opencastproject.mediapackage.MediaPackageElement) AResult(org.opencastproject.assetmanager.api.query.AResult) DublinCoreValue(org.opencastproject.metadata.dublincore.DublinCoreValue) Calendar(java.util.Calendar) SchedulerConflictException(org.opencastproject.scheduler.api.SchedulerConflictException) DCMIPeriod(org.opencastproject.metadata.dublincore.DCMIPeriod) Period(net.fortuna.ical4j.model.Period) DCMIPeriod(org.opencastproject.metadata.dublincore.DCMIPeriod) IOException(java.io.IOException) LinkedList(java.util.LinkedList) 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) PropertyId(org.opencastproject.assetmanager.api.PropertyId) Id(org.opencastproject.mediapackage.identifier.Id) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog)

Example 4 with Id

use of org.opencastproject.mediapackage.identifier.Id in project opencast by opencast.

the class IndexServiceImplTest method testCreateEventInputNormalExpectsCreatedScheduledEvent.

@Test
public void testCreateEventInputNormalExpectsCreatedScheduledEvent() throws Exception {
    String expectedTitle = "Test Event Creation";
    String username = "akm220";
    String org = "mh_default_org";
    String[] creators = new String[] {};
    Id mpId = new IdImpl("mp-id");
    String testResourceLocation = "/events/create-scheduled-event.json";
    JSONObject metadataJson = (JSONObject) parser.parse(IOUtils.toString(IndexServiceImplTest.class.getResourceAsStream(testResourceLocation)));
    Capture<Catalog> result = EasyMock.newCapture();
    Capture<String> mediapackageIdResult = EasyMock.newCapture();
    Capture<String> catalogIdResult = EasyMock.newCapture();
    Capture<String> filenameResult = EasyMock.newCapture();
    Capture<InputStream> catalogResult = EasyMock.newCapture();
    Capture<String> mediapackageTitleResult = EasyMock.newCapture();
    SecurityService securityService = setupSecurityService(username, org);
    Workspace workspace = EasyMock.createMock(Workspace.class);
    EasyMock.expect(workspace.put(EasyMock.capture(mediapackageIdResult), EasyMock.capture(catalogIdResult), EasyMock.capture(filenameResult), EasyMock.capture(catalogResult))).andReturn(new URI("catalog.xml"));
    EasyMock.replay(workspace);
    // Create Common Event Catalog UI Adapter
    CommonEventCatalogUIAdapter commonEventCatalogUIAdapter = setupCommonCatalogUIAdapter(workspace).getA();
    // Setup mediapackage.
    MediaPackage mediapackage = EasyMock.createMock(MediaPackage.class);
    mediapackage.add(EasyMock.capture(result));
    EasyMock.expectLastCall();
    EasyMock.expect(mediapackage.getCatalogs(EasyMock.anyObject(MediaPackageElementFlavor.class))).andReturn(new Catalog[] {});
    EasyMock.expect(mediapackage.getIdentifier()).andReturn(mpId).anyTimes();
    EasyMock.expect(mediapackage.getCreators()).andReturn(creators);
    mediapackage.addCreator("");
    EasyMock.expectLastCall();
    mediapackage.setTitle(EasyMock.capture(mediapackageTitleResult));
    EasyMock.expectLastCall();
    EasyMock.expect(mediapackage.getElements()).andReturn(new MediaPackageElement[] {}).anyTimes();
    EasyMock.expect(mediapackage.getCatalogs(EasyMock.anyObject(MediaPackageElementFlavor.class))).andReturn(new Catalog[] {}).anyTimes();
    EasyMock.expect(mediapackage.getSeries()).andReturn(null).anyTimes();
    mediapackage.setSeries(EasyMock.anyString());
    EasyMock.expectLastCall();
    EasyMock.replay(mediapackage);
    IngestService ingestService = setupIngestService(mediapackage, Capture.<InputStream>newInstance());
    // Setup Authorization Service
    Tuple<MediaPackage, Attachment> returnValue = new Tuple<MediaPackage, Attachment>(mediapackage, null);
    AuthorizationService authorizationService = EasyMock.createMock(AuthorizationService.class);
    EasyMock.expect(authorizationService.setAcl(EasyMock.anyObject(MediaPackage.class), EasyMock.anyObject(AclScope.class), EasyMock.anyObject(AccessControlList.class))).andReturn(returnValue);
    EasyMock.replay(authorizationService);
    CaptureAgentStateService captureAgentStateService = setupCaptureAgentStateService();
    Capture<Date> captureStart = EasyMock.newCapture();
    Capture<Date> captureEnd = EasyMock.newCapture();
    SchedulerService schedulerService = EasyMock.createNiceMock(SchedulerService.class);
    schedulerService.addEvent(EasyMock.capture(captureStart), EasyMock.capture(captureEnd), EasyMock.anyString(), EasyMock.<Set<String>>anyObject(), EasyMock.anyObject(MediaPackage.class), EasyMock.<Map<String, String>>anyObject(), EasyMock.<Map<String, String>>anyObject(), EasyMock.<Opt<Boolean>>anyObject(), EasyMock.<Opt<String>>anyObject(), EasyMock.anyString());
    EasyMock.expectLastCall().once();
    EasyMock.replay(schedulerService);
    // Run Test
    IndexServiceImpl indexServiceImpl = new IndexServiceImpl();
    indexServiceImpl.setAuthorizationService(setupAuthorizationService(mediapackage));
    indexServiceImpl.setIngestService(ingestService);
    indexServiceImpl.setCommonEventCatalogUIAdapter(commonEventCatalogUIAdapter);
    indexServiceImpl.addCatalogUIAdapter(commonEventCatalogUIAdapter);
    indexServiceImpl.setSecurityService(securityService);
    indexServiceImpl.setUserDirectoryService(noUsersUserDirectoryService);
    indexServiceImpl.setWorkspace(workspace);
    indexServiceImpl.setCaptureAgentStateService(captureAgentStateService);
    indexServiceImpl.setSchedulerService(schedulerService);
    String scheduledEvent = indexServiceImpl.createEvent(metadataJson, mediapackage);
    Assert.assertEquals(mediapackage.getIdentifier().compact(), scheduledEvent);
    assertTrue("The catalog must be added to the mediapackage", result.hasCaptured());
    assertEquals("The catalog should have been added to the correct mediapackage", mpId.toString(), mediapackageIdResult.getValue());
    assertTrue("The catalog should have a new id", catalogIdResult.hasCaptured());
    assertTrue("The catalog should have a new filename", filenameResult.hasCaptured());
    assertTrue("The catalog should have been added to the input stream", catalogResult.hasCaptured());
    assertTrue("The mediapackage should have had its title updated", catalogResult.hasCaptured());
    assertEquals("The mediapackage title should have been updated.", expectedTitle, mediapackageTitleResult.getValue());
    assertTrue("The catalog should have been created", catalogResult.hasCaptured());
    assertTrue(captureStart.hasCaptured());
    assertTrue(captureEnd.hasCaptured());
    Assert.assertEquals(new Date(DateTimeSupport.fromUTC("2008-03-16T14:00:00Z")), captureStart.getValue());
    Assert.assertEquals(new Date(DateTimeSupport.fromUTC("2008-03-16T14:01:00Z")), captureEnd.getValue());
}
Also used : AccessControlList(org.opencastproject.security.api.AccessControlList) SchedulerService(org.opencastproject.scheduler.api.SchedulerService) Attachment(org.opencastproject.mediapackage.Attachment) AclScope(org.opencastproject.security.api.AclScope) URI(java.net.URI) IdImpl(org.opencastproject.mediapackage.identifier.IdImpl) SecurityService(org.opencastproject.security.api.SecurityService) MediaPackageElement(org.opencastproject.mediapackage.MediaPackageElement) CommonEventCatalogUIAdapter(org.opencastproject.index.service.catalog.adapter.events.CommonEventCatalogUIAdapter) CaptureAgentStateService(org.opencastproject.capture.admin.api.CaptureAgentStateService) IngestService(org.opencastproject.ingest.api.IngestService) InputStream(java.io.InputStream) MediaPackageElementFlavor(org.opencastproject.mediapackage.MediaPackageElementFlavor) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog) Catalog(org.opencastproject.mediapackage.Catalog) Date(java.util.Date) JSONObject(org.json.simple.JSONObject) AuthorizationService(org.opencastproject.security.api.AuthorizationService) MediaPackage(org.opencastproject.mediapackage.MediaPackage) Id(org.opencastproject.mediapackage.identifier.Id) Tuple(org.opencastproject.util.data.Tuple) Workspace(org.opencastproject.workspace.api.Workspace) Test(org.junit.Test)

Example 5 with Id

use of org.opencastproject.mediapackage.identifier.Id in project opencast by opencast.

the class IndexServiceImplTest method testCreateEventInputNormalExpectsCreatedRecurringEvent.

@Test
public void testCreateEventInputNormalExpectsCreatedRecurringEvent() throws Exception {
    String expectedTitle = "Test Event Creation";
    String username = "akm220";
    String org = "mh_default_org";
    String[] creators = new String[] {};
    Id mpId = new IdImpl("mp-id");
    String testResourceLocation = "/events/create-recurring-event.json";
    JSONObject metadataJson = (JSONObject) parser.parse(IOUtils.toString(IndexServiceImplTest.class.getResourceAsStream(testResourceLocation)));
    Capture<String> mediapackageIdResult = EasyMock.newCapture();
    Capture<String> catalogIdResult = EasyMock.newCapture();
    Capture<String> filenameResult = EasyMock.newCapture();
    Capture<InputStream> catalogResult = EasyMock.newCapture();
    Capture<String> mediapackageTitleResult = EasyMock.newCapture();
    SecurityService securityService = setupSecurityService(username, org);
    Workspace workspace = EasyMock.createMock(Workspace.class);
    EasyMock.expect(workspace.put(EasyMock.capture(mediapackageIdResult), EasyMock.capture(catalogIdResult), EasyMock.capture(filenameResult), EasyMock.capture(catalogResult))).andReturn(new URI("catalog.xml"));
    EasyMock.expect(workspace.read(getClass().getResource("/dublincore.xml").toURI())).andAnswer(() -> getClass().getResourceAsStream("/dublincore.xml")).anyTimes();
    EasyMock.replay(workspace);
    // Create Common Event Catalog UI Adapter
    CommonEventCatalogUIAdapter commonEventCatalogUIAdapter = setupCommonCatalogUIAdapter(workspace).getA();
    // Setup mediapackage.
    MediaPackage mediapackage = EasyMock.createMock(MediaPackage.class);
    EasyMock.expect(mediapackage.clone()).andReturn(mediapackage).anyTimes();
    EasyMock.expect(mediapackage.getSeries()).andReturn(null).anyTimes();
    EasyMock.expect(mediapackage.getCatalogs(EasyMock.anyObject(MediaPackageElementFlavor.class))).andReturn(new Catalog[] { CatalogImpl.fromURI(getClass().getResource("/dublincore.xml").toURI()) });
    EasyMock.expect(mediapackage.getIdentifier()).andReturn(mpId).anyTimes();
    EasyMock.expect(mediapackage.getCreators()).andReturn(creators);
    mediapackage.addCreator("");
    EasyMock.expectLastCall();
    mediapackage.setTitle(EasyMock.capture(mediapackageTitleResult));
    EasyMock.expectLastCall().once();
    mediapackage.setTitle(EasyMock.anyString());
    EasyMock.expectLastCall().times(15);
    EasyMock.expect(mediapackage.getElements()).andReturn(new MediaPackageElement[] {}).anyTimes();
    EasyMock.expect(mediapackage.getCatalogs(EasyMock.anyObject(MediaPackageElementFlavor.class))).andReturn(new Catalog[] {}).anyTimes();
    mediapackage.setIdentifier(EasyMock.anyObject(Id.class));
    EasyMock.expectLastCall().anyTimes();
    mediapackage.setSeries(EasyMock.anyString());
    mediapackage.setSeriesTitle(EasyMock.anyString());
    EasyMock.expectLastCall();
    EasyMock.replay(mediapackage);
    CaptureAgentStateService captureAgentStateService = setupCaptureAgentStateService();
    // Setup scheduler service
    Capture<Date> recurrenceStart = EasyMock.newCapture();
    Capture<Date> recurrenceEnd = EasyMock.newCapture();
    Capture<RRule> rrule = EasyMock.newCapture();
    Capture duration = EasyMock.newCapture();
    Capture<TimeZone> tz = EasyMock.newCapture();
    Capture<Date> schedStart = EasyMock.newCapture();
    Capture<Date> schedEnd = EasyMock.newCapture();
    Capture<RRule> schedRRule = EasyMock.newCapture();
    Capture schedDuration = EasyMock.newCapture();
    Capture<TimeZone> schedTz = EasyMock.newCapture();
    Capture<MediaPackage> mp = EasyMock.newCapture();
    SchedulerService schedulerService = EasyMock.createNiceMock(SchedulerService.class);
    // Look up the expected periods
    EasyMock.expect(schedulerService.calculatePeriods(EasyMock.capture(rrule), EasyMock.capture(recurrenceStart), EasyMock.capture(recurrenceEnd), EasyMock.captureLong(duration), EasyMock.capture(tz))).andAnswer(new IAnswer<List<Period>>() {

        @Override
        public List<Period> answer() throws Throwable {
            return calculatePeriods(rrule.getValue(), recurrenceStart.getValue(), recurrenceEnd.getValue(), (Long) duration.getValue(), tz.getValue());
        }
    }).anyTimes();
    // The actual scheduling
    EasyMock.expect(schedulerService.addMultipleEvents(EasyMock.capture(schedRRule), EasyMock.capture(schedStart), EasyMock.capture(schedEnd), EasyMock.captureLong(schedDuration), EasyMock.capture(schedTz), EasyMock.anyString(), EasyMock.<Set<String>>anyObject(), EasyMock.capture(mp), EasyMock.<Map<String, String>>anyObject(), EasyMock.<Map<String, String>>anyObject(), EasyMock.<Opt<Boolean>>anyObject(), EasyMock.<Opt<String>>anyObject(), EasyMock.anyString())).andAnswer(new IAnswer<Map<String, Period>>() {

        @Override
        public Map<String, Period> answer() throws Throwable {
            List<Period> periods = calculatePeriods(schedRRule.getValue(), schedStart.getValue(), schedEnd.getValue(), (Long) schedDuration.getValue(), schedTz.getValue());
            Map<String, Period> mapping = new LinkedHashMap<>();
            int counter = 0;
            for (Period p : periods) {
                mapping.put(new IdImpl(UUID.randomUUID().toString()).compact(), p);
            }
            return mapping;
        }
    }).anyTimes();
    EasyMock.replay(schedulerService);
    // Run Test
    IndexServiceImpl indexServiceImpl = new IndexServiceImpl();
    indexServiceImpl.setAuthorizationService(setupAuthorizationService(mediapackage));
    indexServiceImpl.setIngestService(setupIngestService(mediapackage, Capture.<InputStream>newInstance()));
    indexServiceImpl.setCommonEventCatalogUIAdapter(commonEventCatalogUIAdapter);
    indexServiceImpl.addCatalogUIAdapter(commonEventCatalogUIAdapter);
    indexServiceImpl.setSecurityService(securityService);
    indexServiceImpl.setUserDirectoryService(noUsersUserDirectoryService);
    indexServiceImpl.setWorkspace(workspace);
    indexServiceImpl.setCaptureAgentStateService(captureAgentStateService);
    indexServiceImpl.setSchedulerService(schedulerService);
    String scheduledEvents = indexServiceImpl.createEvent(metadataJson, mediapackage);
    String[] ids = StringUtils.split(scheduledEvents, ",");
    // We should have as many scheduled events as we do periods
    Assert.assertTrue(ids.length == calculatePeriods(rrule.getValue(), recurrenceStart.getValue(), recurrenceEnd.getValue(), (Long) duration.getValue(), tz.getValue()).size());
    assertEquals("The catalog should have been added to the correct mediapackage", mpId.toString(), mediapackageIdResult.getValue());
    assertTrue("The catalog should have a new id", catalogIdResult.hasCaptured());
    assertTrue("The catalog should have a new filename", filenameResult.hasCaptured());
    assertTrue("The catalog should have been added to the input stream", catalogResult.hasCaptured());
    assertTrue("The mediapackage should have had its title updated", catalogResult.hasCaptured());
    assertEquals("The mediapackage title should have been updated.", expectedTitle, mediapackageTitleResult.getValue());
    assertTrue("The catalog should have been created", catalogResult.hasCaptured());
    // Assert that the start and end recurrence dates captured, along with the duration and recurrence rule
    // This is all used by the scheduling calculation, but not the actual scheduling call
    assertTrue(recurrenceStart.hasCaptured());
    assertTrue(recurrenceEnd.hasCaptured());
    assertTrue(duration.hasCaptured());
    assertTrue(rrule.hasCaptured());
    // Assert that the scheduling call has its necessary data
    assertTrue(schedStart.hasCaptured());
    assertTrue(schedEnd.hasCaptured());
    assertTrue(schedDuration.hasCaptured());
    assertTrue(schedRRule.hasCaptured());
    assertTrue(schedTz.hasCaptured());
    List<Period> pCheck = calculatePeriods(schedRRule.getValue(), schedStart.getValue(), schedEnd.getValue(), (Long) schedDuration.getValue(), schedTz.getValue());
    List<Period> pExpected = calculatePeriods(rrule.getValue(), recurrenceStart.getValue(), recurrenceEnd.getValue(), (Long) duration.getValue(), tz.getValue());
    // Assert that the first capture time is the same as the recurrence start
    assertEquals(pExpected.get(0).getStart(), pCheck.get(0).getStart());
    // Assert that the end of the last capture time is the same as the recurrence end
    assertEquals(pExpected.get(pExpected.size() - 1).getEnd(), pCheck.get(pCheck.size() - 1).getEnd());
}
Also used : SchedulerService(org.opencastproject.scheduler.api.SchedulerService) Set(java.util.Set) RRule(net.fortuna.ical4j.model.property.RRule) URI(java.net.URI) IdImpl(org.opencastproject.mediapackage.identifier.IdImpl) Capture(org.easymock.Capture) LinkedHashMap(java.util.LinkedHashMap) Opt(com.entwinemedia.fn.data.Opt) SecurityService(org.opencastproject.security.api.SecurityService) MediaPackageElement(org.opencastproject.mediapackage.MediaPackageElement) CommonEventCatalogUIAdapter(org.opencastproject.index.service.catalog.adapter.events.CommonEventCatalogUIAdapter) CaptureAgentStateService(org.opencastproject.capture.admin.api.CaptureAgentStateService) InputStream(java.io.InputStream) Period(net.fortuna.ical4j.model.Period) MediaPackageElementFlavor(org.opencastproject.mediapackage.MediaPackageElementFlavor) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog) Catalog(org.opencastproject.mediapackage.Catalog) Date(java.util.Date) IAnswer(org.easymock.IAnswer) TimeZone(java.util.TimeZone) JSONObject(org.json.simple.JSONObject) MediaPackage(org.opencastproject.mediapackage.MediaPackage) Id(org.opencastproject.mediapackage.identifier.Id) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) Workspace(org.opencastproject.workspace.api.Workspace) Test(org.junit.Test)

Aggregations

MediaPackage (org.opencastproject.mediapackage.MediaPackage)10 Id (org.opencastproject.mediapackage.identifier.Id)10 URI (java.net.URI)8 MediaPackageElement (org.opencastproject.mediapackage.MediaPackageElement)8 IdImpl (org.opencastproject.mediapackage.identifier.IdImpl)8 Test (org.junit.Test)7 DublinCoreCatalog (org.opencastproject.metadata.dublincore.DublinCoreCatalog)6 SecurityService (org.opencastproject.security.api.SecurityService)6 Workspace (org.opencastproject.workspace.api.Workspace)6 InputStream (java.io.InputStream)5 Catalog (org.opencastproject.mediapackage.Catalog)5 JSONObject (org.json.simple.JSONObject)4 CommonEventCatalogUIAdapter (org.opencastproject.index.service.catalog.adapter.events.CommonEventCatalogUIAdapter)4 MediaPackageElementFlavor (org.opencastproject.mediapackage.MediaPackageElementFlavor)4 AccessControlList (org.opencastproject.security.api.AccessControlList)4 Date (java.util.Date)3 IngestService (org.opencastproject.ingest.api.IngestService)3 Attachment (org.opencastproject.mediapackage.Attachment)3 AclScope (org.opencastproject.security.api.AclScope)3 LinkedHashMap (java.util.LinkedHashMap)2