Search in sources :

Example 26 with Event

use of org.opencastproject.index.service.impl.index.event.Event in project opencast by opencast.

the class TestSeriesEndpoint method setupIndex.

@SuppressWarnings({ "unchecked" })
private void setupIndex() throws SearchIndexException, IOException, IllegalStateException, ParseException {
    long time = DateTimeSupport.fromUTC("2014-04-27T14:35:50Z");
    Series series1 = createSeries("1", "title 1", "contributor 1", "organizer 1", time, 1L);
    time = DateTimeSupport.fromUTC("2014-04-28T14:35:50Z");
    Series series2 = createSeries("2", "title 2", "contributor 2", "organizer 2", time, null);
    time = DateTimeSupport.fromUTC("2014-04-29T14:35:50Z");
    Series series3 = createSeries("3", "title 3", "contributor 3", "organizer 3", time, null);
    org.opencastproject.index.service.impl.index.theme.Theme theme1 = new org.opencastproject.index.service.impl.index.theme.Theme(1L, new DefaultOrganization().getId());
    theme1.setName("theme-1-name");
    theme1.setDescription("theme-1-description");
    SearchResultItem<Series> item1 = EasyMock.createMock(SearchResultItem.class);
    EasyMock.expect(item1.getSource()).andReturn(series1).anyTimes();
    SearchResultItem<Series> item2 = EasyMock.createMock(SearchResultItem.class);
    EasyMock.expect(item2.getSource()).andReturn(series2).anyTimes();
    SearchResultItem<Series> item3 = EasyMock.createMock(SearchResultItem.class);
    EasyMock.expect(item3.getSource()).andReturn(series3).anyTimes();
    SearchResultItem<Series>[] ascSeriesItems = new SearchResultItem[3];
    ascSeriesItems[0] = item1;
    ascSeriesItems[1] = item2;
    ascSeriesItems[2] = item3;
    SearchResultItem<Series>[] descSeriesItems = new SearchResultItem[3];
    descSeriesItems[0] = item3;
    descSeriesItems[1] = item2;
    descSeriesItems[2] = item1;
    // final SearchResultItem<Event>[] eventItems1 = new SearchResultItem[0];
    final SearchResultItem<Event>[] eventItems1 = createEvents(1, 1, 1);
    // Setup the events for series 2
    final SearchResultItem<Event>[] eventItems2 = new SearchResultItem[0];
    // Setup the events for series 3
    final SearchResultItem<Event>[] eventItems3 = createEvents(0, 1, 2);
    final SearchResultItem<org.opencastproject.index.service.impl.index.theme.Theme> themeItem1 = EasyMock.createMock(SearchResultItem.class);
    EasyMock.expect(themeItem1.getSource()).andReturn(theme1);
    // Setup series search results
    final SearchResult<Series> ascSeriesSearchResult = EasyMock.createMock(SearchResult.class);
    EasyMock.expect(ascSeriesSearchResult.getItems()).andReturn(ascSeriesItems);
    EasyMock.expect(ascSeriesSearchResult.getHitCount()).andReturn((long) ascSeriesItems.length);
    final SearchResult<Series> descSeriesSearchResult = EasyMock.createMock(SearchResult.class);
    EasyMock.expect(descSeriesSearchResult.getItems()).andReturn(descSeriesItems);
    EasyMock.expect(descSeriesSearchResult.getHitCount()).andReturn((long) descSeriesItems.length);
    // Create an empty search result.
    final SearchResult<Series> emptySearchResult = EasyMock.createMock(SearchResult.class);
    EasyMock.expect(emptySearchResult.getPageSize()).andReturn(0L).anyTimes();
    // Create a single search result for series 1.
    final SearchResult<Series> oneSearchResult = EasyMock.createMock(SearchResult.class);
    EasyMock.expect(oneSearchResult.getPageSize()).andReturn(1L).anyTimes();
    EasyMock.expect(oneSearchResult.getItems()).andReturn(new SearchResultItem[] { item1 }).anyTimes();
    // Create a single search result for series 2.
    final SearchResult<Series> twoSearchResult = EasyMock.createMock(SearchResult.class);
    EasyMock.expect(twoSearchResult.getPageSize()).andReturn(1L).anyTimes();
    EasyMock.expect(twoSearchResult.getItems()).andReturn(new SearchResultItem[] { item2 }).anyTimes();
    adminuiSearchIndex = EasyMock.createMock(AdminUISearchIndex.class);
    final Capture<SeriesSearchQuery> captureSeriesSearchQuery = EasyMock.newCapture();
    final Capture<EventSearchQuery> captureEventSearchQuery = EasyMock.newCapture();
    final Capture<ThemeSearchQuery> captureThemeSearchQuery = EasyMock.newCapture();
    EasyMock.expect(adminuiSearchIndex.getByQuery(EasyMock.capture(captureSeriesSearchQuery))).andAnswer(new IAnswer<SearchResult<Series>>() {

        @Override
        public SearchResult<Series> answer() throws Throwable {
            if (captureSeriesSearchQuery.hasCaptured() && captureSeriesSearchQuery.getValue().getIdentifier().length == 1) {
                if ("1".equals(captureSeriesSearchQuery.getValue().getIdentifier()[0])) {
                    return oneSearchResult;
                } else if ("2".equals(captureSeriesSearchQuery.getValue().getIdentifier()[0])) {
                    return twoSearchResult;
                } else {
                    return emptySearchResult;
                }
            } else if (captureSeriesSearchQuery.hasCaptured() && captureSeriesSearchQuery.getValue().getSeriesContributorsSortOrder() == Order.Ascending) {
                return ascSeriesSearchResult;
            } else if (captureSeriesSearchQuery.hasCaptured() && captureSeriesSearchQuery.getValue().getSeriesContributorsSortOrder() == Order.Descending) {
                return descSeriesSearchResult;
            } else if (captureSeriesSearchQuery.hasCaptured() && captureSeriesSearchQuery.getValue().getSeriesDateSortOrder() == Order.Ascending) {
                return ascSeriesSearchResult;
            } else if (captureSeriesSearchQuery.hasCaptured() && captureSeriesSearchQuery.getValue().getSeriesDateSortOrder() == Order.Descending) {
                return descSeriesSearchResult;
            } else if (captureSeriesSearchQuery.hasCaptured() && captureSeriesSearchQuery.getValue().getSeriesOrganizersSortOrder() == Order.Ascending) {
                return ascSeriesSearchResult;
            } else if (captureSeriesSearchQuery.hasCaptured() && captureSeriesSearchQuery.getValue().getSeriesOrganizersSortOrder() == Order.Descending) {
                return descSeriesSearchResult;
            } else if (captureSeriesSearchQuery.hasCaptured() && captureSeriesSearchQuery.getValue().getSeriesTitleSortOrder() == Order.Ascending) {
                return ascSeriesSearchResult;
            } else if (captureSeriesSearchQuery.hasCaptured() && captureSeriesSearchQuery.getValue().getSeriesTitleSortOrder() == Order.Descending) {
                return descSeriesSearchResult;
            } else {
                return ascSeriesSearchResult;
            }
        }
    });
    EasyMock.expect(adminuiSearchIndex.getByQuery(EasyMock.capture(captureEventSearchQuery))).andAnswer(new IAnswer<SearchResult<Event>>() {

        @Override
        public SearchResult<Event> answer() throws Throwable {
            SearchResult<Event> eventsSearchResult = EasyMock.createMock(SearchResult.class);
            if (captureEventSearchQuery.hasCaptured() && "1".equals(captureEventSearchQuery.getValue().getSeriesId()) && !("RUNNING".equals(captureEventSearchQuery.getValue().getWorkflowState())) && !("INSTANTIATED".equals(captureEventSearchQuery.getValue().getWorkflowState()))) {
                // Setup events search results
                EasyMock.expect(eventsSearchResult.getItems()).andReturn(eventItems1).anyTimes();
                EasyMock.expect(eventsSearchResult.getHitCount()).andReturn((long) eventItems1.length).anyTimes();
            } else if (captureEventSearchQuery.hasCaptured() && "1".equals(captureEventSearchQuery.getValue().getSeriesId()) && "INSTANTIATED".equals(captureEventSearchQuery.getValue().getWorkflowState())) {
                // Setup events search results
                EasyMock.expect(eventsSearchResult.getItems()).andReturn(eventItems2).anyTimes();
                EasyMock.expect(eventsSearchResult.getHitCount()).andReturn((long) eventItems2.length).anyTimes();
            } else if (captureEventSearchQuery.hasCaptured() && "1".equals(captureEventSearchQuery.getValue().getSeriesId()) && "RUNNING".equals(captureEventSearchQuery.getValue().getWorkflowState())) {
                // Setup events search results
                EasyMock.expect(eventsSearchResult.getItems()).andReturn(eventItems2).anyTimes();
                EasyMock.expect(eventsSearchResult.getHitCount()).andReturn((long) eventItems2.length).anyTimes();
            } else if (captureEventSearchQuery.hasCaptured() && "2".equals(captureEventSearchQuery.getValue().getSeriesId()) && !("RUNNING".equals(captureEventSearchQuery.getValue().getWorkflowState()))) {
                // Setup events search results
                EasyMock.expect(eventsSearchResult.getItems()).andReturn(eventItems2).anyTimes();
                EasyMock.expect(eventsSearchResult.getHitCount()).andReturn((long) eventItems2.length).anyTimes();
            } else if (captureEventSearchQuery.hasCaptured() && "3".equals(captureEventSearchQuery.getValue().getSeriesId())) {
                // Setup events search results
                EasyMock.expect(eventsSearchResult.getItems()).andReturn(eventItems3).anyTimes();
                EasyMock.expect(eventsSearchResult.getHitCount()).andReturn((long) eventItems3.length).anyTimes();
            } else if (captureEventSearchQuery.hasCaptured() && "2".equals(captureEventSearchQuery.getValue().getSeriesId()) && "RUNNING".equals(captureEventSearchQuery.getValue().getWorkflowState())) {
                // Setup events search results
                EasyMock.expect(eventsSearchResult.getItems()).andReturn(eventItems3).anyTimes();
                EasyMock.expect(eventsSearchResult.getHitCount()).andReturn((long) eventItems3.length).anyTimes();
            } else {
                if (!captureEventSearchQuery.hasCaptured()) {
                    Assert.fail("Haven't captured an event search query yet.");
                } else {
                    logger.info("IDs for search query" + captureEventSearchQuery.getValue().getSeriesId());
                    Assert.fail("Tried to get an event collection that doesn't exist.");
                }
            }
            EasyMock.replay(eventsSearchResult);
            return eventsSearchResult;
        }
    }).anyTimes();
    EasyMock.expect(adminuiSearchIndex.getByQuery(EasyMock.capture(captureThemeSearchQuery))).andAnswer(new IAnswer<SearchResult<org.opencastproject.index.service.impl.index.theme.Theme>>() {

        @Override
        public SearchResult<org.opencastproject.index.service.impl.index.theme.Theme> answer() throws Throwable {
            SearchResult<org.opencastproject.index.service.impl.index.theme.Theme> themeSearchResult = EasyMock.createMock(SearchResult.class);
            // Setup theme search results
            EasyMock.expect(themeSearchResult.getPageSize()).andReturn(1L).anyTimes();
            EasyMock.expect(themeSearchResult.getItems()).andReturn(new SearchResultItem[] { themeItem1 }).anyTimes();
            EasyMock.replay(themeSearchResult);
            return themeSearchResult;
        }
    }).anyTimes();
    EasyMock.replay(adminuiSearchIndex, item1, item2, item3, themeItem1, ascSeriesSearchResult, descSeriesSearchResult, emptySearchResult, oneSearchResult, twoSearchResult);
}
Also used : AdminUISearchIndex(org.opencastproject.adminui.impl.index.AdminUISearchIndex) SeriesSearchQuery(org.opencastproject.index.service.impl.index.series.SeriesSearchQuery) EventSearchQuery(org.opencastproject.index.service.impl.index.event.EventSearchQuery) SearchResultItem(org.opencastproject.matterhorn.search.SearchResultItem) SearchResult(org.opencastproject.matterhorn.search.SearchResult) Series(org.opencastproject.index.service.impl.index.series.Series) IAnswer(org.easymock.IAnswer) ThemeSearchQuery(org.opencastproject.index.service.impl.index.theme.ThemeSearchQuery) Event(org.opencastproject.index.service.impl.index.event.Event) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization)

