Search in sources :

Example 1 with Group

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

the class AbstractSearchIndex method getByQuery.

/**
 * @param query
 *          The query to use to retrieve the groups that match the query
 * @return {@link SearchResult} collection of {@link Group} from a query.
 * @throws SearchIndexException
 *           Thrown if there is an error getting the results.
 */
public SearchResult<Group> getByQuery(GroupSearchQuery query) throws SearchIndexException {
    logger.debug("Searching index using group query '{}'", query);
    // Create the request builder
    SearchRequestBuilder requestBuilder = getSearchRequestBuilder(query, new GroupQueryBuilder(query));
    try {
        return executeQuery(query, requestBuilder, new Fn<SearchMetadataCollection, Group>() {

            @Override
            public Group apply(SearchMetadataCollection metadata) {
                try {
                    return GroupIndexUtils.toGroup(metadata);
                } catch (IOException e) {
                    return chuck(e);
                }
            }
        });
    } catch (Throwable t) {
        throw new SearchIndexException("Error querying series index", t);
    }
}
Also used : Group(org.opencastproject.index.service.impl.index.group.Group) SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder) SearchMetadataCollection(org.opencastproject.matterhorn.search.impl.SearchMetadataCollection) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) IOException(java.io.IOException) GroupQueryBuilder(org.opencastproject.index.service.impl.index.group.GroupQueryBuilder)

Example 2 with Group

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

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

the class GroupsEndpoint method getGroup.

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
@RestQuery(name = "getGroup", description = "Get a single group", returnDescription = "Return the status codes", pathParameters = { @RestParameter(name = "id", description = "The group identifier", isRequired = true, type = STRING) }, reponses = { @RestResponse(responseCode = SC_OK, description = "Group found and returned as JSON"), @RestResponse(responseCode = SC_NOT_FOUND, description = "Group not found") })
public Response getGroup(@PathParam("id") String groupId) throws NotFoundException, SearchIndexException {
    Opt<Group> groupOpt = indexService.getGroup(groupId, searchIndex);
    if (groupOpt.isNone())
        throw new NotFoundException("Group " + groupId + " does not exist.");
    Group group = groupOpt.get();
    return RestUtils.okJson(obj(f("id", v(group.getIdentifier())), f("name", v(group.getName(), Jsons.BLANK)), f("description", v(group.getDescription(), Jsons.BLANK)), f("role", v(group.getRole(), Jsons.BLANK)), f("roles", rolesToJSON(group.getRoles())), f("users", membersToJSON(group.getMembers()))));
}
Also used : Group(org.opencastproject.index.service.impl.index.group.Group) NotFoundException(org.opencastproject.util.NotFoundException) 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 Group

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

the class GroupsEndpoint method addGroupMember.

