Search in sources :

Example 26 with PaginatedList

use of org.graylog2.database.PaginatedList in project graylog2-server by Graylog2.

the class UsersResource method getPage.

@GET
@Timed
@Path("/paginated")
@ApiOperation(value = "Get paginated list of users")
@RequiresPermissions(RestPermissions.USERS_LIST)
@Produces(MediaType.APPLICATION_JSON)
public PaginatedResponse<UserOverviewDTO> getPage(@ApiParam(name = "page") @QueryParam("page") @DefaultValue("1") int page, @ApiParam(name = "per_page") @QueryParam("per_page") @DefaultValue("50") int perPage, @ApiParam(name = "query") @QueryParam("query") @DefaultValue("") String query, @ApiParam(name = "sort", value = "The field to sort the result on", required = true, allowableValues = "title,description") @DefaultValue(UserOverviewDTO.FIELD_FULL_NAME) @QueryParam("sort") String sort, @ApiParam(name = "order", value = "The sort direction", allowableValues = "asc, desc") @DefaultValue("asc") @QueryParam("order") String order) {
    SearchQuery searchQuery;
    final AllUserSessions sessions = AllUserSessions.create(sessionService);
    try {
        searchQuery = searchQueryParser.parse(query);
    } catch (IllegalArgumentException e) {
        throw new BadRequestException("Invalid argument in search query: " + e.getMessage());
    }
    final PaginatedList<UserOverviewDTO> result = paginatedUserService.findPaginated(searchQuery, page, perPage, sort, order);
    final Set<String> allRoleIds = result.stream().flatMap(userDTO -> {
        if (userDTO.roles() != null) {
            return userDTO.roles().stream();
        }
        return Stream.empty();
    }).collect(Collectors.toSet());
    Map<String, String> roleNameMap;
    try {
        roleNameMap = getRoleNameMap(allRoleIds);
    } catch (org.graylog2.database.NotFoundException e) {
        throw new NotFoundException("Couldn't find roles: " + e.getMessage());
    }
    final UserOverviewDTO adminUser = getAdminUserDTO(sessions);
    List<UserOverviewDTO> users = result.stream().map(userDTO -> {
        UserOverviewDTO.Builder builder = userDTO.toBuilder().fillSession(sessions.forUser(userDTO));
        if (userDTO.roles() != null) {
            builder.roles(userDTO.roles().stream().map(roleNameMap::get).collect(Collectors.toSet()));
        }
        return builder.build();
    }).collect(Collectors.toList());
    final PaginatedList<UserOverviewDTO> userOverviewDTOS = new PaginatedList<>(users, result.pagination().total(), result.pagination().page(), result.pagination().perPage());
    return PaginatedResponse.create("users", userOverviewDTOS, query, Collections.singletonMap("admin_user", adminUser));
}
Also used : SearchQuery(org.graylog2.search.SearchQuery) USERS_TOKENCREATE(org.graylog2.shared.security.RestPermissions.USERS_TOKENCREATE) StringUtils(org.apache.commons.lang.StringUtils) DateTimeZone(org.joda.time.DateTimeZone) UserList(org.graylog2.rest.models.users.responses.UserList) USERS_PERMISSIONSEDIT(org.graylog2.shared.security.RestPermissions.USERS_PERMISSIONSEDIT) Produces(javax.ws.rs.Produces) UserManagementService(org.graylog2.shared.users.UserManagementService) USERS_TOKENLIST(org.graylog2.shared.security.RestPermissions.USERS_TOKENLIST) Date(java.util.Date) UserContext(org.graylog.security.UserContext) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) ApiParam(io.swagger.annotations.ApiParam) WildcardPermission(org.apache.shiro.authz.permission.WildcardPermission) Valid(javax.validation.Valid) ApiOperation(io.swagger.annotations.ApiOperation) PaginatedList(org.graylog2.database.PaginatedList) MongoDBSessionService(org.graylog2.security.MongoDBSessionService) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) SearchQueryField(org.graylog2.search.SearchQueryField) AccessTokenService(org.graylog2.security.AccessTokenService) USERS_ROLESEDIT(org.graylog2.shared.security.RestPermissions.USERS_ROLESEDIT) CreateUserRequest(org.graylog2.rest.models.users.requests.CreateUserRequest) Locale(java.util.Locale) Map(java.util.Map) DefaultValue(javax.ws.rs.DefaultValue) BadRequestException(javax.ws.rs.BadRequestException) URI(java.net.URI) ChangePasswordRequest(org.graylog2.rest.models.users.requests.ChangePasswordRequest) AccessToken(org.graylog2.security.AccessToken) DELETE(javax.ws.rs.DELETE) Token(org.graylog2.rest.models.users.responses.Token) Context(javax.ws.rs.core.Context) ImmutableMap(com.google.common.collect.ImmutableMap) TokenSummary(org.graylog2.rest.models.users.responses.TokenSummary) Collection(java.util.Collection) Set(java.util.Set) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) TokenList(org.graylog2.rest.models.users.responses.TokenList) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) PaginatedUserService(org.graylog2.users.PaginatedUserService) NotFoundException(javax.ws.rs.NotFoundException) Timed(com.codahale.metrics.annotation.Timed) List(java.util.List) Stream(java.util.stream.Stream) Response(javax.ws.rs.core.Response) AuditEventTypes(org.graylog2.audit.AuditEventTypes) UserSummary(org.graylog2.rest.models.users.responses.UserSummary) Startpage(org.graylog2.rest.models.users.requests.Startpage) Optional(java.util.Optional) RequiresAuthentication(org.apache.shiro.authz.annotation.RequiresAuthentication) GRNPermission(org.graylog.security.permissions.GRNPermission) USERS_TOKENREMOVE(org.graylog2.shared.security.RestPermissions.USERS_TOKENREMOVE) UserOverviewDTO(org.graylog2.users.UserOverviewDTO) Iterables(com.google.common.collect.Iterables) PathParam(javax.ws.rs.PathParam) NotBlank(javax.validation.constraints.NotBlank) SearchQueryParser(org.graylog2.search.SearchQueryParser) GET(javax.ws.rs.GET) RoleService(org.graylog2.users.RoleService) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) HashMap(java.util.HashMap) ApiResponses(io.swagger.annotations.ApiResponses) Roles(org.graylog2.shared.users.Roles) ArrayList(java.util.ArrayList) MongoDbSession(org.graylog2.security.MongoDbSession) Inject(javax.inject.Inject) RequiresPermissions(org.apache.shiro.authz.annotation.RequiresPermissions) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) AuditEvent(org.graylog2.audit.jersey.AuditEvent) Api(io.swagger.annotations.Api) SearchQuery(org.graylog2.search.SearchQuery) Nullable(javax.annotation.Nullable) PermissionEditRequest(org.graylog2.rest.models.users.requests.PermissionEditRequest) Logger(org.slf4j.Logger) POST(javax.ws.rs.POST) ChangeUserRequest(org.graylog2.shared.users.ChangeUserRequest) ForbiddenException(javax.ws.rs.ForbiddenException) RestResource(org.graylog2.shared.rest.resources.RestResource) Collectors.maxBy(java.util.stream.Collectors.maxBy) UpdateUserPreferences(org.graylog2.rest.models.users.requests.UpdateUserPreferences) ApiResponse(io.swagger.annotations.ApiResponse) ValidationException(org.graylog2.plugin.database.ValidationException) RestPermissions(org.graylog2.shared.security.RestPermissions) USERS_EDIT(org.graylog2.shared.security.RestPermissions.USERS_EDIT) PUT(javax.ws.rs.PUT) PaginatedResponse(org.graylog2.rest.models.PaginatedResponse) User(org.graylog2.plugin.database.users.User) Role(org.graylog2.shared.users.Role) Comparator(java.util.Comparator) Collections(java.util.Collections) NotFoundException(javax.ws.rs.NotFoundException) UserOverviewDTO(org.graylog2.users.UserOverviewDTO) BadRequestException(javax.ws.rs.BadRequestException) PaginatedList(org.graylog2.database.PaginatedList) Path(javax.ws.rs.Path) RequiresPermissions(org.apache.shiro.authz.annotation.RequiresPermissions) Produces(javax.ws.rs.Produces) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation)

