Search in sources :

Example 1 with IndexObject

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

the class EventsEndpointTest method testGetEventsJsonResponse.

@Ignore
@Test
public void testGetEventsJsonResponse() throws Exception {
    String eventJson = IOUtils.toString(getClass().getResource("/events.json"));
    String acceptHeader = "application/" + ApiVersion.CURRENT_VERSION.toExternalForm() + "+" + ApiFormat.JSON;
    List<IndexObject> events = new ArrayList<IndexObject>();
    List<String> contributors = new ArrayList<String>();
    contributors.add("Physics Department");
    List<Publication> publications = getExamplePublications();
    Event event1 = new Event("e6aeb8df-a852-46cd-8128-b89de696f20e", defaultOrg.getId());
    event1.setArchiveVersion(2L);
    event1.setCreated("2015-03-12T10:38:54Z");
    event1.setCreator("Opencast Administrator");
    event1.setContributors(contributors);
    event1.setDescription("Cooling without moving parts and using only heat as an input");
    event1.setDuration(7200000L);
    event1.setHasPreview(true);
    event1.setLocation("physics-e-01");
    List<String> presenters = new ArrayList<String>();
    presenters.add("Prof. A. Einstein");
    event1.setPresenters(presenters);
    event1.setPublications(publications);
    event1.setWorkflowState(WorkflowState.SUCCEEDED);
    event1.setRecordingStartDate("2015-03-20T04:00:00Z");
    event1.setSubject("Space Final Frontier");
    event1.setTitle("Einstein refrigerator");
    events.add(event1);
    Event event2 = new Event("f5aeb8df-a852-46cd-8128-b89de696f20e", defaultOrg.getId());
    event2.setArchiveVersion(5L);
    event2.setCreated("2015-03-12T10:38:54Z");
    event2.setCreator("Opencast Administrator");
    event2.setContributors(contributors);
    event2.setDescription("The history of the universe from the big bang to black holes");
    event2.setDuration(7200000L);
    event2.setHasPreview(true);
    event2.setLocation("physics-e-02");
    presenters = new ArrayList<String>();
    presenters.add("Prof. Stephen Hawking");
    event2.setPresenters(presenters);
    event2.setPublications(publications);
    event2.setWorkflowState(WorkflowState.SUCCEEDED);
    event2.setRecordingStartDate("2015-03-20T04:00:00Z");
    event2.setSubject("Space Final Frontier, Mathematics");
    event2.setTitle("The Theory of Everything");
    events.add(event2);
    EventsEndpoint endpoint = new EventsEndpoint();
    Response result = endpoint.getJsonEvents(acceptHeader, events, false, false, false, false);
    assertTrue(result.getMetadata().get("Content-Type") != null);
    assertEquals("application/v1.0.0+json", result.getMetadata().get("Content-Type").get(0).toString().toLowerCase());
    assertThat(eventJson, SameJSONAs.sameJSONAs(result.getEntity().toString()).allowingAnyArrayOrdering());
}
Also used : Response(javax.ws.rs.core.Response) ArrayList(java.util.ArrayList) IndexObject(org.opencastproject.index.service.impl.index.IndexObject) Publication(org.opencastproject.mediapackage.Publication) Event(org.opencastproject.index.service.impl.index.event.Event) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 2 with IndexObject

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

the class EventsEndpoint method getEvents.

