Search in sources :

Example 16 with MetadataList

use of org.opencastproject.index.service.catalog.adapter.MetadataList in project opencast by opencast.

the class SeriesEndpoint method deserializeMetadataList.

/**
 * Change the simplified fields of key values provided to the external api into a {@link MetadataList}.
 *
 * @param json
 *          The json string that contains an array of metadata field lists for the different catalogs.
 * @return A {@link MetadataList} with the fields populated with the values provided.
 * @throws ParseException
 *           Thrown if unable to parse the json string.
 * @throws NotFoundException
 *           Thrown if unable to find the catalog or field that the json refers to.
 */
protected MetadataList deserializeMetadataList(String json) throws ParseException, NotFoundException {
    MetadataList metadataList = new MetadataList();
    JSONParser parser = new JSONParser();
    JSONArray jsonCatalogs = (JSONArray) parser.parse(json);
    for (int i = 0; i < jsonCatalogs.size(); i++) {
        JSONObject catalog = (JSONObject) jsonCatalogs.get(i);
        if (catalog.get("flavor") == null || StringUtils.isBlank(catalog.get("flavor").toString())) {
            throw new IllegalArgumentException("Unable to create new series as no flavor was given for one of the metadata collections");
        }
        String flavorString = catalog.get("flavor").toString();
        MediaPackageElementFlavor flavor = MediaPackageElementFlavor.parseFlavor(flavorString);
        MetadataCollection collection = null;
        SeriesCatalogUIAdapter adapter = null;
        for (SeriesCatalogUIAdapter seriesCatalogUIAdapter : indexService.getSeriesCatalogUIAdapters()) {
            MediaPackageElementFlavor catalogFlavor = MediaPackageElementFlavor.parseFlavor(seriesCatalogUIAdapter.getFlavor());
            if (catalogFlavor.equals(flavor)) {
                adapter = seriesCatalogUIAdapter;
                collection = seriesCatalogUIAdapter.getRawFields();
            }
        }
        if (collection == null) {
            throw new IllegalArgumentException(String.format("Unable to find an SeriesCatalogUIAdapter with Flavor '%s'", flavorString));
        }
        String fieldsJson = catalog.get("fields").toString();
        if (StringUtils.trimToNull(fieldsJson) != null) {
            Map<String, String> fields = RequestUtils.getKeyValueMap(fieldsJson);
            for (String key : fields.keySet()) {
                if ("subjects".equals(key)) {
                    MetadataField<?> field = collection.getOutputFields().get("subject");
                    if (field == null) {
                        throw new NotFoundException(String.format("Cannot find a metadata field with id '%s' from Catalog with Flavor '%s'.", key, flavorString));
                    }
                    collection.removeField(field);
                    try {
                        JSONArray subjects = (JSONArray) parser.parse(fields.get(key));
                        collection.addField(MetadataField.copyMetadataFieldWithValue(field, StringUtils.join(subjects.iterator(), ",")));
                    } catch (ParseException e) {
                        throw new IllegalArgumentException(String.format("Unable to parse the 'subjects' metadata array field because: %s", e.toString()));
                    }
                } else {
                    MetadataField<?> field = collection.getOutputFields().get(key);
                    if (field == null) {
                        throw new NotFoundException(String.format("Cannot find a metadata field with id '%s' from Catalog with Flavor '%s'.", key, flavorString));
                    }
                    collection.removeField(field);
                    collection.addField(MetadataField.copyMetadataFieldWithValue(field, fields.get(key)));
                }
            }
        }
        metadataList.add(adapter, collection);
    }
    return metadataList;
}
Also used : JSONArray(org.json.simple.JSONArray) NotFoundException(org.opencastproject.util.NotFoundException) SeriesCatalogUIAdapter(org.opencastproject.metadata.dublincore.SeriesCatalogUIAdapter) MediaPackageElementFlavor(org.opencastproject.mediapackage.MediaPackageElementFlavor) MetadataList(org.opencastproject.index.service.catalog.adapter.MetadataList) JSONObject(org.json.simple.JSONObject) JSONParser(org.json.simple.parser.JSONParser) MetadataCollection(org.opencastproject.metadata.dublincore.MetadataCollection) ParseException(org.json.simple.parser.ParseException)

