Search in sources :

Example 61 with BadRequestException

use of javax.ws.rs.BadRequestException in project graylog2-server by Graylog2.

the class LookupTableResource method caches.

@GET
@Path("caches")
@ApiOperation(value = "List available caches")
@RequiresPermissions(RestPermissions.LOOKUP_TABLES_READ)
public CachesPage caches(@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(CacheDto.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) {
    if (!CACHE_ALLOWABLE_SORT_FIELDS.contains(sort.toLowerCase(Locale.ENGLISH))) {
        sort = CacheDto.FIELD_TITLE;
    }
    DBSort.SortBuilder sortBuilder;
    if ("desc".equalsIgnoreCase(order)) {
        sortBuilder = DBSort.desc(sort);
    } else {
        sortBuilder = DBSort.asc(sort);
    }
    try {
        final SearchQuery searchQuery = cacheSearchQueryParser.parse(query);
        final DBQuery.Query dbQuery = searchQuery.toDBQuery();
        PaginatedList<CacheDto> paginated = dbCacheService.findPaginated(dbQuery, sortBuilder, page, perPage);
        return new CachesPage(query, paginated.pagination(), paginated.stream().map(CacheApi::fromDto).collect(Collectors.toList()));
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(e.getMessage(), e);
    }
}
Also used : SearchQuery(org.graylog2.search.SearchQuery) DBQuery(org.mongojack.DBQuery) BadRequestException(javax.ws.rs.BadRequestException) CacheApi(org.graylog2.rest.models.system.lookup.CacheApi) CacheDto(org.graylog2.lookup.dto.CacheDto) DBSort(org.mongojack.DBSort) Path(javax.ws.rs.Path) RequiresPermissions(org.apache.shiro.authz.annotation.RequiresPermissions) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation)

Example 62 with BadRequestException

use of javax.ws.rs.BadRequestException in project graylog2-server by Graylog2.

the class RegexReplaceTesterResource method testRegexReplaceExtractor.

private RegexReplaceTesterResponse testRegexReplaceExtractor(String example, String regex, String replacement, boolean replaceAll) {
    final Map<String, Object> config = ImmutableMap.<String, Object>of("regex", regex, "replacement", replacement, "replace_all", replaceAll);
    final RegexReplaceExtractor extractor;
    try {
        extractor = new RegexReplaceExtractor(new MetricRegistry(), "test", "Test", 0L, Extractor.CursorStrategy.COPY, "test", "test", config, getCurrentUser().getName(), Collections.<Converter>emptyList(), Extractor.ConditionType.NONE, "");
    } catch (Extractor.ReservedFieldException e) {
        throw new BadRequestException("Trying to overwrite a reserved message field", e);
    } catch (ConfigurationException e) {
        throw new BadRequestException("Invalid extractor configuration", e);
    }
    final Extractor.Result result = extractor.runExtractor(example);
    final RegexReplaceTesterResponse.Match match = result == null ? null : RegexReplaceTesterResponse.Match.create(String.valueOf(result.getValue()), result.getBeginIndex(), result.getEndIndex());
    return RegexReplaceTesterResponse.create(result != null, match, regex, replacement, replaceAll, example);
}
Also used : MetricRegistry(com.codahale.metrics.MetricRegistry) RegexReplaceExtractor(org.graylog2.inputs.extractors.RegexReplaceExtractor) RegexReplaceTesterResponse(org.graylog2.rest.models.tools.responses.RegexReplaceTesterResponse) ConfigurationException(org.graylog2.ConfigurationException) Converter(org.graylog2.plugin.inputs.Converter) BadRequestException(javax.ws.rs.BadRequestException) Extractor(org.graylog2.plugin.inputs.Extractor) RegexReplaceExtractor(org.graylog2.inputs.extractors.RegexReplaceExtractor)

Example 63 with BadRequestException

use of javax.ws.rs.BadRequestException in project graylog2-server by Graylog2.

the class UsersResource method setUserRoles.

