Search in sources :

Example 1 with Order

use of org.opencastproject.matterhorn.search.SearchQuery.Order 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 2 with Order

use of org.opencastproject.matterhorn.search.SearchQuery.Order 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 3 with Order

use of org.opencastproject.matterhorn.search.SearchQuery.Order in project opencast by opencast.

the class UsersEndpoint method getUsers.

@GET
@Path("users.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "allusers", description = "Returns a list of users", returnDescription = "Returns a JSON representation of the list of user accounts", 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: STATUS, NAME OR LAST_UPDATED.  Add '_DESC' to reverse the sort order (e.g. STATUS_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 user accounts.") })
public Response getUsers(@QueryParam("filter") String filter, @QueryParam("sort") String sort, @QueryParam("limit") int limit, @QueryParam("offset") int offset) throws IOException {
    if (limit < 1)
        limit = 100;
    Option<String> optSort = Option.option(trimToNull(sort));
    Option<String> filterName = Option.none();
    Option<String> filterRole = Option.none();
    Option<String> filterProvider = 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 (UsersListQuery.FILTER_NAME_NAME.equals(name)) {
            filterName = Option.some(value);
        } else if (UsersListQuery.FILTER_ROLE_NAME.equals(name)) {
            filterRole = Option.some(value);
        } else if (UsersListQuery.FILTER_PROVIDER_NAME.equals(name)) {
            filterProvider = Option.some(value);
        } else if ((UsersListQuery.FILTER_TEXT_NAME.equals(name)) && (StringUtils.isNotBlank(value))) {
            filterText = Option.some(value);
        }
    }
    // Filter users by filter criteria
    List<User> filteredUsers = new ArrayList<>();
    for (Iterator<User> i = userDirectoryService.getUsers(); i.hasNext(); ) {
        User user = i.next();
        // Filter list
        if (filterName.isSome() && !filterName.get().equals(user.getName()) || (filterRole.isSome() && !Stream.$(user.getRoles()).map(getRoleName).toSet().contains(filterRole.get())) || (filterProvider.isSome() && !filterProvider.get().equals(user.getProvider())) || (filterText.isSome() && !TextFilter.match(filterText.get(), user.getUsername(), user.getName(), user.getEmail(), user.getProvider()) && !TextFilter.match(filterText.get(), Stream.$(user.getRoles()).map(getRoleName).mkString(" ")))) {
            continue;
        }
        filteredUsers.add(user);
    }
    int total = filteredUsers.size();
    // Sort by name, description or role
    if (optSort.isSome()) {
        final Set<SortCriterion> sortCriteria = RestUtils.parseSortQueryParameter(optSort.get());
        Collections.sort(filteredUsers, new Comparator<User>() {

            @Override
            public int compare(User user1, User user2) {
                for (SortCriterion criterion : sortCriteria) {
                    Order order = criterion.getOrder();
                    switch(criterion.getFieldName()) {
                        case "name":
                            if (order.equals(Order.Descending))
                                return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user2.getName()), trimToEmpty(user1.getName()));
                            return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user1.getName()), trimToEmpty(user2.getName()));
                        case "username":
                            if (order.equals(Order.Descending))
                                return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user2.getUsername()), trimToEmpty(user1.getUsername()));
                            return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user1.getUsername()), trimToEmpty(user2.getUsername()));
                        case "email":
                            if (order.equals(Order.Descending))
                                return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user2.getEmail()), trimToEmpty(user1.getEmail()));
                            return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user1.getEmail()), trimToEmpty(user2.getEmail()));
                        case "roles":
                            String roles1 = Stream.$(user1.getRoles()).map(getRoleName).sort(sortByName).mkString(",");
                            String roles2 = Stream.$(user2.getRoles()).map(getRoleName).sort(sortByName).mkString(",");
                            if (order.equals(Order.Descending))
                                return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(roles2), trimToEmpty(roles1));
                            return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(roles1), trimToEmpty(roles2));
                        case "provider":
                            if (order.equals(Order.Descending))
                                return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user2.getProvider()), trimToEmpty(user1.getProvider()));
                            return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user1.getProvider()), trimToEmpty(user2.getProvider()));
                        default:
                            logger.info("Unkown sort type: {}", criterion.getFieldName());
                            return 0;
                    }
                }
                return 0;
            }
        });
    }
    // Apply Limit and offset
    filteredUsers = new SmartIterator<User>(limit, offset).applyLimitAndOffset(filteredUsers);
    List<JValue> usersJSON = new ArrayList<>();
    for (User user : filteredUsers) {
        usersJSON.add(generateJsonUser(user));
    }
    return okJsonList(usersJSON, offset, limit, total);
}
Also used : Order(org.opencastproject.matterhorn.search.SearchQuery.Order) JpaUser(org.opencastproject.security.impl.jpa.JpaUser) User(org.opencastproject.security.api.User) 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 Order