Example 27 with Event

use of org.opencastproject.index.service.impl.index.event.Event in project opencast by opencast.

the class ToolsEndpoint method editVideo.

@POST
@Path("{mediapackageid}/editor.json")
@Consumes(MediaType.APPLICATION_JSON)
@RestQuery(name = "editVideo", description = "Takes editing information from the client side and processes it", returnDescription = "", pathParameters = { @RestParameter(name = "mediapackageid", description = "The id of the media package", isRequired = true, type = RestParameter.Type.STRING) }, reponses = { @RestResponse(description = "Editing information saved and processed", responseCode = HttpServletResponse.SC_OK), @RestResponse(description = "Media package not found", responseCode = HttpServletResponse.SC_NOT_FOUND), @RestResponse(description = "The editing information cannot be parsed", responseCode = HttpServletResponse.SC_BAD_REQUEST) })
public Response editVideo(@PathParam("mediapackageid") final String mediaPackageId, @Context HttpServletRequest request) throws IndexServiceException, NotFoundException {
    String details;
    try (InputStream is = request.getInputStream()) {
        details = IOUtils.toString(is);
    } catch (IOException e) {
        logger.error("Error reading request body: {}", getStackTrace(e));
        return R.serverError();
    }
    JSONParser parser = new JSONParser();
    EditingInfo editingInfo;
    try {
        JSONObject detailsJSON = (JSONObject) parser.parse(details);
        editingInfo = EditingInfo.parse(detailsJSON);
    } catch (Exception e) {
        logger.warn("Unable to parse concat information ({}): {}", details, ExceptionUtils.getStackTrace(e));
        return R.badRequest("Unable to parse details");
    }
    final Opt<Event> optEvent = getEvent(mediaPackageId);
    if (optEvent.isNone()) {
        return R.notFound();
    } else {
        MediaPackage mediaPackage = index.getEventMediapackage(optEvent.get());
        Smil smil;
        try {
            smil = createSmilCuttingCatalog(editingInfo, mediaPackage);
        } catch (Exception e) {
            logger.warn("Unable to create a SMIL cutting catalog ({}): {}", details, getStackTrace(e));
            return R.badRequest("Unable to create SMIL cutting catalog");
        }
        try {
            addSmilToArchive(mediaPackage, smil);
        } catch (IOException e) {
            logger.warn("Unable to add SMIL cutting catalog to archive: {}", getStackTrace(e));
            return R.serverError();
        }
        if (editingInfo.getPostProcessingWorkflow().isSome()) {
            final String workflowId = editingInfo.getPostProcessingWorkflow().get();
            try {
                final Workflows workflows = new Workflows(assetManager, workspace, workflowService);
                workflows.applyWorkflowToLatestVersion($(mediaPackage.getIdentifier().toString()), ConfiguredWorkflow.workflow(workflowService.getWorkflowDefinitionById(workflowId))).run();
            } catch (AssetManagerException e) {
                logger.warn("Unable to start workflow '{}' on archived media package '{}': {}", workflowId, mediaPackage, getStackTrace(e));
                return R.serverError();
            } catch (WorkflowDatabaseException e) {
                logger.warn("Unable to load workflow '{}' from workflow service: {}", workflowId, getStackTrace(e));
                return R.serverError();
            } catch (NotFoundException e) {
                logger.warn("Workflow '{}' not found", workflowId);
                return R.badRequest("Workflow not found");
            }
        }
    }
    return R.ok();
}
Also used : Workflows(org.opencastproject.assetmanager.util.Workflows) InputStream(java.io.InputStream) NotFoundException(org.opencastproject.util.NotFoundException) IOException(java.io.IOException) AssetManagerException(org.opencastproject.assetmanager.api.AssetManagerException) SmilException(org.opencastproject.smil.api.SmilException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) ConfigurationException(org.osgi.service.cm.ConfigurationException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) JAXBException(javax.xml.bind.JAXBException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) SAXException(org.xml.sax.SAXException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) AssetManagerException(org.opencastproject.assetmanager.api.AssetManagerException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) JSONObject(org.json.simple.JSONObject) MediaPackage(org.opencastproject.mediapackage.MediaPackage) Event(org.opencastproject.index.service.impl.index.event.Event) JSONParser(org.json.simple.parser.JSONParser) Smil(org.opencastproject.smil.entity.api.Smil) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 28 with Event