private void setUserRoles(@Nullable List<String> roles, User user) {
    if (roles != null) {
        try {
            final Map<String, Role> nameMap = roleService.loadAllLowercaseNameMap();
            List<String> unknownRoles = new ArrayList<>();
            roles.forEach(roleName -> {
                if (!nameMap.containsKey(roleName.toLowerCase(Locale.US))) {
                    unknownRoles.add(roleName);
                }
            });
            if (!unknownRoles.isEmpty()) {
                throw new BadRequestException(String.format(Locale.ENGLISH, "Invalid role names: %s", StringUtils.join(unknownRoles, ", ")));
            }
            final Iterable<String> roleIds = Iterables.transform(roles, Roles.roleNameToIdFunction(nameMap));
            user.setRoleIds(Sets.newHashSet(roleIds));
        } catch (org.graylog2.database.NotFoundException e) {
            throw new InternalServerErrorException(e);
        }
    }
}
Also used : Role(org.graylog2.shared.users.Role) ArrayList(java.util.ArrayList) BadRequestException(javax.ws.rs.BadRequestException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException)

Example 64 with BadRequestException

use of javax.ws.rs.BadRequestException in project graylog2-server by Graylog2.

the class UsersResource method updateAccountStatus.

@PUT
@Path("{userId}/status/{newStatus}")
@Consumes(MediaType.WILDCARD)
@ApiOperation("Update the account status for a user")
@AuditEvent(type = AuditEventTypes.USER_UPDATE)
public Response updateAccountStatus(@ApiParam(name = "userId", value = "The id of the user whose status to change.", required = true) @PathParam("userId") @NotBlank String userId, @ApiParam(name = "newStatus", value = "The account status to be set", required = true, defaultValue = "enabled", allowableValues = "enabled,disabled,deleted") @PathParam("newStatus") @NotBlank String newStatusString, @Context UserContext userContext) throws ValidationException {
    if (userId.equalsIgnoreCase(userContext.getUserId())) {
        throw new BadRequestException("Users are not allowed to set their own status");
    }
    final User.AccountStatus newStatus = User.AccountStatus.valueOf(newStatusString.toUpperCase(Locale.US));
    final User user = loadUserById(userId);
    checkPermission(RestPermissions.USERS_EDIT, user.getName());
    final User.AccountStatus oldStatus = user.getAccountStatus();
    if (oldStatus.equals(newStatus)) {
        return Response.notModified().build();
    }
    userManagementService.setUserStatus(user, newStatus);
    return Response.ok().build();
}
Also used : User(org.graylog2.plugin.database.users.User) BadRequestException(javax.ws.rs.BadRequestException) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation) AuditEvent(org.graylog2.audit.jersey.AuditEvent) PUT(javax.ws.rs.PUT)

Example 65 with BadRequestException

use of javax.ws.rs.BadRequestException in project graylog2-server by Graylog2.

the class RegexTesterResource method doTestRegex.

private RegexTesterResponse doTestRegex(String example, String regex) {
    final Pattern pattern;
    try {
        pattern = Pattern.compile(regex, Pattern.DOTALL);
    } catch (PatternSyntaxException e) {
        throw new BadRequestException("Invalid regular expression: " + e.getMessage(), e);
    }
    final Matcher matcher = pattern.matcher(example);
    boolean matched = matcher.find();
    // Get the first matched group.
    final RegexTesterResponse.Match match;
    if (matched && matcher.groupCount() > 0) {
        match = RegexTesterResponse.Match.create(matcher.group(1), matcher.start(1), matcher.end(1));
    } else {
        match = null;
    }
    return RegexTesterResponse.create(matched, match, regex, example);
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) BadRequestException(javax.ws.rs.BadRequestException) RegexTesterResponse(org.graylog2.rest.models.tools.responses.RegexTesterResponse) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Aggregations

BadRequestException (javax.ws.rs.BadRequestException)238 Path (javax.ws.rs.Path)92 ApiOperation (io.swagger.annotations.ApiOperation)80 POST (javax.ws.rs.POST)65 Consumes (javax.ws.rs.Consumes)61 Produces (javax.ws.rs.Produces)55 AuditEvent (org.graylog2.audit.jersey.AuditEvent)52 NotFoundException (javax.ws.rs.NotFoundException)42 Timed (com.codahale.metrics.annotation.Timed)40 PUT (javax.ws.rs.PUT)40 ApiResponses (io.swagger.annotations.ApiResponses)38 Test (org.junit.Test)34 GET (javax.ws.rs.GET)32 IOException (java.io.IOException)30 Response (javax.ws.rs.core.Response)27 RequiresPermissions (org.apache.shiro.authz.annotation.RequiresPermissions)27 InternalServerErrorException (javax.ws.rs.InternalServerErrorException)26 NoAuditEvent (org.graylog2.audit.jersey.NoAuditEvent)26 URI (java.net.URI)24 HashMap (java.util.HashMap)22