Example 27 with PaginatedList

use of org.graylog2.database.PaginatedList in project graylog2-server by Graylog2.

the class LookupTableResource method tables.

@GET
@Path("tables")
@ApiOperation(value = "List configured lookup tables")
@RequiresPermissions(RestPermissions.LOOKUP_TABLES_READ)
public LookupTablePage tables(@ApiParam(name = "page") @QueryParam("page") @DefaultValue("1") int page, @ApiParam(name = "per_page") @QueryParam("per_page") @DefaultValue("50") int perPage, @ApiParam(name = "sort", value = "The field to sort the result on", required = true, allowableValues = "title,description,name,id") @DefaultValue(LookupTableDto.FIELD_TITLE) @QueryParam("sort") String sort, @ApiParam(name = "order", value = "The sort direction", allowableValues = "asc, desc") @DefaultValue("desc") @QueryParam("order") String order, @ApiParam(name = "query") @QueryParam("query") String query, @ApiParam(name = "resolve") @QueryParam("resolve") @DefaultValue("false") boolean resolveObjects) {
    if (!LUT_ALLOWABLE_SORT_FIELDS.contains(sort.toLowerCase(Locale.ENGLISH))) {
        sort = LookupTableDto.FIELD_TITLE;
    }
    DBSort.SortBuilder sortBuilder;
    if ("desc".equalsIgnoreCase(order)) {
        sortBuilder = DBSort.desc(sort);
    } else {
        sortBuilder = DBSort.asc(sort);
    }
    try {
        final SearchQuery searchQuery = lutSearchQueryParser.parse(query);
        final DBQuery.Query dbQuery = searchQuery.toDBQuery();
        PaginatedList<LookupTableDto> paginated = dbTableService.findPaginated(dbQuery, sortBuilder, page, perPage);
        ImmutableSet.Builder<CacheApi> caches = ImmutableSet.builder();
        ImmutableSet.Builder<DataAdapterApi> dataAdapters = ImmutableSet.builder();
        if (resolveObjects) {
            ImmutableSet.Builder<String> cacheIds = ImmutableSet.builder();
            ImmutableSet.Builder<String> dataAdapterIds = ImmutableSet.builder();
            paginated.forEach(dto -> {
                cacheIds.add(dto.cacheId());
                dataAdapterIds.add(dto.dataAdapterId());
            });
            dbCacheService.findByIds(cacheIds.build()).forEach(cacheDto -> caches.add(CacheApi.fromDto(cacheDto)));
            dbDataAdapterService.findByIds(dataAdapterIds.build()).forEach(dataAdapterDto -> dataAdapters.add(DataAdapterApi.fromDto(dataAdapterDto)));
        }
        return new LookupTablePage(query, paginated.pagination(), paginated.stream().map(LookupTableApi::fromDto).collect(Collectors.toList()), caches.build(), dataAdapters.build());
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(e.getMessage(), e);
    }
}
Also used : SearchQuery(org.graylog2.search.SearchQuery) LookupTableApi(org.graylog2.rest.models.system.lookup.LookupTableApi) LookupTableDto(org.graylog2.lookup.dto.LookupTableDto) DataAdapterApi(org.graylog2.rest.models.system.lookup.DataAdapterApi) DBSort(org.mongojack.DBSort) ImmutableSet(com.google.common.collect.ImmutableSet) DBQuery(org.mongojack.DBQuery) BadRequestException(javax.ws.rs.BadRequestException) CacheApi(org.graylog2.rest.models.system.lookup.CacheApi) Path(javax.ws.rs.Path) RequiresPermissions(org.apache.shiro.authz.annotation.RequiresPermissions) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation)