use of org.opencastproject.matterhorn.search.SearchQuery.Order in project opencast by opencast.

the class AbstractElasticsearchIndex method getSearchRequestBuilder.

/**
 * Creates a request builder for a search query based on the properties known by the search query.
 * <p>
 * Once this query builder has been created, support for ordering needs to be configured as needed.
 *
 * @param query
 *          the search query
 * @return the request builder
 */
protected SearchRequestBuilder getSearchRequestBuilder(SearchQuery query, QueryBuilder queryBuilder) {
    SearchRequestBuilder requestBuilder = new SearchRequestBuilder(getSearchClient());
    requestBuilder.setIndices(getIndexName());
    requestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
    requestBuilder.setPreference("_local");
    // Create the actual search query
    requestBuilder.setQuery(queryBuilder);
    logger.debug("Searching for {}", requestBuilder.toString());
    // Make sure all fields are being returned
    if (query.getFields().length > 0) {
        requestBuilder.addFields(query.getFields());
    } else {
        requestBuilder.addField("*");
    }
    // Types
    requestBuilder.setTypes(query.getTypes());
    // Pagination
    if (query.getOffset() >= 0)
        requestBuilder.setFrom(query.getOffset());
    int limit = ELASTICSEARCH_INDEX_MAX_RESULT_WINDOW;
    if (query.getLimit() > 0) {
        // see https://www.elastic.co/guide/en/elasticsearch/reference/2.1/index-modules.html
        if (query.getOffset() > 0 && (long) query.getOffset() + (long) query.getLimit() > ELASTICSEARCH_INDEX_MAX_RESULT_WINDOW)
            limit = ELASTICSEARCH_INDEX_MAX_RESULT_WINDOW - query.getOffset();
        else
            limit = query.getLimit();
    }
    requestBuilder.setSize(limit);
    // Sort orders
    Map<String, Order> sortCriteria = query.getSortOrders();
    for (Entry<String, Order> sortCriterion : sortCriteria.entrySet()) {
        switch(sortCriterion.getValue()) {
            case Ascending:
                requestBuilder.addSort(sortCriterion.getKey(), SortOrder.ASC);
                break;
            case Descending:
                requestBuilder.addSort(sortCriterion.getKey(), SortOrder.DESC);
                break;
            default:
                break;
        }
    }
    return requestBuilder;
}
Also used : SortOrder(org.elasticsearch.search.sort.SortOrder) Order(org.opencastproject.matterhorn.search.SearchQuery.Order) SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder)

Aggregations

Order (org.opencastproject.matterhorn.search.SearchQuery.Order)4 JValue (com.entwinemedia.fn.data.json.JValue)3 ArrayList (java.util.ArrayList)3 GET (javax.ws.rs.GET)3 Path (javax.ws.rs.Path)3 Produces (javax.ws.rs.Produces)3 SortCriterion (org.opencastproject.matterhorn.search.SortCriterion)3 RestQuery (org.opencastproject.util.doc.rest.RestQuery)3 SmartIterator (org.opencastproject.util.SmartIterator)2 SearchRequestBuilder (org.elasticsearch.action.search.SearchRequestBuilder)1 SortOrder (org.elasticsearch.search.sort.SortOrder)1 ManagedAcl (org.opencastproject.authorization.xacml.manager.api.ManagedAcl)1 Agent (org.opencastproject.capture.admin.api.Agent)1 User (org.opencastproject.security.api.User)1 JpaUser (org.opencastproject.security.impl.jpa.JpaUser)1