use of org.opencastproject.index.service.impl.index.event.Event in project opencast by opencast.

the class ToolsEndpoint method getVideoEditor.

@GET
@Path("{mediapackageid}/editor.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "getVideoEditor", description = "Returns all the information required to get the editor tool started", returnDescription = "JSON object", pathParameters = { @RestParameter(name = "mediapackageid", description = "The id of the media package", isRequired = true, type = RestParameter.Type.STRING) }, reponses = { @RestResponse(description = "Media package found", responseCode = SC_OK), @RestResponse(description = "Media package not found", responseCode = SC_NOT_FOUND) })
public Response getVideoEditor(@PathParam("mediapackageid") final String mediaPackageId) throws IndexServiceException, NotFoundException {
    if (!isEditorAvailable(mediaPackageId))
        return R.notFound();
    // Select tracks
    final Event event = getEvent(mediaPackageId).get();
    final MediaPackage mp = index.getEventMediapackage(event);
    List<MediaPackageElement> previewPublications = getPreviewElementsFromPublication(getInternalPublication(mp));
    // Collect previews and tracks
    List<JValue> jPreviews = new ArrayList<>();
    List<JValue> jTracks = new ArrayList<>();
    for (MediaPackageElement element : previewPublications) {
        final URI elementUri;
        if (urlSigningService.accepts(element.getURI().toString())) {
            try {
                String clientIP = null;
                if (signWithClientIP) {
                    clientIP = securityService.getUserIP();
                }
                elementUri = new URI(urlSigningService.sign(element.getURI().toString(), expireSeconds, null, clientIP));
            } catch (URISyntaxException e) {
                logger.error("Error while trying to sign the preview urls because: {}", getStackTrace(e));
                throw new WebApplicationException(e, SC_INTERNAL_SERVER_ERROR);
            } catch (UrlSigningException e) {
                logger.error("Error while trying to sign the preview urls because: {}", getStackTrace(e));
                throw new WebApplicationException(e, SC_INTERNAL_SERVER_ERROR);
            }
        } else {
            elementUri = element.getURI();
        }
        jPreviews.add(obj(f("uri", v(elementUri.toString())), f("flavor", v(element.getFlavor().getType()))));
        if (!Type.Track.equals(element.getElementType()))
            continue;
        JObject jTrack = obj(f("id", v(element.getIdentifier())), f("flavor", v(element.getFlavor().getType())));
        // Check if there's a waveform for the current track
        Opt<Attachment> optWaveform = getWaveformForTrack(mp, element);
        if (optWaveform.isSome()) {
            final URI waveformUri;
            if (urlSigningService.accepts(element.getURI().toString())) {
                try {
                    waveformUri = new URI(urlSigningService.sign(optWaveform.get().getURI().toString(), expireSeconds, null, null));
                } catch (URISyntaxException e) {
                    logger.error("Error while trying to serialize the waveform urls because: {}", getStackTrace(e));
                    throw new WebApplicationException(e, SC_INTERNAL_SERVER_ERROR);
                } catch (UrlSigningException e) {
                    logger.error("Error while trying to sign the preview urls because: {}", getStackTrace(e));
                    throw new WebApplicationException(e, SC_INTERNAL_SERVER_ERROR);
                }
            } else {
                waveformUri = optWaveform.get().getURI();
            }
            jTracks.add(jTrack.merge(obj(f("waveform", v(waveformUri.toString())))));
        } else {
            jTracks.add(jTrack);
        }
    }
    // Get existing segments
    List<JValue> jSegments = new ArrayList<>();
    for (Tuple<Long, Long> segment : getSegments(mp)) {
        jSegments.add(obj(f(START_KEY, v(segment.getA())), f(END_KEY, v(segment.getB()))));
    }
    // Get workflows
    List<JValue> jWorkflows = new ArrayList<>();
    for (WorkflowDefinition workflow : getEditingWorkflows()) {
        jWorkflows.add(obj(f("id", v(workflow.getId())), f("name", v(workflow.getTitle(), Jsons.BLANK))));
    }
    return RestUtils.okJson(obj(f("title", v(mp.getTitle(), Jsons.BLANK)), f("date", v(event.getRecordingStartDate(), Jsons.BLANK)), f("series", obj(f("id", v(event.getSeriesId(), Jsons.BLANK)), f("title", v(event.getSeriesName(), Jsons.BLANK)))), f("presenters", arr($(event.getPresenters()).map(Functions.stringToJValue))), f("previews", arr(jPreviews)), f(TRACKS_KEY, arr(jTracks)), f("duration", v(mp.getDuration())), f(SEGMENTS_KEY, arr(jSegments)), f("workflows", arr(jWorkflows))));
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) ArrayList(java.util.ArrayList) WorkflowDefinition(org.opencastproject.workflow.api.WorkflowDefinition) Attachment(org.opencastproject.mediapackage.Attachment) URISyntaxException(java.net.URISyntaxException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) URI(java.net.URI) MediaPackageElement(org.opencastproject.mediapackage.MediaPackageElement) JValue(com.entwinemedia.fn.data.json.JValue) MediaPackage(org.opencastproject.mediapackage.MediaPackage) Event(org.opencastproject.index.service.impl.index.event.Event) JObject(com.entwinemedia.fn.data.json.JObject) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 29 with Event

use of org.opencastproject.index.service.impl.index.event.Event in project opencast by opencast.

the class EventsEndpoint method getEventMedia.

@GET
@Path("{eventId}/media")
@Produces({ "application/json", "application/v1.0.0+json" })
public Response getEventMedia(@HeaderParam("Accept") String acceptHeader, @PathParam("eventId") String id) throws Exception {
    ArrayList<TrackImpl> tracks = new ArrayList<>();
    for (final Event event : indexService.getEvent(id, externalIndex)) {
        final MediaPackage mp = indexService.getEventMediapackage(event);
        for (Track track : mp.getTracks()) {
            if (track instanceof TrackImpl) {
                tracks.add((TrackImpl) track);
            }
        }
        List<JValue> tracksJson = new ArrayList<>();
        for (Track track : tracks) {
            List<Field> fields = new ArrayList<>();
            if (track.getChecksum() != null)
                fields.add(f("checksum", v(track.getChecksum().toString())));
            if (track.getDescription() != null)
                fields.add(f("description", v(track.getDescription())));
            if (track.getDuration() != null)
                fields.add(f("duration", v(track.getDuration())));
            if (track.getElementDescription() != null)
                fields.add(f("element-description", v(track.getElementDescription())));
            if (track.getFlavor() != null)
                fields.add(f("flavor", v(track.getFlavor().toString())));
            if (track.getIdentifier() != null)
                fields.add(f("identifier", v(track.getIdentifier())));
            if (track.getMimeType() != null)
                fields.add(f("identifier", v(track.getMimeType().toString())));
            fields.add(f("size", v(track.getSize())));
            if (track.getStreams() != null) {
                List<Field> streams = new ArrayList<>();
                for (Stream stream : track.getStreams()) {
                    streams.add(f(stream.getIdentifier(), getJsonStream(stream)));
                }
                fields.add(f("streams", obj(streams)));
            }
            if (track.getTags() != null) {
                List<JValue> tags = new ArrayList<>();
                for (String tag : track.getTags()) {
                    tags.add(v(tag));
                }
                fields.add(f("tags", arr(tags)));
            }
            if (track.getURI() != null)
                fields.add(f("uri", v(track.getURI().toString())));
            tracksJson.add(obj(fields));
        }
        return ApiResponses.Json.ok(ApiVersion.VERSION_1_0_0, arr(tracksJson));
    }
    return ApiResponses.notFound("Cannot find an event with id '%s'.", id);
}
Also used : Field(com.entwinemedia.fn.data.json.Field) MetadataField(org.opencastproject.metadata.dublincore.MetadataField) TrackImpl(org.opencastproject.mediapackage.track.TrackImpl) JValue(com.entwinemedia.fn.data.json.JValue) ArrayList(java.util.ArrayList) MediaPackage(org.opencastproject.mediapackage.MediaPackage) Event(org.opencastproject.index.service.impl.index.event.Event) AudioStream(org.opencastproject.mediapackage.AudioStream) Stream(org.opencastproject.mediapackage.Stream) VideoStream(org.opencastproject.mediapackage.VideoStream) Track(org.opencastproject.mediapackage.Track) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 30 with Event

use of org.opencastproject.index.service.impl.index.event.Event in project opencast by opencast.

the class EventsEndpoint method updateEventMetadataByType.

@PUT
@Path("{eventId}/metadata")
@Produces({ "application/json", "application/v1.0.0+json" })
@RestQuery(name = "updateeventmetadata", description = "Update the metadata with the matching type of the specified event. For a metadata catalog there is the flavor such as 'dublincore/episode' and this is the unique type.", returnDescription = "", pathParameters = { @RestParameter(name = "eventId", description = "The event id", isRequired = true, type = STRING) }, restParameters = { @RestParameter(name = "type", isRequired = true, description = "The type of metadata to update", type = STRING), @RestParameter(name = "metadata", description = "Metadata catalog in JSON format", isRequired = true, type = STRING) }, reponses = { @RestResponse(description = "The metadata of the given namespace has been updated.", responseCode = HttpServletResponse.SC_OK), @RestResponse(description = "The request is invalid or inconsistent.", responseCode = HttpServletResponse.SC_BAD_REQUEST), @RestResponse(description = "The specified event does not exist.", responseCode = HttpServletResponse.SC_NOT_FOUND) })
public Response updateEventMetadataByType(@HeaderParam("Accept") String acceptHeader, @PathParam("eventId") String id, @QueryParam("type") String type, @FormParam("metadata") String metadataJSON) throws Exception {
    Map<String, String> updatedFields;
    JSONParser parser = new JSONParser();
    try {
        updatedFields = RequestUtils.getKeyValueMap(metadataJSON);
    } catch (ParseException e) {
        logger.debug("Unable to update event '{}' with metadata type '{}' and content '{}' because: {}", id, type, metadataJSON, ExceptionUtils.getStackTrace(e));
        return RestUtil.R.badRequest(String.format("Unable to parse metadata fields as json from '%s' because '%s'", metadataJSON, ExceptionUtils.getStackTrace(e)));
    } catch (IllegalArgumentException e) {
        logger.debug("Unable to update event '{}' with metadata type '{}' and content '{}' because: {}", id, type, metadataJSON, ExceptionUtils.getStackTrace(e));
        return RestUtil.R.badRequest(e.getMessage());
    }
    if (updatedFields == null || updatedFields.size() == 0) {
        return RestUtil.R.badRequest(String.format("Unable to parse metadata fields as json from '%s' because there were no fields to update.", metadataJSON));
    }
    Opt<MediaPackageElementFlavor> flavor = getFlavor(type);
    if (flavor.isNone()) {
        return R.badRequest(String.format("Unable to parse type '%s' as a flavor so unable to find the matching catalog.", type));
    }
    MetadataCollection collection = null;
    EventCatalogUIAdapter adapter = null;
    for (final Event event : indexService.getEvent(id, externalIndex)) {
        MetadataList metadataList = new MetadataList();
        // Try the main catalog first as we load it from the index.
        if (flavor.get().equals(eventCatalogUIAdapter.getFlavor())) {
            collection = EventUtils.getEventMetadata(event, eventCatalogUIAdapter);
            adapter = eventCatalogUIAdapter;
        } else {
            metadataList.add(eventCatalogUIAdapter, EventUtils.getEventMetadata(event, eventCatalogUIAdapter));
        }
        // Try the other catalogs
        List<EventCatalogUIAdapter> catalogUIAdapters = getEventCatalogUIAdapters();
        catalogUIAdapters.remove(eventCatalogUIAdapter);
        MediaPackage mediaPackage = indexService.getEventMediapackage(event);
        if (catalogUIAdapters.size() > 0) {
            for (EventCatalogUIAdapter catalogUIAdapter : catalogUIAdapters) {
                if (flavor.get().equals(catalogUIAdapter.getFlavor())) {
                    collection = catalogUIAdapter.getFields(mediaPackage);
                    adapter = eventCatalogUIAdapter;
                } else {
                    metadataList.add(catalogUIAdapter, catalogUIAdapter.getFields(mediaPackage));
                }
            }
        }
        if (collection == null) {
            return ApiResponses.notFound("Cannot find a catalog with type '%s' for event with id '%s'.", type, id);
        }
        for (String key : updatedFields.keySet()) {
            if ("subjects".equals(key)) {
                MetadataField<?> field = collection.getOutputFields().get(DublinCore.PROPERTY_SUBJECT.getLocalName());
                Opt<Response> error = validateField(field, key, id, type, updatedFields);
                if (error.isSome()) {
                    return error.get();
                }
                collection.removeField(field);
                JSONArray subjectArray = (JSONArray) parser.parse(updatedFields.get(key));
                collection.addField(MetadataField.copyMetadataFieldWithValue(field, StringUtils.join(subjectArray.iterator(), ",")));
            } else if ("startDate".equals(key)) {
                // Special handling for start date since in API v1 we expect start date and start time to be separate fields.
                MetadataField<String> field = (MetadataField<String>) collection.getOutputFields().get(key);
                Opt<Response> error = validateField(field, key, id, type, updatedFields);
                if (error.isSome()) {
                    return error.get();
                }
                String apiPattern = field.getPattern().get();
                if (configuredMetadataFields.containsKey("startDate")) {
                    apiPattern = configuredMetadataFields.get("startDate").getPattern().getOr(apiPattern);
                }
                SimpleDateFormat apiSdf = MetadataField.getSimpleDateFormatter(apiPattern);
                SimpleDateFormat sdf = MetadataField.getSimpleDateFormatter(field.getPattern().get());
                DateTime oldStartDate = new DateTime(sdf.parse(field.getValue().get()), DateTimeZone.UTC);
                DateTime newStartDate = new DateTime(apiSdf.parse(updatedFields.get(key)), DateTimeZone.UTC);
                DateTime updatedStartDate = oldStartDate.withDate(newStartDate.year().get(), newStartDate.monthOfYear().get(), newStartDate.dayOfMonth().get());
                collection.removeField(field);
                collection.addField(MetadataField.copyMetadataFieldWithValue(field, sdf.format(updatedStartDate.toDate())));
            } else if ("startTime".equals(key)) {
                // Special handling for start time since in API v1 we expect start date and start time to be separate fields.
                MetadataField<String> field = (MetadataField<String>) collection.getOutputFields().get("startDate");
                Opt<Response> error = validateField(field, "startDate", id, type, updatedFields);
                if (error.isSome()) {
                    return error.get();
                }
                String apiPattern = "HH:mm";
                if (configuredMetadataFields.containsKey("startTime")) {
                    apiPattern = configuredMetadataFields.get("startTime").getPattern().getOr(apiPattern);
                }
                SimpleDateFormat apiSdf = MetadataField.getSimpleDateFormatter(apiPattern);
                SimpleDateFormat sdf = MetadataField.getSimpleDateFormatter(field.getPattern().get());
                DateTime oldStartDate = new DateTime(sdf.parse(field.getValue().get()), DateTimeZone.UTC);
                DateTime newStartDate = new DateTime(apiSdf.parse(updatedFields.get(key)), DateTimeZone.UTC);
                DateTime updatedStartDate = oldStartDate.withTime(newStartDate.hourOfDay().get(), newStartDate.minuteOfHour().get(), newStartDate.secondOfMinute().get(), newStartDate.millisOfSecond().get());
                collection.removeField(field);
                collection.addField(MetadataField.copyMetadataFieldWithValue(field, sdf.format(updatedStartDate.toDate())));
            } else {
                MetadataField<?> field = collection.getOutputFields().get(key);
                Opt<Response> error = validateField(field, key, id, type, updatedFields);
                if (error.isSome()) {
                    return error.get();
                }
                collection.removeField(field);
                collection.addField(MetadataField.copyMetadataFieldWithValue(field, updatedFields.get(key)));
            }
        }
        metadataList.add(adapter, collection);
        indexService.updateEventMetadata(id, metadataList, externalIndex);
        return ApiResponses.Json.noContent(ApiVersion.VERSION_1_0_0);
    }
    return ApiResponses.notFound("Cannot find an event with id '%s'.", id);
}
Also used : JSONArray(org.json.simple.JSONArray) MediaPackageElementFlavor(org.opencastproject.mediapackage.MediaPackageElementFlavor) MetadataField(org.opencastproject.metadata.dublincore.MetadataField) DateTime(org.joda.time.DateTime) MetadataList(org.opencastproject.index.service.catalog.adapter.MetadataList) RestResponse(org.opencastproject.util.doc.rest.RestResponse) Response(javax.ws.rs.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) Opt(com.entwinemedia.fn.data.Opt) CommonEventCatalogUIAdapter(org.opencastproject.index.service.catalog.adapter.events.CommonEventCatalogUIAdapter) EventCatalogUIAdapter(org.opencastproject.metadata.dublincore.EventCatalogUIAdapter) MediaPackage(org.opencastproject.mediapackage.MediaPackage) Event(org.opencastproject.index.service.impl.index.event.Event) JSONParser(org.json.simple.parser.JSONParser) MetadataCollection(org.opencastproject.metadata.dublincore.MetadataCollection) ParseException(org.json.simple.parser.ParseException) SimpleDateFormat(java.text.SimpleDateFormat) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) RestQuery(org.opencastproject.util.doc.rest.RestQuery) PUT(javax.ws.rs.PUT)