Example 28 with PaginatedList

use of org.graylog2.database.PaginatedList in project graylog2-server by Graylog2.

the class LookupTableResource method get.

@GET
@Path("tables/{idOrName}")
@ApiOperation(value = "Retrieve the named lookup table")
public LookupTablePage get(@ApiParam(name = "idOrName") @PathParam("idOrName") @NotEmpty String idOrName, @ApiParam(name = "resolve") @QueryParam("resolve") @DefaultValue("false") boolean resolveObjects) {
    Optional<LookupTableDto> lookupTableDto = dbTableService.get(idOrName);
    if (!lookupTableDto.isPresent()) {
        throw new NotFoundException();
    }
    LookupTableDto tableDto = lookupTableDto.get();
    checkPermission(RestPermissions.LOOKUP_TABLES_READ, tableDto.id());
    Set<CacheApi> caches = Collections.emptySet();
    Set<DataAdapterApi> adapters = Collections.emptySet();
    if (resolveObjects) {
        caches = dbCacheService.findByIds(Collections.singleton(tableDto.cacheId())).stream().map(CacheApi::fromDto).collect(Collectors.toSet());
        adapters = dbDataAdapterService.findByIds(Collections.singleton(tableDto.dataAdapterId())).stream().map(DataAdapterApi::fromDto).collect(Collectors.toSet());
    }
    final PaginatedList<LookupTableApi> result = PaginatedList.singleton(LookupTableApi.fromDto(tableDto), 1, 1);
    return new LookupTablePage(null, result.pagination(), result, caches, adapters);
}
Also used : LookupTableApi(org.graylog2.rest.models.system.lookup.LookupTableApi) NotFoundException(javax.ws.rs.NotFoundException) LookupTableDto(org.graylog2.lookup.dto.LookupTableDto) CacheApi(org.graylog2.rest.models.system.lookup.CacheApi) DataAdapterApi(org.graylog2.rest.models.system.lookup.DataAdapterApi) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation)

