Search in sources :

Example 1 with EventSearchQuery

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

the class AbstractEventEndpoint method getEvents.

@GET
@Path("events.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "getevents", description = "Returns all the events as JSON", returnDescription = "All the events as JSON", restParameters = { @RestParameter(name = "filter", isRequired = false, description = "The filter used for the query. They should be formated like that: 'filter1:value1,filter2:value2'", type = STRING), @RestParameter(name = "sort", description = "The order instructions used to sort the query result. Must be in the form '<field name>:(ASC|DESC)'", isRequired = false, type = STRING), @RestParameter(name = "limit", description = "The maximum number of items to return per page.", isRequired = false, type = RestParameter.Type.INTEGER), @RestParameter(name = "offset", description = "The page number.", isRequired = false, type = RestParameter.Type.INTEGER) }, reponses = { @RestResponse(description = "Returns all events as JSON", responseCode = HttpServletResponse.SC_OK) })
public Response getEvents(@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) {
    Option<Integer> optLimit = Option.option(limit);
    Option<Integer> optOffset = Option.option(offset);
    Option<String> optSort = Option.option(trimToNull(sort));
    ArrayList<JValue> eventsList = new ArrayList<>();
    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();
    }
    Map<String, String> filters = RestUtils.parseFilter(filter);
    for (String name : filters.keySet()) {
        if (EventListQuery.FILTER_PRESENTERS_BIBLIOGRAPHIC_NAME.equals(name))
            query.withPresenter(filters.get(name));
        if (EventListQuery.FILTER_PRESENTERS_TECHNICAL_NAME.equals(name))
            query.withTechnicalPresenters(filters.get(name));
        if (EventListQuery.FILTER_CONTRIBUTORS_NAME.equals(name))
            query.withContributor(filters.get(name));
        if (EventListQuery.FILTER_LOCATION_NAME.equals(name))
            query.withLocation(filters.get(name));
        if (EventListQuery.FILTER_AGENT_NAME.equals(name))
            query.withAgentId(filters.get(name));
        if (EventListQuery.FILTER_TEXT_NAME.equals(name))
            query.withText(QueryPreprocessor.sanitize(filters.get(name)));
        if (EventListQuery.FILTER_SERIES_NAME.equals(name))
            query.withSeriesId(filters.get(name));
        if (EventListQuery.FILTER_STATUS_NAME.equals(name))
            query.withEventStatus(filters.get(name));
        if (EventListQuery.FILTER_OPTEDOUT_NAME.equals(name))
            query.withOptedOut(Boolean.parseBoolean(filters.get(name)));
        if (EventListQuery.FILTER_REVIEW_STATUS_NAME.equals(name))
            query.withReviewStatus(filters.get(name));
        if (EventListQuery.FILTER_COMMENTS_NAME.equals(name)) {
            switch(Comments.valueOf(filters.get(name))) {
                case NONE:
                    query.withComments(false);
                    break;
                case OPEN:
                    query.withOpenComments(true);
                    break;
                case RESOLVED:
                    query.withComments(true);
                    query.withOpenComments(false);
                    break;
                default:
                    logger.info("Unknown comment {}", filters.get(name));
                    return Response.status(SC_BAD_REQUEST).build();
            }
        }
        if (EventListQuery.FILTER_STARTDATE_NAME.equals(name)) {
            try {
                Tuple<Date, Date> fromAndToCreationRange = RestUtils.getFromAndToDateRange(filters.get(name));
                query.withTechnicalStartFrom(fromAndToCreationRange.getA());
                query.withTechnicalStartTo(fromAndToCreationRange.getB());
            } catch (IllegalArgumentException e) {
                return RestUtil.R.badRequest(e.getMessage());
            }
        }
    }
    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.PUBLICATION:
                    query.sortByPublicationIgnoringInternal(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.SERIES_NAME:
                    query.sortBySeriesName(criterion.getOrder());
                    break;
                case EventIndexSchema.LOCATION:
                    query.sortByLocation(criterion.getOrder());
                    break;
                case EventIndexSchema.EVENT_STATUS:
                    query.sortByEventStatus(criterion.getOrder());
                    break;
                default:
                    throw new WebApplicationException(Status.BAD_REQUEST);
            }
        }
    }
    // TODO: Add the comment resolution filter to the query
    EventCommentsListProvider.RESOLUTION resolution = null;
    if (StringUtils.isNotBlank(resolutionFilter)) {
        try {
            resolution = EventCommentsListProvider.RESOLUTION.valueOf(resolutionFilter);
        } catch (Exception e) {
            logger.warn("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 = getIndex().getByQuery(query);
    } catch (SearchIndexException e) {
        logger.error("The admin UI Search Index was not able to get the events list:", e);
        return RestUtil.R.serverError();
    }
    // If the results list if empty, we return already a response.
    if (results.getPageSize() == 0) {
        logger.debug("No events match the given filters.");
        return okJsonList(eventsList, nul(offset).getOr(0), nul(limit).getOr(0), 0);
    }
    for (SearchResultItem<Event> item : results.getItems()) {
        Event source = item.getSource();
        source.updatePreview(getAdminUIConfiguration().getPreviewSubtype());
        eventsList.add(eventToJSON(source));
    }
    return okJsonList(eventsList, nul(offset).getOr(0), nul(limit).getOr(0), results.getHitCount());
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) EventCommentsListProvider(org.opencastproject.index.service.resources.list.provider.EventCommentsListProvider) EventSearchQuery(org.opencastproject.index.service.impl.index.event.EventSearchQuery) ArrayList(java.util.ArrayList) Date(java.util.Date) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) WebApplicationException(javax.ws.rs.WebApplicationException) EventCommentException(org.opencastproject.event.comment.EventCommentException) JSONException(org.codehaus.jettison.json.JSONException) JobEndpointException(org.opencastproject.adminui.exception.JobEndpointException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) ParseException(java.text.ParseException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) AclServiceException(org.opencastproject.authorization.xacml.manager.api.AclServiceException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) WorkflowStateException(org.opencastproject.workflow.api.WorkflowStateException) JValue(com.entwinemedia.fn.data.json.JValue) SortCriterion(org.opencastproject.matterhorn.search.SortCriterion) Event(org.opencastproject.index.service.impl.index.event.Event) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 2 with EventSearchQuery

