Search in sources :

Example 1 with SortCriterion

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

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

the class AclEndpoint method getAclsAsJson.

@GET
@Path("acls.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "allaclasjson", description = "Returns a list of acls", returnDescription = "Returns a JSON representation of the list of acls available the current user's organization", 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", isRequired = false, description = "The sort order. May include any of the following: NAME. Add '_DESC' to reverse the sort order (e.g. NAME_DESC).", type = STRING), @RestParameter(defaultValue = "100", description = "The maximum number of items to return per page.", isRequired = false, name = "limit", type = RestParameter.Type.STRING), @RestParameter(defaultValue = "0", description = "The page number.", isRequired = false, name = "offset", type = RestParameter.Type.STRING) }, reponses = { @RestResponse(responseCode = SC_OK, description = "The list of ACL's has successfully been returned") })
public Response getAclsAsJson(@QueryParam("filter") String filter, @QueryParam("sort") String sort, @QueryParam("offset") int offset, @QueryParam("limit") int limit) throws IOException {
    if (limit < 1)
        limit = 100;
    Opt<String> optSort = Opt.nul(trimToNull(sort));
    Option<String> filterName = Option.none();
    Option<String> filterText = Option.none();
    Map<String, String> filters = RestUtils.parseFilter(filter);
    for (String name : filters.keySet()) {
        String value = filters.get(name);
        if (AclsListQuery.FILTER_NAME_NAME.equals(name)) {
            filterName = Option.some(value);
        } else if ((AclsListQuery.FILTER_TEXT_NAME.equals(name)) && (StringUtils.isNotBlank(value))) {
            filterText = Option.some(value);
        }
    }
    // Filter acls by filter criteria
    List<ManagedAcl> filteredAcls = new ArrayList<>();
    for (ManagedAcl acl : aclService().getAcls()) {
        // Filter list
        if ((filterName.isSome() && !filterName.get().equals(acl.getName())) || (filterText.isSome() && !TextFilter.match(filterText.get(), acl.getName()))) {
            continue;
        }
        filteredAcls.add(acl);
    }
    int total = filteredAcls.size();
    // Sort by name, description or role
    if (optSort.isSome()) {
        final Set<SortCriterion> sortCriteria = RestUtils.parseSortQueryParameter(optSort.get());
        Collections.sort(filteredAcls, new Comparator<ManagedAcl>() {

            @Override
            public int compare(ManagedAcl acl1, ManagedAcl acl2) {
                for (SortCriterion criterion : sortCriteria) {
                    Order order = criterion.getOrder();
                    switch(criterion.getFieldName()) {
                        case "name":
                            if (order.equals(Order.Descending))
                                return ObjectUtils.compare(acl2.getName(), acl1.getName());
                            return ObjectUtils.compare(acl1.getName(), acl2.getName());
                        default:
                            logger.info("Unkown sort type: {}", criterion.getFieldName());
                            return 0;
                    }
                }
                return 0;
            }
        });
    }
    // Apply Limit and offset
    List<JValue> aclJSON = Stream.$(filteredAcls).drop(offset).apply(limit > 0 ? StreamOp.<ManagedAcl>id().take(limit) : StreamOp.<ManagedAcl>id()).map(fullManagedAcl).toList();
    return okJsonList(aclJSON, offset, limit, total);
}
Also used : Order(org.opencastproject.matterhorn.search.SearchQuery.Order) ManagedAcl(org.opencastproject.authorization.xacml.manager.api.ManagedAcl) ArrayList(java.util.ArrayList) 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 3 with SortCriterion

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

the class CaptureAgentsEndpoint method getAgents.

@GET
@Produces({ MediaType.APPLICATION_JSON })
@Path("agents.json")
@RestQuery(name = "getAgents", description = "Return all of the known capture agents 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 = "100", description = "The maximum number of items to return per page.", isRequired = false, name = "limit", type = RestParameter.Type.STRING), @RestParameter(defaultValue = "0", description = "The page number.", isRequired = false, name = "offset", type = RestParameter.Type.STRING), @RestParameter(defaultValue = "false", description = "Define if the inputs should or not returned with the capture agent.", isRequired = false, name = "inputs", type = RestParameter.Type.BOOLEAN), @RestParameter(name = "sort", isRequired = false, description = "The sort order. May include any of the following: STATUS, NAME OR LAST_UPDATED.  Add '_DESC' to reverse the sort order (e.g. STATUS_DESC).", type = STRING) }, reponses = { @RestResponse(description = "An XML representation of the agent capabilities", responseCode = HttpServletResponse.SC_OK) }, returnDescription = "")
public Response getAgents(@QueryParam("limit") int limit, @QueryParam("offset") int offset, @QueryParam("inputs") boolean inputs, @QueryParam("filter") String filter, @QueryParam("sort") String sort) {
    Option<String> filterName = Option.none();
    Option<String> filterStatus = Option.none();
    Option<Long> filterLastUpdated = Option.none();
    Option<String> filterText = Option.none();
    Option<String> optSort = Option.option(trimToNull(sort));
    Map<String, String> filters = RestUtils.parseFilter(filter);
    for (String name : filters.keySet()) {
        if (AgentsListQuery.FILTER_NAME_NAME.equals(name))
            filterName = Option.some(filters.get(name));
        if (AgentsListQuery.FILTER_STATUS_NAME.equals(name))
            filterStatus = Option.some(filters.get(name));
        if (AgentsListQuery.FILTER_LAST_UPDATED.equals(name)) {
            try {
                filterLastUpdated = Option.some(Long.parseLong(filters.get(name)));
            } catch (NumberFormatException e) {
                logger.info("Unable to parse long {}", filters.get(name));
                return Response.status(Status.BAD_REQUEST).build();
            }
        }
        if (AgentsListQuery.FILTER_TEXT_NAME.equals(name) && StringUtils.isNotBlank(filters.get(name)))
            filterText = Option.some(filters.get(name));
    }
    // Filter agents by filter criteria
    List<Agent> filteredAgents = new ArrayList<>();
    for (Entry<String, Agent> entry : service.getKnownAgents().entrySet()) {
        Agent agent = entry.getValue();
        // Filter list
        if ((filterName.isSome() && !filterName.get().equals(agent.getName())) || (filterStatus.isSome() && !filterStatus.get().equals(agent.getState())) || (filterLastUpdated.isSome() && filterLastUpdated.get() != agent.getLastHeardFrom()) || (filterText.isSome() && !TextFilter.match(filterText.get(), agent.getName(), agent.getState())))
            continue;
        filteredAgents.add(agent);
    }
    int total = filteredAgents.size();
    // Sort by status, name or last updated date
    if (optSort.isSome()) {
        final Set<SortCriterion> sortCriteria = RestUtils.parseSortQueryParameter(optSort.get());
        Collections.sort(filteredAgents, new Comparator<Agent>() {

            @Override
            public int compare(Agent agent1, Agent agent2) {
                for (SortCriterion criterion : sortCriteria) {
                    Order order = criterion.getOrder();
                    switch(criterion.getFieldName()) {
                        case "status":
                            if (order.equals(Order.Descending))
                                return agent2.getState().compareTo(agent1.getState());
                            return agent1.getState().compareTo(agent2.getState());
                        case "name":
                            if (order.equals(Order.Descending))
                                return agent2.getName().compareTo(agent1.getName());
                            return agent1.getName().compareTo(agent2.getName());
                        case "updated":
                            if (order.equals(Order.Descending))
                                return agent2.getLastHeardFrom().compareTo(agent1.getLastHeardFrom());
                            return agent1.getLastHeardFrom().compareTo(agent2.getLastHeardFrom());
                        default:
                            logger.info("Unknown sort type: {}", criterion.getFieldName());
                            return 0;
                    }
                }
                return 0;
            }
        });
    }
    // Apply Limit and offset
    filteredAgents = new SmartIterator<Agent>(limit, offset).applyLimitAndOffset(filteredAgents);
    // Run through and build a map of updates (rather than states)
    List<JValue> agentsJSON = new ArrayList<>();
    for (Agent agent : filteredAgents) {
        agentsJSON.add(generateJsonAgent(agent, /* Option.option(room), blacklist, */
        inputs, false));
    }
    return okJsonList(agentsJSON, offset, limit, total);
}
Also used : Order(org.opencastproject.matterhorn.search.SearchQuery.Order) Agent(org.opencastproject.capture.admin.api.Agent) SmartIterator(org.opencastproject.util.SmartIterator) ArrayList(java.util.ArrayList) 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 4 with SortCriterion

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

the class GroupsEndpoint method getGroups.

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("groups.json")
@RestQuery(name = "allgroupsasjson", description = "Returns a list of groups", returnDescription = "List of groups for the current user's organization as JSON.", restParameters = { @RestParameter(name = "filter", isRequired = false, type = STRING, description = "Filter used for the query, formatted like: 'filter1:value1,filter2:value2'"), @RestParameter(name = "sort", isRequired = false, type = STRING, description = "The sort order. May include any of the following: NAME, DESCRIPTION, ROLE. " + "Add '_DESC' to reverse the sort order (e.g. NAME_DESC)."), @RestParameter(name = "limit", isRequired = false, type = INTEGER, defaultValue = "100", description = "The maximum number of items to return per page."), @RestParameter(name = "offset", isRequired = false, type = INTEGER, defaultValue = "0", description = "The page number.") }, reponses = { @RestResponse(responseCode = SC_OK, description = "The groups.") })
public Response getGroups(@QueryParam("filter") String filter, @QueryParam("sort") String sort, @QueryParam("offset") int offset, @QueryParam("limit") int limit) throws IOException {
    GroupSearchQuery query = new GroupSearchQuery(securityService.getOrganization().getId(), securityService.getUser());
    Opt<String> optSort = Opt.nul(trimToNull(sort));
    Option<Integer> optOffset = Option.option(offset);
    Option<Integer> optLimit = Option.option(limit);
    // 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 (GroupsListQuery.FILTER_NAME_NAME.equals(name)) {
            query.withName(filters.get(name));
        } else if (GroupsListQuery.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 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());
    SearchResult<Group> results;
    try {
        results = searchIndex.getByQuery(query);
    } catch (SearchIndexException e) {
        logger.error("The External Search Index was not able to get the groups list.", e);
        return RestUtil.R.serverError();
    }
    List<JValue> groupsJSON = new ArrayList<>();
    for (SearchResultItem<Group> item : results.getItems()) {
        Group group = item.getSource();
        List<Field> fields = new ArrayList<>();
        fields.add(f("id", v(group.getIdentifier())));
        fields.add(f("name", v(group.getName(), Jsons.BLANK)));
        fields.add(f("description", v(group.getDescription(), Jsons.BLANK)));
        fields.add(f("role", v(group.getRole())));
        fields.add(f("users", membersToJSON(group.getMembers())));
        groupsJSON.add(obj(fields));
    }
    return okJsonList(groupsJSON, offset, limit, results.getHitCount());
}
Also used : Group(org.opencastproject.index.service.impl.index.group.Group) WebApplicationException(javax.ws.rs.WebApplicationException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) ArrayList(java.util.ArrayList) GroupSearchQuery(org.opencastproject.index.service.impl.index.group.GroupSearchQuery) Field(com.entwinemedia.fn.data.json.Field) 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 5 with SortCriterion

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

the class ServicesEndpoint method getServices.

@GET
@Path("services.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(description = "Returns the list of services", name = "services", restParameters = { @RestParameter(name = "limit", description = "The maximum number of items to return per page", isRequired = false, type = RestParameter.Type.INTEGER), @RestParameter(name = "offset", description = "The offset", isRequired = false, type = RestParameter.Type.INTEGER), @RestParameter(name = "filter", description = "Filter results by name, host, actions, status or free text query", isRequired = false, type = STRING), @RestParameter(name = "sort", description = "The sort order.  May include any " + "of the following: host, name, running, queued, completed,  meanRunTime, meanQueueTime, " + "status. The sort suffix must be :asc for ascending sort order and :desc for descending.", isRequired = false, type = STRING) }, reponses = { @RestResponse(description = "Returns the list of services from Opencast", responseCode = HttpServletResponse.SC_OK) }, returnDescription = "The list of services")
public Response getServices(@QueryParam("limit") final int limit, @QueryParam("offset") final int offset, @QueryParam("filter") String filter, @QueryParam("sort") String sort) throws Exception {
    Option<String> sortOpt = Option.option(StringUtils.trimToNull(sort));
    ServicesListQuery query = new ServicesListQuery();
    EndpointUtil.addRequestFiltersToQuery(filter, query);
    String fName = null;
    if (query.getName().isSome())
        fName = StringUtils.trimToNull(query.getName().get());
    String fHostname = null;
    if (query.getHostname().isSome())
        fHostname = StringUtils.trimToNull(query.getHostname().get());
    String fStatus = null;
    if (query.getStatus().isSome())
        fStatus = StringUtils.trimToNull(query.getStatus().get());
    String fFreeText = null;
    if (query.getFreeText().isSome())
        fFreeText = StringUtils.trimToNull(query.getFreeText().get());
    List<Service> services = new ArrayList<Service>();
    for (ServiceStatistics stats : serviceRegistry.getServiceStatistics()) {
        Service service = new Service(stats);
        if (fName != null && !StringUtils.equalsIgnoreCase(service.getName(), fName))
            continue;
        if (fHostname != null && !StringUtils.equalsIgnoreCase(service.getHost(), fHostname))
            continue;
        if (fStatus != null && !StringUtils.equalsIgnoreCase(service.getStatus().toString(), fStatus))
            continue;
        if (query.getActions().isSome()) {
            ServiceState serviceState = service.getStatus();
            if (query.getActions().get()) {
                if (ServiceState.NORMAL == serviceState)
                    continue;
            } else {
                if (ServiceState.NORMAL != serviceState)
                    continue;
            }
        }
        if (fFreeText != null && !StringUtils.containsIgnoreCase(service.getName(), fFreeText) && !StringUtils.containsIgnoreCase(service.getHost(), fFreeText) && !StringUtils.containsIgnoreCase(service.getStatus().toString(), fFreeText))
            continue;
        services.add(service);
    }
    int total = services.size();
    if (sortOpt.isSome()) {
        Set<SortCriterion> sortCriteria = RestUtils.parseSortQueryParameter(sortOpt.get());
        if (!sortCriteria.isEmpty()) {
            try {
                SortCriterion sortCriterion = sortCriteria.iterator().next();
                Collections.sort(services, new ServiceStatisticsComparator(sortCriterion.getFieldName(), sortCriterion.getOrder() == SearchQuery.Order.Ascending));
            } catch (Exception ex) {
                logger.warn("Failed to sort services collection.", ex);
            }
        }
    }
    List<JValue> jsonList = new ArrayList<JValue>();
    for (Service s : new SmartIterator<Service>(limit, offset).applyLimitAndOffset(services)) {
        jsonList.add(s.toJSON());
    }
    return RestUtils.okJsonList(jsonList, offset, limit, total);
}
Also used : ServiceState(org.opencastproject.serviceregistry.api.ServiceState) ArrayList(java.util.ArrayList) RestService(org.opencastproject.util.doc.rest.RestService) ServiceStatistics(org.opencastproject.serviceregistry.api.ServiceStatistics) SortCriterion(org.opencastproject.matterhorn.search.SortCriterion) JValue(com.entwinemedia.fn.data.json.JValue) ServicesListQuery(org.opencastproject.index.service.resources.list.query.ServicesListQuery) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

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