Example 17 with MetadataList

use of org.opencastproject.index.service.catalog.adapter.MetadataList in project opencast by opencast.

the class IndexServiceImplTest method testUpdateMediaPackageMetadata.

@Test
public void testUpdateMediaPackageMetadata() throws Exception {
    // mock/initialize dependencies
    String username = "user1";
    String org = "mh_default_org";
    String testResourceLocation = "/events/update-event.json";
    String metadataJson = IOUtils.toString(getClass().getResourceAsStream(testResourceLocation));
    MetadataCollection metadataCollection = new DublinCoreMetadataCollection();
    metadataCollection.addField(MetadataField.createTextMetadataField("title", Opt.some("title"), "EVENTS.EVENTS.DETAILS.METADATA.TITLE", false, true, Opt.none(), Opt.none(), Opt.none(), Opt.none(), Opt.none()));
    metadataCollection.addField(MetadataField.createTextLongMetadataField("creator", Opt.some("creator"), "EVENTS.EVENTS.DETAILS.METADATA.PRESENTERS", false, false, Opt.none(), Opt.none(), Opt.none(), Opt.none(), Opt.none()));
    metadataCollection.addField(MetadataField.createTextMetadataField("isPartOf", Opt.some("isPartOf"), "EVENTS.EVENTS.DETAILS.METADATA.SERIES", false, false, Opt.none(), Opt.none(), Opt.none(), Opt.none(), Opt.none()));
    MetadataList metadataList = new MetadataList(metadataCollection, metadataJson);
    String eventId = "event-1";
    Event event = new Event(eventId, org);
    event.setTitle("Test Event 1");
    SearchQuery query = EasyMock.createMock(SearchQuery.class);
    EasyMock.expect(query.getLimit()).andReturn(100);
    EasyMock.expect(query.getOffset()).andReturn(0);
    EasyMock.replay(query);
    SearchResultItemImpl<Event> searchResultItem = new SearchResultItemImpl<>(1.0, event);
    SearchResultImpl<Event> searchResult = new SearchResultImpl<>(query, 0, 0);
    searchResult.addResultItem(searchResultItem);
    SecurityService securityService = setupSecurityService(username, org);
    AbstractSearchIndex index = EasyMock.createMock(AbstractSearchIndex.class);
    MediaPackage mp = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder().loadFromXml(getClass().getResourceAsStream("/events/update-event-mp.xml"));
    EasyMock.expect(index.getByQuery(EasyMock.anyObject(EventSearchQuery.class))).andReturn(searchResult);
    EasyMock.replay(index);
    Workspace workspace = EasyMock.createMock(Workspace.class);
    EasyMock.expect(workspace.put(EasyMock.anyString(), EasyMock.anyString(), EasyMock.anyString(), EasyMock.anyObject())).andReturn(getClass().getResource("/dublincore.xml").toURI()).anyTimes();
    EasyMock.expect(workspace.read(EasyMock.anyObject())).andAnswer(() -> getClass().getResourceAsStream("/dublincore.xml")).anyTimes();
    EasyMock.replay(workspace);
    CommonEventCatalogUIAdapter commonEventCatalogUIAdapter = setupCommonCatalogUIAdapter(workspace).getA();
    // Using scheduler as the source of the media package here.
    SchedulerService schedulerService = EasyMock.createMock(SchedulerService.class);
    EasyMock.expect(schedulerService.getMediaPackage(EasyMock.anyString())).andReturn(mp);
    Capture<Opt<MediaPackage>> mpCapture = new Capture<>();
    schedulerService.updateEvent(EasyMock.anyString(), EasyMock.anyObject(Opt.class), EasyMock.anyObject(Opt.class), EasyMock.anyObject(Opt.class), EasyMock.anyObject(Opt.class), EasyMock.capture(mpCapture), EasyMock.anyObject(Opt.class), EasyMock.anyObject(Opt.class), EasyMock.anyObject(Opt.class), EasyMock.anyString());
    EasyMock.expectLastCall();
    EasyMock.replay(schedulerService);
    SeriesService seriesService = EasyMock.createMock(SeriesService.class);
    DublinCoreCatalog seriesDC = DublinCores.read(getClass().getResourceAsStream("/events/update-event-series.xml"));
    EasyMock.expect(seriesService.getSeries(EasyMock.anyString())).andReturn(seriesDC);
    EasyMock.expect(seriesService.getSeriesAccessControl(EasyMock.anyString())).andReturn(null);
    EasyMock.expect(seriesService.getSeriesElements(EasyMock.anyString())).andReturn(Opt.none());
    EasyMock.replay(seriesService);
    // create service
    IndexServiceImpl indexService = new IndexServiceImpl();
    indexService.setSecurityService(securityService);
    indexService.setSchedulerService(schedulerService);
    indexService.setCommonEventCatalogUIAdapter(commonEventCatalogUIAdapter);
    indexService.addCatalogUIAdapter(commonEventCatalogUIAdapter);
    indexService.setSeriesService(seriesService);
    indexService.setWorkspace(workspace);
    MetadataList updateEventMetadata = indexService.updateEventMetadata(org, metadataList, index);
    Assert.assertTrue(mpCapture.hasCaptured());
    Assert.assertEquals("series-1", mp.getSeries());
    Assert.assertEquals(1, mp.getCatalogs(MediaPackageElements.SERIES).length);
}
Also used : DublinCoreMetadataCollection(org.opencastproject.index.service.catalog.adapter.DublinCoreMetadataCollection) EventSearchQuery(org.opencastproject.index.service.impl.index.event.EventSearchQuery) SearchQuery(org.opencastproject.matterhorn.search.SearchQuery) SearchResultItemImpl(org.opencastproject.matterhorn.search.impl.SearchResultItemImpl) SchedulerService(org.opencastproject.scheduler.api.SchedulerService) EventSearchQuery(org.opencastproject.index.service.impl.index.event.EventSearchQuery) Capture(org.easymock.Capture) MetadataList(org.opencastproject.index.service.catalog.adapter.MetadataList) AbstractSearchIndex(org.opencastproject.index.service.impl.index.AbstractSearchIndex) Opt(com.entwinemedia.fn.data.Opt) SearchResultImpl(org.opencastproject.matterhorn.search.impl.SearchResultImpl) SeriesService(org.opencastproject.series.api.SeriesService) SecurityService(org.opencastproject.security.api.SecurityService) MediaPackage(org.opencastproject.mediapackage.MediaPackage) Event(org.opencastproject.index.service.impl.index.event.Event) CommonEventCatalogUIAdapter(org.opencastproject.index.service.catalog.adapter.events.CommonEventCatalogUIAdapter) DublinCoreMetadataCollection(org.opencastproject.index.service.catalog.adapter.DublinCoreMetadataCollection) MetadataCollection(org.opencastproject.metadata.dublincore.MetadataCollection) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog) Workspace(org.opencastproject.workspace.api.Workspace) Test(org.junit.Test)