use of org.opencastproject.index.service.impl.index.event.EventSearchQuery 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 3 with EventSearchQuery

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

the class EventsEndpoint method extendEventsStatusOverview.

private void extendEventsStatusOverview(List<Field> fields, Series series) throws SearchIndexException {
    EventSearchQuery query = new EventSearchQuery(getSecurityService().getOrganization().getId(), getSecurityService().getUser()).withoutActions().withSeriesId(series.getIdentifier());
    SearchResult<Event> result = externalIndex.getByQuery(query);
    // collect recording statuses
    int blacklisted = 0;
    int optOut = 0;
    int ready = 0;
    for (SearchResultItem<Event> item : result.getItems()) {
        Event event = item.getSource();
        if (event.getSchedulingStatus() == null)
            continue;
        SchedulingStatus schedulingStatus = SchedulingStatus.valueOf(event.getSchedulingStatus());
        if (SchedulingStatus.BLACKLISTED.equals(schedulingStatus)) {
            blacklisted++;
        } else if (series.isOptedOut() || SchedulingStatus.OPTED_OUT.equals(schedulingStatus)) {
            optOut++;
        } else {
            ready++;
        }
    }
    fields.add(f("events", obj(f("BLACKLISTED", v(blacklisted)), f("OPTED_OUT", v(optOut)), f("READY", v(ready)))));
}
Also used : EventSearchQuery(org.opencastproject.index.service.impl.index.event.EventSearchQuery) Event(org.opencastproject.index.service.impl.index.event.Event) SchedulingStatus(org.opencastproject.index.service.impl.index.event.Event.SchedulingStatus)

Example 4 with EventSearchQuery

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

the class SeriesEndpoint method hasProcessingEvents.

/**
 * Check if the series with the given Id has events being currently processed
 *
 * @param seriesId
 *          the series Id
 * @return true if events being part of the series are currently processed
 */
private boolean hasProcessingEvents(String seriesId) {
    EventSearchQuery query = new EventSearchQuery(securityService.getOrganization().getId(), securityService.getUser());
    long elementsCount = 0;
    query.withSeriesId(seriesId);
    try {
        query.withWorkflowState(WorkflowInstance.WorkflowState.RUNNING.toString());
        SearchResult<Event> events = searchIndex.getByQuery(query);
        elementsCount = events.getHitCount();
        query.withWorkflowState(WorkflowInstance.WorkflowState.INSTANTIATED.toString());
        events = searchIndex.getByQuery(query);
        elementsCount += events.getHitCount();
    } catch (SearchIndexException e) {
        logger.warn("Could not perform search query: {}", ExceptionUtils.getStackTrace(e));
        throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
    }
    return elementsCount > 0;
}
Also used : SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) WebApplicationException(javax.ws.rs.WebApplicationException) EventSearchQuery(org.opencastproject.index.service.impl.index.event.EventSearchQuery) Event(org.opencastproject.index.service.impl.index.event.Event)

Example 5 with EventSearchQuery

use of org.opencastproject.index.service.impl.index.event.EventSearchQuery 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

Event (org.opencastproject.index.service.impl.index.event.Event)6 EventSearchQuery (org.opencastproject.index.service.impl.index.event.EventSearchQuery)6 WebApplicationException (javax.ws.rs.WebApplicationException)3 SearchIndexException (org.opencastproject.matterhorn.search.SearchIndexException)3 ArrayList (java.util.ArrayList)2 GET (javax.ws.rs.GET)2 Path (javax.ws.rs.Path)2 Produces (javax.ws.rs.Produces)2 IndexServiceException (org.opencastproject.index.service.exception.IndexServiceException)2 SearchResultItem (org.opencastproject.matterhorn.search.SearchResultItem)2 SortCriterion (org.opencastproject.matterhorn.search.SortCriterion)2 SchedulerException (org.opencastproject.scheduler.api.SchedulerException)2 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)2 UrlSigningException (org.opencastproject.security.urlsigning.exception.UrlSigningException)2 NotFoundException (org.opencastproject.util.NotFoundException)2 RestQuery (org.opencastproject.util.doc.rest.RestQuery)2 JValue (com.entwinemedia.fn.data.json.JValue)1 IOException (java.io.IOException)1 ParseException (java.text.ParseException)1 Date (java.util.Date)1