@GET
@Path("/")
@Produces({ "application/json", "application/v1.0.0+json" })
@RestQuery(name = "getevents", description = "Returns a list of events. By setting the optional sign parameter to true, the method will pre-sign distribution urls if signing is turned on in Opencast. Remember to consider the maximum validity of signed URLs when caching this response.", returnDescription = "", restParameters = { @RestParameter(name = "sign", isRequired = false, description = "Whether public distribution urls should be signed.", type = Type.BOOLEAN), @RestParameter(name = "withacl", isRequired = false, description = "Whether the acl metadata should be included in the response.", type = Type.BOOLEAN), @RestParameter(name = "withmetadata", isRequired = false, description = "Whether the metadata catalogs should be included in the response.", type = Type.BOOLEAN), @RestParameter(name = "withpublications", isRequired = false, description = "Whether the publication ids and urls should be included in the response.", type = Type.BOOLEAN), @RestParameter(name = "filter", isRequired = false, description = "A comma seperated list of filters to limit the results with. A filter is the filter's name followed by a colon \":\" and then the value to filter with so it is the form <Filter Name>:<Value to Filter With>.", type = STRING), @RestParameter(name = "sort", description = "Sort the results based upon a list of comma seperated sorting criteria. In the comma seperated list each type of sorting is specified as a pair such as: <Sort Name>:ASC or <Sort Name>:DESC. Adding the suffix ASC or DESC sets the order as ascending or descending order and is mandatory.", isRequired = false, type = STRING), @RestParameter(name = "limit", description = "The maximum number of results to return for a single request.", isRequired = false, type = RestParameter.Type.INTEGER), @RestParameter(name = "offset", description = "Number of results to skip based on the limit. 0 is the first set of results up to the limit, 1 is the second set of results after the first limit, 2 is third set of results after skipping the first two sets of results etc.", isRequired = false, type = RestParameter.Type.INTEGER) }, reponses = { @RestResponse(description = "A (potentially empty) list of events is returned.", responseCode = HttpServletResponse.SC_OK) })
public Response getEvents(@HeaderParam("Accept") String acceptHeader, @QueryParam("id") String id, @QueryParam("commentReason") String reasonFilter, @QueryParam("commentResolution") String resolutionFilter, @QueryParam("filter") String filter, @QueryParam("sort") String sort, @QueryParam("offset") Integer offset, @QueryParam("limit") Integer limit, @QueryParam("sign") boolean sign, @QueryParam("withacl") Boolean withAcl, @QueryParam("withmetadata") Boolean withMetadata, @QueryParam("withpublications") Boolean withPublications) {
    Option<Integer> optLimit = Option.option(limit);
    Option<Integer> optOffset = Option.option(offset);
    Option<String> optSort = Option.option(trimToNull(sort));
    EventSearchQuery query = new EventSearchQuery(getSecurityService().getOrganization().getId(), getSecurityService().getUser());
    // If the limit is set to 0, this is not taken into account
    if (optLimit.isSome() && limit == 0) {
        optLimit = Option.none();
    }
    // Parse the filters
    if (StringUtils.isNotBlank(filter)) {
        for (String f : filter.split(",")) {
            String[] filterTuple = f.split(":");
            if (filterTuple.length < 2) {
                logger.info("No value for filter {} in filters list: {}", filterTuple[0], filter);
                continue;
            }
            String name = filterTuple[0];
            String value = filterTuple[1];
            if ("presenters".equals(name))
                query.withPresenter(value);
            if ("contributors".equals(name))
                query.withContributor(value);
            if ("location".equals(name))
                query.withLocation(value);
            if ("textFilter".equals(name))
                query.withText("*" + value + "*");
            if ("series".equals(name))
                query.withSeriesId(value);
            if ("subject".equals(name))
                query.withSubject(value);
        }
    }
    if (optSort.isSome()) {
        Set<SortCriterion> sortCriteria = RestUtils.parseSortQueryParameter(optSort.get());
        for (SortCriterion criterion : sortCriteria) {
            switch(criterion.getFieldName()) {
                case EventIndexSchema.TITLE:
                    query.sortByTitle(criterion.getOrder());
                    break;
                case EventIndexSchema.PRESENTER:
                    query.sortByPresenter(criterion.getOrder());
                    break;
                case EventIndexSchema.TECHNICAL_START:
                case "technical_date":
                    query.sortByTechnicalStartDate(criterion.getOrder());
                    break;
                case EventIndexSchema.TECHNICAL_END:
                    query.sortByTechnicalEndDate(criterion.getOrder());
                    break;
                case EventIndexSchema.START_DATE:
                case "date":
                    query.sortByStartDate(criterion.getOrder());
                    break;
                case EventIndexSchema.END_DATE:
                    query.sortByEndDate(criterion.getOrder());
                    break;
                case EventIndexSchema.REVIEW_STATUS:
                    query.sortByReviewStatus(criterion.getOrder());
                    break;
                case EventIndexSchema.WORKFLOW_STATE:
                    query.sortByWorkflowState(criterion.getOrder());
                    break;
                case EventIndexSchema.SCHEDULING_STATUS:
                    query.sortBySchedulingStatus(criterion.getOrder());
                    break;
                case EventIndexSchema.SERIES_NAME:
                    query.sortBySeriesName(criterion.getOrder());
                    break;
                case EventIndexSchema.LOCATION:
                    query.sortByLocation(criterion.getOrder());
                    break;
                default:
                    return RestUtil.R.badRequest(String.format("Unknown search criterion in request: %s", criterion.getFieldName()));
            }
        }
    }
    // TODO: Add the comment resolution filter to the query
    CommentResolution resolution = null;
    if (StringUtils.isNotBlank(resolutionFilter)) {
        try {
            resolution = CommentResolution.valueOf(resolutionFilter);
        } catch (Exception e) {
            logger.debug("Unable to parse comment resolution filter {}", resolutionFilter);
            return Response.status(Status.BAD_REQUEST).build();
        }
    }
    if (optLimit.isSome())
        query.withLimit(optLimit.get());
    if (optOffset.isSome())
        query.withOffset(offset);
    // TODO: Add other filters to the query
    SearchResult<Event> results = null;
    try {
        results = externalIndex.getByQuery(query);
    } catch (SearchIndexException e) {
        logger.error("The External Search Index was not able to get the events list: {}", ExceptionUtils.getStackTrace(e));
        throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
    }
    SearchResultItem<Event>[] items = results.getItems();
    List<IndexObject> events = new ArrayList<>();
    for (SearchResultItem<Event> item : items) {
        Event source = item.getSource();
        source.updatePreview(previewSubtype);
        events.add(source);
    }
    try {
        return getJsonEvents(acceptHeader, events, withAcl, withMetadata, withPublications, sign);
    } catch (Exception e) {
        logger.error("Unable to get events because: {}", ExceptionUtils.getStackTrace(e));
        throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) WebApplicationException(javax.ws.rs.WebApplicationException) EventSearchQuery(org.opencastproject.index.service.impl.index.event.EventSearchQuery) SearchResultItem(org.opencastproject.matterhorn.search.SearchResultItem) ArrayList(java.util.ArrayList) 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) SortCriterion(org.opencastproject.matterhorn.search.SortCriterion) Event(org.opencastproject.index.service.impl.index.event.Event) IndexObject(org.opencastproject.index.service.impl.index.IndexObject) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Aggregations

ArrayList (java.util.ArrayList)2 IndexObject (org.opencastproject.index.service.impl.index.IndexObject)2 Event (org.opencastproject.index.service.impl.index.event.Event)2 IOException (java.io.IOException)1 GET (javax.ws.rs.GET)1 Path (javax.ws.rs.Path)1 Produces (javax.ws.rs.Produces)1 WebApplicationException (javax.ws.rs.WebApplicationException)1 Response (javax.ws.rs.core.Response)1 ParseException (org.json.simple.parser.ParseException)1 Ignore (org.junit.Ignore)1 Test (org.junit.Test)1 IndexServiceException (org.opencastproject.index.service.exception.IndexServiceException)1 EventSearchQuery (org.opencastproject.index.service.impl.index.event.EventSearchQuery)1 IngestException (org.opencastproject.ingest.api.IngestException)1 SearchIndexException (org.opencastproject.matterhorn.search.SearchIndexException)1 SearchResultItem (org.opencastproject.matterhorn.search.SearchResultItem)1 SortCriterion (org.opencastproject.matterhorn.search.SortCriterion)1 MediaPackageException (org.opencastproject.mediapackage.MediaPackageException)1 Publication (org.opencastproject.mediapackage.Publication)1