@POST
@Path("{groupId}/members")
@Produces({ "application/json", "application/v1.0.0+json" })
@RestQuery(name = "addgroupmember", description = "Adds a member to a group.", returnDescription = "", pathParameters = { @RestParameter(name = "groupId", description = "The group id", isRequired = true, type = STRING) }, restParameters = { @RestParameter(name = "member", description = "Member Name", isRequired = true, type = STRING) }, reponses = { @RestResponse(description = "The member was already member of the group.", responseCode = HttpServletResponse.SC_OK), @RestResponse(description = "The member has been added.", responseCode = HttpServletResponse.SC_NO_CONTENT), @RestResponse(description = "The specified group does not exist.", responseCode = HttpServletResponse.SC_NOT_FOUND) })
public Response addGroupMember(@HeaderParam("Accept") String acceptHeader, @PathParam("groupId") String id, @FormParam("member") String member) {
    try {
        Opt<Group> groupOpt = indexService.getGroup(id, externalIndex);
        if (groupOpt.isSome()) {
            Group group = groupOpt.get();
            Set<String> members = group.getMembers();
            if (!members.contains(member)) {
                group.addMember(member);
                return indexService.updateGroup(group.getIdentifier(), group.getName(), group.getDescription(), StringUtils.join(group.getRoles(), ","), StringUtils.join(group.getMembers(), ","));
            } else {
                return ApiResponses.Json.ok(ApiVersion.VERSION_1_0_0, "Member is already member of group");
            }
        } else {
            return ApiResponses.notFound("Cannot find group with id '%s'.", id);
        }
    } catch (SearchIndexException e) {
        logger.warn("The external search index was not able to retrieve the group with id '%s', reason: ", getStackTrace(e));
        return ApiResponses.serverError("Could not retrieve group with id '%s', reason: '%s'", id, getMessage(e));
    } catch (NotFoundException e) {
        logger.warn("The external search index was not able to update the group with id {}, ", getStackTrace(e));
        return ApiResponses.serverError("Could not update group with id '%s', reason: '%s'", id, getMessage(e));
    }
}
Also used : Group(org.opencastproject.index.service.impl.index.group.Group) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) NotFoundException(org.opencastproject.util.NotFoundException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 5 with Group

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

the class GroupsEndpoint method removeGroupMember.

@DELETE
@Path("{groupId}/members/{memberId}")
@Produces({ "application/json", "application/v1.0.0+json" })
@RestQuery(name = "removegroupmember", description = "Removes a member from a group", returnDescription = "", pathParameters = { @RestParameter(name = "groupId", description = "The group id", isRequired = true, type = STRING), @RestParameter(name = "memberId", description = "The member id", isRequired = true, type = STRING) }, reponses = { @RestResponse(description = "The member has been removed.", responseCode = HttpServletResponse.SC_NO_CONTENT), @RestResponse(description = "The specified group or member does not exist.", responseCode = HttpServletResponse.SC_NOT_FOUND) })
public Response removeGroupMember(@HeaderParam("Accept") String acceptHeader, @PathParam("groupId") String id, @PathParam("memberId") String memberId) {
    try {
        Opt<Group> groupOpt = indexService.getGroup(id, externalIndex);
        if (groupOpt.isSome()) {
            Group group = groupOpt.get();
            Set<String> members = group.getMembers();
            if (members.contains(memberId)) {
                members.remove(memberId);
                group.setMembers(members);
                return indexService.updateGroup(group.getIdentifier(), group.getName(), group.getDescription(), StringUtils.join(group.getRoles(), ","), StringUtils.join(group.getMembers(), ","));
            } else {
                return ApiResponses.notFound("Cannot find member '%s' in group '%s'.", memberId, id);
            }
        } else {
            return ApiResponses.notFound("Cannot find group with id '%s'.", id);
        }
    } catch (SearchIndexException e) {
        logger.warn("The external search index was not able to retrieve the group with id {}, ", getStackTrace(e));
        return ApiResponses.serverError("Could not retrieve groups, reason: '%s'", getMessage(e));
    } catch (NotFoundException e) {
        logger.warn("The external search index was not able to update the group with id {}, ", getStackTrace(e));
        return ApiResponses.serverError("Could not update group with id '%s', reason: '%s'", id, getMessage(e));
    }
}
Also used : Group(org.opencastproject.index.service.impl.index.group.Group) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) NotFoundException(org.opencastproject.util.NotFoundException) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) Produces(javax.ws.rs.Produces) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Aggregations

Group (org.opencastproject.index.service.impl.index.group.Group)6 SearchIndexException (org.opencastproject.matterhorn.search.SearchIndexException)5 Path (javax.ws.rs.Path)4 Produces (javax.ws.rs.Produces)4 RestQuery (org.opencastproject.util.doc.rest.RestQuery)4 NotFoundException (org.opencastproject.util.NotFoundException)3 GET (javax.ws.rs.GET)2 Field (com.entwinemedia.fn.data.json.Field)1 JValue (com.entwinemedia.fn.data.json.JValue)1 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 HashSet (java.util.HashSet)1 DELETE (javax.ws.rs.DELETE)1 POST (javax.ws.rs.POST)1 WebApplicationException (javax.ws.rs.WebApplicationException)1 SearchRequestBuilder (org.elasticsearch.action.search.SearchRequestBuilder)1 GroupQueryBuilder (org.opencastproject.index.service.impl.index.group.GroupQueryBuilder)1 GroupSearchQuery (org.opencastproject.index.service.impl.index.group.GroupSearchQuery)1 SortCriterion (org.opencastproject.matterhorn.search.SortCriterion)1 SearchMetadataCollection (org.opencastproject.matterhorn.search.impl.SearchMetadataCollection)1