Search in sources :

Example 11 with SortCriterion

use of org.opencastproject.matterhorn.search.SortCriterion in project opencast by opencast.

the class SeriesEndpoint method getSeries.

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("series.json")
@RestQuery(name = "listSeriesAsJson", description = "Returns the series matching the query parameters", returnDescription = "Returns the series search results as JSON", restParameters = { @RestParameter(name = "sortorganizer", isRequired = false, description = "The sort type to apply to the series organizer or organizers either Ascending or Descending.", 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 = "filter", isRequired = false, description = "The filter used for the query. They should be formated like that: 'filter1:value1,filter2,value2'", type = STRING), @RestParameter(name = "offset", isRequired = false, description = "The page offset", type = INTEGER, defaultValue = "0"), @RestParameter(name = "optedOut", isRequired = false, description = "Whether this series is opted out", type = BOOLEAN), @RestParameter(name = "limit", isRequired = false, description = "Results per page (max 100)", type = INTEGER, defaultValue = "100") }, reponses = { @RestResponse(responseCode = SC_OK, description = "The access control list."), @RestResponse(responseCode = SC_UNAUTHORIZED, description = "If the current user is not authorized to perform this action") })
public Response getSeries(@QueryParam("filter") String filter, @QueryParam("sort") String sort, @QueryParam("offset") int offset, @QueryParam("limit") int limit, @QueryParam("optedOut") Boolean optedOut) throws UnauthorizedException {
    try {
        logger.debug("Requested series list");
        SeriesSearchQuery query = new SeriesSearchQuery(securityService.getOrganization().getId(), securityService.getUser());
        Option<String> optSort = Option.option(trimToNull(sort));
        if (offset != 0) {
            query.withOffset(offset);
        }
        // If limit is 0, we set the default limit
        query.withLimit(limit == 0 ? DEFAULT_LIMIT : limit);
        if (optedOut != null)
            query.withOptedOut(optedOut);
        Map<String, String> filters = RestUtils.parseFilter(filter);
        for (String name : filters.keySet()) {
            if (SeriesListQuery.FILTER_ACL_NAME.equals(name)) {
                query.withManagedAcl(filters.get(name));
            } else if (SeriesListQuery.FILTER_CONTRIBUTORS_NAME.equals(name)) {
                query.withContributor(filters.get(name));
            } else if (SeriesListQuery.FILTER_CREATIONDATE_NAME.equals(name)) {
                try {
                    Tuple<Date, Date> fromAndToCreationRange = RestUtils.getFromAndToDateRange(filters.get(name));
                    query.withCreatedFrom(fromAndToCreationRange.getA());
                    query.withCreatedTo(fromAndToCreationRange.getB());
                } catch (IllegalArgumentException e) {
                    return RestUtil.R.badRequest(e.getMessage());
                }
            } else if (SeriesListQuery.FILTER_CREATOR_NAME.equals(name)) {
                query.withCreator(filters.get(name));
            } else if (SeriesListQuery.FILTER_TEXT_NAME.equals(name)) {
                query.withText(QueryPreprocessor.sanitize(filters.get(name)));
            } else if (SeriesListQuery.FILTER_LANGUAGE_NAME.equals(name)) {
                query.withLanguage(filters.get(name));
            } else if (SeriesListQuery.FILTER_LICENSE_NAME.equals(name)) {
                query.withLicense(filters.get(name));
            } else if (SeriesListQuery.FILTER_ORGANIZERS_NAME.equals(name)) {
                query.withOrganizer(filters.get(name));
            } else if (SeriesListQuery.FILTER_SUBJECT_NAME.equals(name)) {
                query.withSubject(filters.get(name));
            } else if (SeriesListQuery.FILTER_TITLE_NAME.equals(name)) {
                query.withTitle(filters.get(name));
            }
        }
        if (optSort.isSome()) {
            Set<SortCriterion> sortCriteria = RestUtils.parseSortQueryParameter(optSort.get());
            for (SortCriterion criterion : sortCriteria) {
                switch(criterion.getFieldName()) {
                    case SeriesIndexSchema.TITLE:
                        query.sortByTitle(criterion.getOrder());
                        break;
                    case SeriesIndexSchema.CONTRIBUTORS:
                        query.sortByContributors(criterion.getOrder());
                        break;
                    case SeriesIndexSchema.CREATOR:
                        query.sortByOrganizers(criterion.getOrder());
                        break;
                    case SeriesIndexSchema.CREATED_DATE_TIME:
                        query.sortByCreatedDateTime(criterion.getOrder());
                        break;
                    case SeriesIndexSchema.MANAGED_ACL:
                        query.sortByManagedAcl(criterion.getOrder());
                        break;
                    default:
                        logger.info("Unknown filter criteria {}", criterion.getFieldName());
                        return Response.status(SC_BAD_REQUEST).build();
                }
            }
        }
        logger.trace("Using Query: " + query.toString());
        SearchResult<Series> result = searchIndex.getByQuery(query);
        if (logger.isDebugEnabled()) {
            logger.debug("Found {} results in {} ms", result.getDocumentCount(), result.getSearchTime());
        }
        List<JValue> series = new ArrayList<>();
        for (SearchResultItem<Series> item : result.getItems()) {
            List<Field> fields = new ArrayList<>();
            Series s = item.getSource();
            String sId = s.getIdentifier();
            fields.add(f("id", v(sId)));
            fields.add(f("optedOut", v(s.isOptedOut())));
            fields.add(f("title", v(s.getTitle(), Jsons.BLANK)));
            fields.add(f("organizers", arr($(s.getOrganizers()).map(Functions.stringToJValue))));
            fields.add(f("contributors", arr($(s.getContributors()).map(Functions.stringToJValue))));
            if (s.getCreator() != null) {
                fields.add(f("createdBy", v(s.getCreator())));
            }
            if (s.getCreatedDateTime() != null) {
                fields.add(f("creation_date", v(toUTC(s.getCreatedDateTime().getTime()), Jsons.BLANK)));
            }
            if (s.getLanguage() != null) {
                fields.add(f("language", v(s.getLanguage())));
            }
            if (s.getLicense() != null) {
                fields.add(f("license", v(s.getLicense())));
            }
            if (s.getRightsHolder() != null) {
                fields.add(f("rightsHolder", v(s.getRightsHolder())));
            }
            if (StringUtils.isNotBlank(s.getManagedAcl())) {
                fields.add(f("managedAcl", v(s.getManagedAcl())));
            }
            series.add(obj(fields));
        }
        logger.debug("Request done");
        return okJsonList(series, offset, limit, result.getHitCount());
    } catch (Exception e) {
        logger.warn("Could not perform search query: {}", ExceptionUtils.getStackTrace(e));
        throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) SeriesSearchQuery(org.opencastproject.index.service.impl.index.series.SeriesSearchQuery) ArrayList(java.util.ArrayList) Date(java.util.Date) WebApplicationException(javax.ws.rs.WebApplicationException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) SeriesException(org.opencastproject.series.api.SeriesException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) AclServiceException(org.opencastproject.authorization.xacml.manager.api.AclServiceException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) Series(org.opencastproject.index.service.impl.index.series.Series) Field(com.entwinemedia.fn.data.json.Field) MetadataField(org.opencastproject.metadata.dublincore.MetadataField) SortCriterion(org.opencastproject.matterhorn.search.SortCriterion) JValue(com.entwinemedia.fn.data.json.JValue) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 12 with SortCriterion

use of org.opencastproject.matterhorn.search.SortCriterion in project opencast by opencast.

the class ThemesEndpoint method getThemes.

@GET
@Produces({ MediaType.APPLICATION_JSON })
@Path("themes.json")
@RestQuery(name = "getThemes", description = "Return all of the known themes on the system", 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(defaultValue = "0", description = "The maximum number of items to return per page.", isRequired = false, name = "limit", type = RestParameter.Type.INTEGER), @RestParameter(defaultValue = "0", description = "The page number.", isRequired = false, name = "offset", type = RestParameter.Type.INTEGER), @RestParameter(name = "sort", isRequired = false, description = "The sort order. May include any of the following: NAME, CREATOR.  Add '_DESC' to reverse the sort order (e.g. CREATOR_DESC).", type = STRING) }, reponses = { @RestResponse(description = "A JSON representation of the themes", responseCode = HttpServletResponse.SC_OK) }, returnDescription = "")
public Response getThemes(@QueryParam("filter") String filter, @QueryParam("limit") int limit, @QueryParam("offset") int offset, @QueryParam("sort") String sort) {
    Option<Integer> optLimit = Option.option(limit);
    Option<Integer> optOffset = Option.option(offset);
    Option<String> optSort = Option.option(trimToNull(sort));
    ThemeSearchQuery query = new ThemeSearchQuery(securityService.getOrganization().getId(), securityService.getUser());
    // If the limit is set to 0, this is not taken into account
    if (optLimit.isSome() && limit == 0) {
        optLimit = Option.none();
    }
    if (optLimit.isSome())
        query.withLimit(optLimit.get());
    if (optOffset.isSome())
        query.withOffset(offset);
    Map<String, String> filters = RestUtils.parseFilter(filter);
    for (String name : filters.keySet()) {
        if (ThemesListQuery.FILTER_CREATOR_NAME.equals(name))
            query.withCreator(filters.get(name));
        if (ThemesListQuery.FILTER_TEXT_NAME.equals(name))
            query.withText(QueryPreprocessor.sanitize(filters.get(name)));
    }
    if (optSort.isSome()) {
        Set<SortCriterion> sortCriteria = RestUtils.parseSortQueryParameter(optSort.get());
        for (SortCriterion criterion : sortCriteria) {
            switch(criterion.getFieldName()) {
                case ThemeIndexSchema.NAME:
                    query.sortByName(criterion.getOrder());
                    break;
                case ThemeIndexSchema.DESCRIPTION:
                    query.sortByDescription(criterion.getOrder());
                    break;
                case ThemeIndexSchema.CREATOR:
                    query.sortByCreator(criterion.getOrder());
                    break;
                case ThemeIndexSchema.DEFAULT:
                    query.sortByDefault(criterion.getOrder());
                    break;
                case ThemeIndexSchema.CREATION_DATE:
                    query.sortByCreatedDateTime(criterion.getOrder());
                    break;
                default:
                    logger.info("Unknown sort criteria {}", criterion.getFieldName());
                    return Response.status(SC_BAD_REQUEST).build();
            }
        }
    }
    logger.trace("Using Query: " + query.toString());
    SearchResult<org.opencastproject.index.service.impl.index.theme.Theme> results = null;
    try {
        results = searchIndex.getByQuery(query);
    } catch (SearchIndexException e) {
        logger.error("The admin UI Search Index was not able to get the themes list:", e);
        return RestUtil.R.serverError();
    }
    List<JValue> themesJSON = new ArrayList<JValue>();
    // If the results list if empty, we return already a response.
    if (results.getPageSize() == 0) {
        logger.debug("No themes match the given filters.");
        return okJsonList(themesJSON, nul(offset).getOr(0), nul(limit).getOr(0), 0);
    }
    for (SearchResultItem<org.opencastproject.index.service.impl.index.theme.Theme> item : results.getItems()) {
        org.opencastproject.index.service.impl.index.theme.Theme theme = item.getSource();
        themesJSON.add(themeToJSON(theme, false));
    }
    return okJsonList(themesJSON, nul(offset).getOr(0), nul(limit).getOr(0), results.getHitCount());
}
Also used : SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) ArrayList(java.util.ArrayList) ThemeSearchQuery(org.opencastproject.index.service.impl.index.theme.ThemeSearchQuery) SortCriterion(org.opencastproject.matterhorn.search.SortCriterion) JValue(com.entwinemedia.fn.data.json.JValue) Theme(org.opencastproject.themes.Theme) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 13 with SortCriterion