Example 18 with MetadataList

use of org.opencastproject.index.service.catalog.adapter.MetadataList in project opencast by opencast.

the class AbstractEventEndpoint method getNewMetadata.

@GET
@Path("new/metadata")
@RestQuery(name = "getNewMetadata", description = "Returns all the data related to the metadata tab in the new event modal as JSON", returnDescription = "All the data related to the event metadata tab as JSON", reponses = { @RestResponse(responseCode = SC_OK, description = "Returns all the data related to the event metadata tab as JSON") })
public Response getNewMetadata() {
    MetadataList metadataList = getIndexService().getMetadataListWithAllEventCatalogUIAdapters();
    Opt<MetadataCollection> optMetadataByAdapter = metadataList.getMetadataByAdapter(getIndexService().getCommonEventCatalogUIAdapter());
    if (optMetadataByAdapter.isSome()) {
        MetadataCollection collection = optMetadataByAdapter.get();
        if (collection.getOutputFields().containsKey(DublinCore.PROPERTY_CREATED.getLocalName()))
            collection.removeField(collection.getOutputFields().get(DublinCore.PROPERTY_CREATED.getLocalName()));
        if (collection.getOutputFields().containsKey("duration"))
            collection.removeField(collection.getOutputFields().get("duration"));
        if (collection.getOutputFields().containsKey(DublinCore.PROPERTY_IDENTIFIER.getLocalName()))
            collection.removeField(collection.getOutputFields().get(DublinCore.PROPERTY_IDENTIFIER.getLocalName()));
        if (collection.getOutputFields().containsKey(DublinCore.PROPERTY_SOURCE.getLocalName()))
            collection.removeField(collection.getOutputFields().get(DublinCore.PROPERTY_SOURCE.getLocalName()));
        if (collection.getOutputFields().containsKey("startDate"))
            collection.removeField(collection.getOutputFields().get("startDate"));
        if (collection.getOutputFields().containsKey("startTime"))
            collection.removeField(collection.getOutputFields().get("startTime"));
        if (collection.getOutputFields().containsKey("location"))
            collection.removeField(collection.getOutputFields().get("location"));
        metadataList.add(getIndexService().getCommonEventCatalogUIAdapter(), collection);
    }
    return okJson(metadataList.toJSON());
}
Also used : MetadataList(org.opencastproject.index.service.catalog.adapter.MetadataList) MetadataCollection(org.opencastproject.metadata.dublincore.MetadataCollection) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 19 with MetadataList