Aggregations

Event (org.opencastproject.index.service.impl.index.event.Event)67 Path (javax.ws.rs.Path)35 RestQuery (org.opencastproject.util.doc.rest.RestQuery)34 NotFoundException (org.opencastproject.util.NotFoundException)26 WebApplicationException (javax.ws.rs.WebApplicationException)24 SearchIndexException (org.opencastproject.matterhorn.search.SearchIndexException)22 Produces (javax.ws.rs.Produces)21 IndexServiceException (org.opencastproject.index.service.exception.IndexServiceException)19 MediaPackage (org.opencastproject.mediapackage.MediaPackage)19 SchedulerException (org.opencastproject.scheduler.api.SchedulerException)19 ParseException (java.text.ParseException)17 JSONException (org.codehaus.jettison.json.JSONException)17 UrlSigningException (org.opencastproject.security.urlsigning.exception.UrlSigningException)17 GET (javax.ws.rs.GET)16 AclServiceException (org.opencastproject.authorization.xacml.manager.api.AclServiceException)16 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)16 EventCommentException (org.opencastproject.event.comment.EventCommentException)15 WorkflowDatabaseException (org.opencastproject.workflow.api.WorkflowDatabaseException)15 JobEndpointException (org.opencastproject.adminui.exception.JobEndpointException)14 WorkflowStateException (org.opencastproject.workflow.api.WorkflowStateException)14