use of org.opencastproject.matterhorn.search.SortCriterion 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)

Example 14 with SortCriterion

use of org.opencastproject.matterhorn.search.SortCriterion in project opencast by opencast.

the class SeriesEndpoint method getSeriesList.

@GET
@Path("")
@Produces({ "application/json", "application/v1.0.0+json" })
@RestQuery(name = "getseries", description = "Returns a list of series.", returnDescription = "", restParameters = { @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 series is returned.", responseCode = HttpServletResponse.SC_OK) })
public Response getSeriesList(@HeaderParam("Accept") String acceptHeader, @QueryParam("filter") String filter, @QueryParam("sort") String sort, @QueryParam("order") String order, @QueryParam("offset") int offset, @QueryParam("limit") int limit) throws UnauthorizedException {
    try {
        SeriesSearchQuery query = new SeriesSearchQuery(securityService.getOrganization().getId(), securityService.getUser());
        Option<String> optSort = Option.option(trimToNull(sort));
        if (offset > 0) {
            query.withOffset(offset);
        }
        // If limit is 0, we set the default limit
        query.withLimit(limit < 1 ? DEFAULT_LIMIT : limit);
        // 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 ("managedAcl".equals(name)) {
                    query.withAccessPolicy(value);
                } else if ("contributors".equals(name)) {
                    query.withContributor(value);
                } else if ("CreationDate".equals(name)) {
                    if (name.split("/").length == 2) {
                        try {
                            Tuple<Date, Date> fromAndToCreationRange = getFromAndToCreationRange(name.split("/")[0], name.split("/")[1]);
                            query.withCreatedFrom(fromAndToCreationRange.getA());
                            query.withCreatedTo(fromAndToCreationRange.getB());
                        } catch (IllegalArgumentException e) {
                            return RestUtil.R.badRequest(e.getMessage());
                        }
                    }
                    query.withCreator(value);
                } else if ("Creator".equals(name)) {
                    query.withCreator(value);
                } else if ("textFilter".equals(name)) {
                    query.withText("*" + value + "*");
                } else if ("language".equals(name)) {
                    query.withLanguage(value);
                } else if ("license".equals(name)) {
                    query.withLicense(value);
                } else if ("organizers".equals(name)) {
                    query.withOrganizer(value);
                } else if ("subject".equals(name)) {
                    query.withSubject(value);
                } else if ("title".equals(name)) {
                    query.withTitle(value);
                }
            }
        }
        if (optSort.isSome()) {
            Set<SortCriterion> sortCriteria = RestUtils.parseSortQueryParameter(optSort.get());
            for (SortCriterion criterion : sortCriteria) {
                switch(criterion.getFieldName()) {
                    case SeriesIndexSchema.TITLE:
                        query.sortByTitle(criterion.getOrder());
                        break;
                    case SeriesIndexSchema.CONTRIBUTORS:
                        query.sortByContributors(criterion.getOrder());
                        break;
                    case SeriesIndexSchema.CREATOR:
                        query.sortByOrganizers(criterion.getOrder());
                        break;
                    case EventIndexSchema.CREATED:
                        query.sortByCreatedDateTime(criterion.getOrder());
                        break;
                    default:
                        logger.info("Unknown filter criteria {}", criterion.getFieldName());
                        return Response.status(SC_BAD_REQUEST).build();
                }
            }
        }
        logger.trace("Using Query: " + query.toString());
        SearchResult<Series> result = externalIndex.getByQuery(query);
        return ApiResponses.Json.ok(VERSION_1_0_0, arr($(result.getItems()).map(new Fn<SearchResultItem<Series>, JValue>() {

            @Override
            public JValue apply(SearchResultItem<Series> a) {
                final Series s = a.getSource();
                JValue subjects;
                if (s.getSubject() == null) {
                    subjects = arr();
                } else {
                    subjects = arr(splitSubjectIntoArray(s.getSubject()));
                }
                Date createdDate = s.getCreatedDateTime();
                return obj(f("identifier", v(s.getIdentifier())), f("title", v(s.getTitle())), f("creator", v(s.getCreator(), BLANK)), f("created", v(createdDate != null ? toUTC(createdDate.getTime()) : null, BLANK)), f("subjects", subjects), f("contributors", arr($(s.getContributors()).map(Functions.stringToJValue))), f("organizers", arr($(s.getOrganizers()).map(Functions.stringToJValue))), f("publishers", arr($(s.getPublishers()).map(Functions.stringToJValue))));
            }
        }).toList()));
    } catch (Exception e) {
        logger.warn("Could not perform search query: {}", ExceptionUtils.getStackTrace(e));
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) SeriesSearchQuery(org.opencastproject.index.service.impl.index.series.SeriesSearchQuery) Fn(com.entwinemedia.fn.Fn) SearchResultItem(org.opencastproject.matterhorn.search.SearchResultItem) Date(java.util.Date) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) SeriesException(org.opencastproject.series.api.SeriesException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) WebApplicationException(javax.ws.rs.WebApplicationException) ParseException(org.json.simple.parser.ParseException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) Series(org.opencastproject.index.service.impl.index.series.Series) SortCriterion(org.opencastproject.matterhorn.search.SortCriterion) JValue(com.entwinemedia.fn.data.json.JValue) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 15 with SortCriterion