use of org.opencastproject.index.service.catalog.adapter.MetadataList in project opencast by opencast.

the class SeriesEndpoint method getNewMetadata.

@GET
@Path("new/metadata")
@RestQuery(name = "getNewMetadata", description = "Returns all the data related to the metadata tab in the new series modal as JSON", returnDescription = "All the data related to the series metadata tab as JSON", reponses = { @RestResponse(responseCode = SC_OK, description = "Returns all the data related to the series metadata tab as JSON") })
public Response getNewMetadata() {
    MetadataList metadataList = indexService.getMetadataListWithAllSeriesCatalogUIAdapters();
    Opt<MetadataCollection> metadataByAdapter = metadataList.getMetadataByAdapter(indexService.getCommonSeriesCatalogUIAdapter());
    if (metadataByAdapter.isSome()) {
        MetadataCollection collection = metadataByAdapter.get();
        safelyRemoveField(collection, "identifier");
        metadataList.add(indexService.getCommonSeriesCatalogUIAdapter(), collection);
    }
    return okJson(metadataList.toJSON());
}
Also used : MetadataList(org.opencastproject.index.service.catalog.adapter.MetadataList) MetadataCollection(org.opencastproject.metadata.dublincore.MetadataCollection) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 20 with MetadataList

use of org.opencastproject.index.service.catalog.adapter.MetadataList in project opencast by opencast.

the class EventsEndpoint method eventToJSON.

/**
 * Transform an {@link Event} to Json
 *
 * @param event
 *          The event to transform into json
 * @param withAcl
 *          Whether to add the acl information for the event
 * @param withMetadata
 *          Whether to add all the metadata for the event
 * @param withPublications
 *          Whether to add the publications
 * @param withSignedUrls
 *          Whether to sign the urls if they are protected by stream security.
 * @return The event in json format.
 * @throws IndexServiceException
 *           Thrown if unable to get the metadata for the event.
 * @throws SearchIndexException
 *           Thrown if unable to get event publications from search service
 * @throws NotFoundException
 *           Thrown if unable to find all of the metadata
 */
