Search in sources :

Example 21 with BadRequestException

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

the class ExtractorsResource method create.

@POST
@Timed
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Add an extractor to an input", response = ExtractorCreated.class)
@ApiResponses(value = { @ApiResponse(code = 404, message = "No such input on this node."), @ApiResponse(code = 400, message = "No such extractor type."), @ApiResponse(code = 400, message = "Field the extractor should write on is reserved."), @ApiResponse(code = 400, message = "Missing or invalid configuration.") })
@AuditEvent(type = AuditEventTypes.EXTRACTOR_CREATE)
public Response create(@ApiParam(name = "inputId", required = true) @PathParam("inputId") String inputId, @ApiParam(name = "JSON body", required = true) @Valid @NotNull CreateExtractorRequest cer) throws NotFoundException {
    checkPermission(RestPermissions.INPUTS_EDIT, inputId);
    final Input mongoInput = inputService.find(inputId);
    final String id = new com.eaio.uuid.UUID().toString();
    final Extractor extractor = buildExtractorFromRequest(cer, id);
    try {
        inputService.addExtractor(mongoInput, extractor);
    } catch (ValidationException e) {
        final String msg = "Extractor persist validation failed.";
        LOG.error(msg, e);
        throw new BadRequestException(msg, e);
    }
    final String msg = "Added extractor <" + id + "> of type [" + cer.extractorType() + "] to input <" + inputId + ">.";
    LOG.info(msg);
    activityWriter.write(new Activity(msg, ExtractorsResource.class));
    final ExtractorCreated result = ExtractorCreated.create(id);
    final URI extractorUri = getUriBuilderToSelf().path(ExtractorsResource.class).path("{inputId}").build(mongoInput.getId());
    return Response.created(extractorUri).entity(result).build();
}
Also used : ExtractorCreated(org.graylog2.rest.models.system.inputs.extractors.responses.ExtractorCreated) Input(org.graylog2.inputs.Input) MessageInput(org.graylog2.plugin.inputs.MessageInput) ValidationException(org.graylog2.plugin.database.ValidationException) BadRequestException(javax.ws.rs.BadRequestException) Activity(org.graylog2.shared.system.activities.Activity) Extractor(org.graylog2.plugin.inputs.Extractor) URI(java.net.URI) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) Timed(com.codahale.metrics.annotation.Timed) ApiOperation(io.swagger.annotations.ApiOperation) AuditEvent(org.graylog2.audit.jersey.AuditEvent) ApiResponses(io.swagger.annotations.ApiResponses)

Example 22 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)

Example 23 with BadRequestException

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

the class StreamRuleResource method update.

@PUT
@Path("/{streamRuleId}")
@Timed
@ApiOperation(value = "Update a stream rule")
@ApiResponses(value = { @ApiResponse(code = 404, message = "Stream or stream rule not found."), @ApiResponse(code = 400, message = "Invalid JSON Body.") })
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@AuditEvent(type = AuditEventTypes.STREAM_RULE_UPDATE)
public SingleStreamRuleSummaryResponse update(@ApiParam(name = "streamid", value = "The stream id this rule belongs to.", required = true) @PathParam("streamid") String streamid, @ApiParam(name = "streamRuleId", value = "The stream rule id we are updating", required = true) @PathParam("streamRuleId") String streamRuleId, @ApiParam(name = "JSON body", required = true) @Valid @NotNull CreateStreamRuleRequest cr) throws NotFoundException, ValidationException {
    checkPermission(RestPermissions.STREAMS_EDIT, streamid);
    checkNotDefaultStream(streamid, "Cannot update stream rules on default stream.");
    final StreamRule streamRule;
    streamRule = streamRuleService.load(streamRuleId);
    if (!streamRule.getStreamId().equals(streamid)) {
        throw new NotFoundException("Couldn't update stream rule " + streamRuleId + "in stream " + streamid);
    }
    final StreamRuleType streamRuleType = StreamRuleType.fromInteger(cr.type());
    if (null == streamRuleType) {
        throw new BadRequestException("Unknown stream rule type " + cr.type());
    }
    streamRule.setField(cr.field());
    streamRule.setType(streamRuleType);
    streamRule.setInverted(cr.inverted());
    streamRule.setValue(cr.value());
    streamRule.setDescription(cr.description());
    streamRuleService.save(streamRule);
    clusterEventBus.post(StreamsChangedEvent.create(streamid));
    return SingleStreamRuleSummaryResponse.create(streamRule.getId());
}
Also used : StreamRule(org.graylog2.plugin.streams.StreamRule) StreamRuleType(org.graylog2.plugin.streams.StreamRuleType) NotFoundException(org.graylog2.database.NotFoundException) BadRequestException(javax.ws.rs.BadRequestException) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) Timed(com.codahale.metrics.annotation.Timed) ApiOperation(io.swagger.annotations.ApiOperation) AuditEvent(org.graylog2.audit.jersey.AuditEvent) PUT(javax.ws.rs.PUT) ApiResponses(io.swagger.annotations.ApiResponses)

Example 24 with BadRequestException

use of javax.ws.rs.BadRequestException in project jersey by jersey.

the class AbstractFormProvider method readFrom.