use of org.opencastproject.matterhorn.search.SortCriterion in project opencast by opencast.

the class IndexServiceImpl method getGroups.

@Override
public SearchResult<Group> getGroups(String filter, Opt<Integer> optLimit, Opt<Integer> optOffset, Opt<String> optSort, AbstractSearchIndex index) throws SearchIndexException {
    GroupSearchQuery query = new GroupSearchQuery(securityService.getOrganization().getId(), securityService.getUser());
    // 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 (GroupsListQuery.FILTER_NAME_NAME.equals(name))
                query.withName(value);
        }
    }
    if (optSort.isSome()) {
        Set<SortCriterion> sortCriteria = RestUtils.parseSortQueryParameter(optSort.get());
        for (SortCriterion criterion : sortCriteria) {
            switch(criterion.getFieldName()) {
                case GroupIndexSchema.NAME:
                    query.sortByName(criterion.getOrder());
                    break;
                case GroupIndexSchema.DESCRIPTION:
                    query.sortByDescription(criterion.getOrder());
                    break;
                case GroupIndexSchema.ROLE:
                    query.sortByRole(criterion.getOrder());
                    break;
                case GroupIndexSchema.MEMBERS:
                    query.sortByMembers(criterion.getOrder());
                    break;
                case GroupIndexSchema.ROLES:
                    query.sortByRoles(criterion.getOrder());
                    break;
                default:
                    throw new WebApplicationException(Status.BAD_REQUEST);
            }
        }
    }
    if (optLimit.isSome())
        query.withLimit(optLimit.get());
    if (optOffset.isSome())
        query.withOffset(optOffset.get());
    return index.getByQuery(query);
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) SortCriterion(org.opencastproject.matterhorn.search.SortCriterion) GroupSearchQuery(org.opencastproject.index.service.impl.index.group.GroupSearchQuery)

Aggregations

SortCriterion (org.opencastproject.matterhorn.search.SortCriterion)15 GET (javax.ws.rs.GET)13 Path (javax.ws.rs.Path)13 Produces (javax.ws.rs.Produces)13 RestQuery (org.opencastproject.util.doc.rest.RestQuery)13 ArrayList (java.util.ArrayList)11 JValue (com.entwinemedia.fn.data.json.JValue)10 WebApplicationException (javax.ws.rs.WebApplicationException)10 SearchIndexException (org.opencastproject.matterhorn.search.SearchIndexException)6 NotFoundException (org.opencastproject.util.NotFoundException)5 IndexServiceException (org.opencastproject.index.service.exception.IndexServiceException)4 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)4 SmartIterator (org.opencastproject.util.SmartIterator)4 Date (java.util.Date)3 Order (org.opencastproject.matterhorn.search.SearchQuery.Order)3 Field (com.entwinemedia.fn.data.json.Field)2 ParseException (java.text.ParseException)2 HashSet (java.util.HashSet)2 ParseException (org.json.simple.parser.ParseException)2 AclServiceException (org.opencastproject.authorization.xacml.manager.api.AclServiceException)2