protected JValue eventToJSON(Event event, Boolean withAcl, Boolean withMetadata, Boolean withPublications, Boolean withSignedUrls) throws IndexServiceException, SearchIndexException, NotFoundException {
    List<Field> fields = new ArrayList<>();
    if (event.getArchiveVersion() != null)
        fields.add(f("archive_version", v(event.getArchiveVersion())));
    fields.add(f("created", v(event.getCreated(), Jsons.BLANK)));
    fields.add(f("creator", v(event.getCreator(), Jsons.BLANK)));
    fields.add(f("contributor", arr($(event.getContributors()).map(Functions.stringToJValue))));
    fields.add(f("description", v(event.getDescription(), Jsons.BLANK)));
    fields.add(f("has_previews", v(event.hasPreview())));
    fields.add(f("identifier", v(event.getIdentifier(), BLANK)));
    fields.add(f("location", v(event.getLocation(), BLANK)));
    fields.add(f("presenter", arr($(event.getPresenters()).map(Functions.stringToJValue))));
    List<JValue> publicationIds = new ArrayList<>();
    if (event.getPublications() != null) {
        for (Publication publication : event.getPublications()) {
            publicationIds.add(v(publication.getChannel()));
        }
    }
    fields.add(f("publication_status", arr(publicationIds)));
    fields.add(f("processing_state", v(event.getWorkflowState(), BLANK)));
    fields.add(f("start", v(event.getTechnicalStartTime(), BLANK)));
    if (event.getTechnicalEndTime() != null) {
        long duration = new DateTime(event.getTechnicalEndTime()).getMillis() - new DateTime(event.getTechnicalStartTime()).getMillis();
        fields.add(f("duration", v(duration)));
    }
    if (StringUtils.trimToNull(event.getSubject()) != null) {
        fields.add(f("subjects", arr(splitSubjectIntoArray(event.getSubject()))));
    } else {
        fields.add(f("subjects", arr()));
    }
    fields.add(f("title", v(event.getTitle(), BLANK)));
    if (withAcl != null && withAcl) {
        AccessControlList acl = getAclFromEvent(event);
        fields.add(f("acl", arr(AclUtils.serializeAclToJson(acl))));
    }
    if (withMetadata != null && withMetadata) {
        try {
            Opt<MetadataList> metadata = getEventMetadata(event);
            if (metadata.isSome()) {
                fields.add(f("metadata", metadata.get().toJSON()));
            }
        } catch (Exception e) {
            logger.error("Unable to get metadata for event '{}' because: {}", event.getIdentifier(), ExceptionUtils.getStackTrace(e));
            throw new IndexServiceException("Unable to add metadata to event", e);
        }
    }
    if (withPublications != null && withPublications) {
        List<JValue> publications = getPublications(event, withSignedUrls);
        fields.add(f("publications", arr(publications)));
    }
    return obj(fields);
}
Also used : AccessControlList(org.opencastproject.security.api.AccessControlList) ArrayList(java.util.ArrayList) Publication(org.opencastproject.mediapackage.Publication) DateTime(org.joda.time.DateTime) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) IngestException(org.opencastproject.ingest.api.IngestException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) ConfigurationException(org.osgi.service.cm.ConfigurationException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) ParseException(org.json.simple.parser.ParseException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) MetadataList(org.opencastproject.index.service.catalog.adapter.MetadataList) Field(com.entwinemedia.fn.data.json.Field) MetadataField(org.opencastproject.metadata.dublincore.MetadataField) JValue(com.entwinemedia.fn.data.json.JValue) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException)

Aggregations

MetadataList (org.opencastproject.index.service.catalog.adapter.MetadataList)27 MetadataCollection (org.opencastproject.metadata.dublincore.MetadataCollection)15 NotFoundException (org.opencastproject.util.NotFoundException)10 Path (javax.ws.rs.Path)8 JSONArray (org.json.simple.JSONArray)8 JSONParser (org.json.simple.parser.JSONParser)8 RestQuery (org.opencastproject.util.doc.rest.RestQuery)8 ParseException (org.json.simple.parser.ParseException)7 IOException (java.io.IOException)6 Produces (javax.ws.rs.Produces)6 IndexServiceException (org.opencastproject.index.service.exception.IndexServiceException)6 EventCatalogUIAdapter (org.opencastproject.metadata.dublincore.EventCatalogUIAdapter)6 GET (javax.ws.rs.GET)5 WebApplicationException (javax.ws.rs.WebApplicationException)5 JSONObject (org.json.simple.JSONObject)5 CommonEventCatalogUIAdapter (org.opencastproject.index.service.catalog.adapter.events.CommonEventCatalogUIAdapter)5 IngestException (org.opencastproject.ingest.api.IngestException)5 MediaPackageException (org.opencastproject.mediapackage.MediaPackageException)5 AccessControlList (org.opencastproject.security.api.AccessControlList)5 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)5