public <M extends MultivaluedMap<String, String>> M readFrom(M map, MediaType mediaType, boolean decode, InputStream entityStream) throws IOException {
    final String encoded = readFromAsString(entityStream, mediaType);
    final String charsetName = ReaderWriter.getCharset(mediaType).name();
    final StringTokenizer tokenizer = new StringTokenizer(encoded, "&");
    String token;
    try {
        while (tokenizer.hasMoreTokens()) {
            token = tokenizer.nextToken();
            int idx = token.indexOf('=');
            if (idx < 0) {
                map.add(decode ? URLDecoder.decode(token, charsetName) : token, null);
            } else if (idx > 0) {
                if (decode) {
                    map.add(URLDecoder.decode(token.substring(0, idx), charsetName), URLDecoder.decode(token.substring(idx + 1), charsetName));
                } else {
                    map.add(token.substring(0, idx), token.substring(idx + 1));
                }
            }
        }
        return map;
    } catch (IllegalArgumentException ex) {
        throw new BadRequestException(ex);
    }
}
Also used : StringTokenizer(java.util.StringTokenizer) BadRequestException(javax.ws.rs.BadRequestException)

Example 25 with BadRequestException

use of javax.ws.rs.BadRequestException in project jersey by jersey.

the class MultiPartReaderClientSide method readMultiPart.

protected MultiPart readMultiPart(final Class<MultiPart> type, final Type genericType, final Annotation[] annotations, MediaType mediaType, final MultivaluedMap<String, String> headers, final InputStream stream) throws IOException, MIMEParsingException {
    mediaType = unquoteMediaTypeParameters(mediaType, "boundary");
    final MIMEMessage mimeMessage = new MIMEMessage(stream, mediaType.getParameters().get("boundary"), mimeConfig);
    final boolean formData = MediaTypes.typeEqual(mediaType, MediaType.MULTIPART_FORM_DATA_TYPE);
    final MultiPart multiPart = formData ? new FormDataMultiPart() : new MultiPart();
    final MessageBodyWorkers workers = messageBodyWorkers.get();
    multiPart.setMessageBodyWorkers(workers);
    final MultivaluedMap<String, String> multiPartHeaders = multiPart.getHeaders();
    for (final Map.Entry<String, List<String>> entry : headers.entrySet()) {
        final List<String> values = entry.getValue();
        for (final String value : values) {
            multiPartHeaders.add(entry.getKey(), value);
        }
    }
    final boolean fileNameFix;
    if (!formData) {
        multiPart.setMediaType(mediaType);
        fileNameFix = false;
    } else {
        // see if the User-Agent header corresponds to some version of MS Internet Explorer
        // if so, need to set fileNameFix to true to handle issue http://java.net/jira/browse/JERSEY-759
        final String userAgent = headers.getFirst(HttpHeaders.USER_AGENT);
        fileNameFix = userAgent != null && userAgent.contains(" MSIE ");
    }
    for (final MIMEPart mimePart : getMimeParts(mimeMessage)) {
        final BodyPart bodyPart = formData ? new FormDataBodyPart(fileNameFix) : new BodyPart();
        // Configure providers.
        bodyPart.setMessageBodyWorkers(workers);
        // Copy headers.
        for (final Header header : mimePart.getAllHeaders()) {
            bodyPart.getHeaders().add(header.getName(), header.getValue());
        }
        try {
            final String contentType = bodyPart.getHeaders().getFirst("Content-Type");
            if (contentType != null) {
                bodyPart.setMediaType(MediaType.valueOf(contentType));
            }
            bodyPart.getContentDisposition();
        } catch (final IllegalArgumentException ex) {
            throw new BadRequestException(ex);
        }
        // Copy data into a BodyPartEntity structure.
        bodyPart.setEntity(new BodyPartEntity(mimePart));
        // Add this BodyPart to our MultiPart.
        multiPart.getBodyParts().add(bodyPart);
    }
    return multiPart;
}
Also used : MessageBodyWorkers(org.glassfish.jersey.message.MessageBodyWorkers) BodyPart(org.glassfish.jersey.media.multipart.BodyPart) FormDataBodyPart(org.glassfish.jersey.media.multipart.FormDataBodyPart) BodyPartEntity(org.glassfish.jersey.media.multipart.BodyPartEntity) MultiPart(org.glassfish.jersey.media.multipart.MultiPart) FormDataMultiPart(org.glassfish.jersey.media.multipart.FormDataMultiPart) Header(org.jvnet.mimepull.Header) MIMEMessage(org.jvnet.mimepull.MIMEMessage) FormDataBodyPart(org.glassfish.jersey.media.multipart.FormDataBodyPart) FormDataMultiPart(org.glassfish.jersey.media.multipart.FormDataMultiPart) BadRequestException(javax.ws.rs.BadRequestException) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) MIMEPart(org.jvnet.mimepull.MIMEPart)

Aggregations

BadRequestException (javax.ws.rs.BadRequestException)58 ApiOperation (io.swagger.annotations.ApiOperation)34 AuditEvent (org.graylog2.audit.jersey.AuditEvent)31 Timed (com.codahale.metrics.annotation.Timed)26 Path (javax.ws.rs.Path)26 ApiResponses (io.swagger.annotations.ApiResponses)22 POST (javax.ws.rs.POST)20 Produces (javax.ws.rs.Produces)20 Consumes (javax.ws.rs.Consumes)18 URI (java.net.URI)13 PUT (javax.ws.rs.PUT)13 ValidationException (org.graylog2.plugin.database.ValidationException)11 RequiresPermissions (org.apache.shiro.authz.annotation.RequiresPermissions)9 InternalServerErrorException (javax.ws.rs.InternalServerErrorException)8 NotFoundException (org.graylog2.database.NotFoundException)8 Stream (org.graylog2.plugin.streams.Stream)8 DELETE (javax.ws.rs.DELETE)6 NotFoundException (javax.ws.rs.NotFoundException)6 NoAuditEvent (org.graylog2.audit.jersey.NoAuditEvent)5 ConfigurationException (org.graylog2.plugin.configuration.ConfigurationException)5