Example 29 with PaginatedList

use of org.graylog2.database.PaginatedList in project graylog2-server by Graylog2.

the class EventNotificationsResource method listNotifications.

@GET
@ApiOperation("List all available notifications")
public PaginatedResponse<NotificationDto> listNotifications(@ApiParam(name = "page") @QueryParam("page") @DefaultValue("1") int page, @ApiParam(name = "per_page") @QueryParam("per_page") @DefaultValue("50") int perPage, @ApiParam(name = "query") @QueryParam("query") @DefaultValue("") String query) {
    final SearchQuery searchQuery = searchQueryParser.parse(query);
    final PaginatedList<NotificationDto> result = dbNotificationService.searchPaginated(searchQuery, notification -> {
        return isPermitted(RestPermissions.EVENT_NOTIFICATIONS_READ, notification.id());
    }, "title", page, perPage);
    return PaginatedResponse.create("notifications", result, query);
}
Also used : SearchQuery(org.graylog2.search.SearchQuery) NotificationDto(org.graylog.events.notifications.NotificationDto) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation)

Aggregations

ApiOperation (io.swagger.annotations.ApiOperation)23 GET (javax.ws.rs.GET)22 SearchQuery (org.graylog2.search.SearchQuery)21 BadRequestException (javax.ws.rs.BadRequestException)17 RequiresPermissions (org.apache.shiro.authz.annotation.RequiresPermissions)16 Path (javax.ws.rs.Path)15 PaginatedList (org.graylog2.database.PaginatedList)11 Produces (javax.ws.rs.Produces)10 Timed (com.codahale.metrics.annotation.Timed)9 Api (io.swagger.annotations.Api)7 ApiParam (io.swagger.annotations.ApiParam)7 List (java.util.List)7 Collectors (java.util.stream.Collectors)7 Inject (javax.inject.Inject)7 PUT (javax.ws.rs.PUT)7 SearchQueryParser (org.graylog2.search.SearchQueryParser)7 ImmutableMap (com.google.common.collect.ImmutableMap)6 Map (java.util.Map)6 DELETE (javax.ws.rs.DELETE)6 DefaultValue (javax.ws.rs.DefaultValue)6