use of javax.ws.rs.BadRequestException in project graylog2-server by Graylog2.
the class SearchResource method createRequestExceptionForParseFailure.
protected WebApplicationException createRequestExceptionForParseFailure(String query, SearchPhaseExecutionException e) {
LOG.warn("Unable to execute search: {}", e.getMessage());
QueryParseError errorMessage = QueryParseError.create(query, "Unable to execute search", e.getClass().getCanonicalName());
// We're so going to hell for this…
if (e.toString().contains("nested: QueryParsingException")) {
final QueryParser queryParser = new QueryParser("", new StandardAnalyzer());
try {
queryParser.parse(query);
} catch (ParseException parseException) {
Token currentToken = null;
try {
// FIXME I have no idea why this is necessary but without that call currentToken will be null.
final ParseException exception = queryParser.generateParseException();
currentToken = exception.currentToken;
} catch (NullPointerException npe) {
// "Normal" exception and no need to spam the logs with it.
LOG.debug("Exception thrown while generating parse exception.", npe);
}
if (currentToken == null) {
LOG.warn("No position/token available for ParseException.", parseException);
errorMessage = QueryParseError.create(query, parseException.getMessage(), parseException.getClass().getCanonicalName());
} else {
// scan for first usable token with position information
int beginColumn = 0;
int beginLine = 0;
int endColumn = 0;
int endLine = 0;
while (currentToken != null && beginLine == 0) {
beginColumn = currentToken.beginColumn;
beginLine = currentToken.beginLine;
endColumn = currentToken.endColumn;
endLine = currentToken.endLine;
currentToken = currentToken.next;
}
errorMessage = QueryParseError.create(query, beginColumn, beginLine, endColumn, endLine, parseException.getMessage(), parseException.getClass().getCanonicalName());
}
}
return new BadRequestException(Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build());
} else {
return new InternalServerErrorException("Unable to fulfill search request", e);
}
}
use of javax.ws.rs.BadRequestException in project graylog2-server by Graylog2.
the class StreamResource method update.
@PUT
@Timed
@Path("/{streamId}")
@ApiOperation(value = "Update a stream")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = 404, message = "Stream not found."), @ApiResponse(code = 400, message = "Invalid ObjectId.") })
@AuditEvent(type = AuditEventTypes.STREAM_UPDATE)
public StreamResponse update(@ApiParam(name = "streamId", required = true) @PathParam("streamId") String streamId, @ApiParam(name = "JSON body", required = true) @Valid @NotNull UpdateStreamRequest cr) throws NotFoundException, ValidationException {
checkPermission(RestPermissions.STREAMS_EDIT, streamId);
checkNotDefaultStream(streamId, "The default stream cannot be edited.");
final Stream stream = streamService.load(streamId);
if (!Strings.isNullOrEmpty(cr.title())) {
stream.setTitle(cr.title());
}
if (!Strings.isNullOrEmpty(cr.description())) {
stream.setDescription(cr.description());
}
if (cr.matchingType() != null) {
try {
stream.setMatchingType(Stream.MatchingType.valueOf(cr.matchingType()));
} catch (IllegalArgumentException e) {
throw new BadRequestException("Invalid matching type '" + cr.matchingType() + "' specified. Should be one of: " + Arrays.toString(Stream.MatchingType.values()));
}
}
final Boolean removeMatchesFromDefaultStream = cr.removeMatchesFromDefaultStream();
if (removeMatchesFromDefaultStream != null) {
stream.setRemoveMatchesFromDefaultStream(removeMatchesFromDefaultStream);
}
// id if it's null/empty in the update request.
if (!Strings.isNullOrEmpty(cr.indexSetId())) {
stream.setIndexSetId(cr.indexSetId());
}
final Optional<IndexSet> indexSet = indexSetRegistry.get(stream.getIndexSetId());
if (!indexSet.isPresent()) {
throw new BadRequestException("Index set with ID <" + stream.getIndexSetId() + "> does not exist!");
} else if (!indexSet.get().getConfig().isWritable()) {
throw new BadRequestException("Assigned index set must be writable!");
}
streamService.save(stream);
clusterEventBus.post(StreamsChangedEvent.create(stream.getId()));
return streamToResponse(stream);
}
use of javax.ws.rs.BadRequestException in project graylog2-server by Graylog2.
the class StreamAlertConditionResource method create.
@POST
@Timed
@ApiOperation(value = "Create an alert condition")
@ApiResponses(value = { @ApiResponse(code = 404, message = "Stream not found."), @ApiResponse(code = 400, message = "Invalid ObjectId.") })
@AuditEvent(type = AuditEventTypes.ALERT_CONDITION_CREATE)
public Response create(@ApiParam(name = "streamId", value = "The stream id this new alert condition belongs to.", required = true) @PathParam("streamId") String streamid, @ApiParam(name = "JSON body", required = true) @Valid @NotNull CreateConditionRequest ccr) throws NotFoundException, ValidationException {
checkPermission(RestPermissions.STREAMS_EDIT, streamid);
final Stream stream = streamService.load(streamid);
try {
final AlertCondition alertCondition = alertService.fromRequest(convertConfigurationInRequest(ccr), stream, getCurrentUser().getName());
streamService.addAlertCondition(stream, alertCondition);
final Map<String, String> result = ImmutableMap.of("alert_condition_id", alertCondition.getId());
final URI alertConditionUri = getUriBuilderToSelf().path(StreamAlertConditionResource.class).path("{conditionId}").build(stream.getId(), alertCondition.getId());
return Response.created(alertConditionUri).entity(result).build();
} catch (ConfigurationException e) {
throw new BadRequestException("Invalid alert condition parameters", e);
}
}
use of javax.ws.rs.BadRequestException in project graylog2-server by Graylog2.
the class StreamAlertResource method addReceiver.
@POST
@Timed
@Path("receivers")
@ApiOperation(value = "Add an alert receiver")
@ApiResponses(value = { @ApiResponse(code = 404, message = "Stream not found."), @ApiResponse(code = 400, message = "Invalid ObjectId."), @ApiResponse(code = 400, message = "Stream has no email alarm callbacks.") })
@AuditEvent(type = AuditEventTypes.ALERT_RECEIVER_CREATE)
@Deprecated
public Response addReceiver(@ApiParam(name = "streamId", value = "The stream id this new alert condition belongs to.", required = true) @PathParam("streamId") String streamId, @ApiParam(name = "entity", value = "Name/ID of user or email address to add as alert receiver.", required = true) @QueryParam("entity") String entity, @ApiParam(name = "type", value = "Type: users or emails", required = true) @QueryParam("type") String type) throws org.graylog2.database.NotFoundException {
checkPermission(RestPermissions.STREAMS_EDIT, streamId);
checkArgument(!Strings.isNullOrEmpty(entity));
if (type == null || !"users".equals(type) && !"emails".equals(type)) {
final String msg = "No such type: [" + type + "]";
LOG.warn(msg);
throw new BadRequestException(msg);
}
final Stream stream = streamService.load(streamId);
// TODO What's the actual URI of the created resource?
final URI streamAlertUri = getUriBuilderToSelf().path(StreamAlertResource.class).build(streamId);
// Maybe the list already contains this receiver?
if (stream.getAlertReceivers().containsKey(type) || stream.getAlertReceivers().get(type) != null && stream.getAlertReceivers().get(type).contains(entity)) {
return Response.created(streamAlertUri).build();
}
streamService.addAlertReceiver(stream, type, entity);
return Response.created(streamAlertUri).build();
}
use of javax.ws.rs.BadRequestException in project graylog2-server by Graylog2.
the class MessageResource method decodeMessage.
private Message decodeMessage(Codec codec, ResolvableInetSocketAddress remoteAddress, RawMessage rawMessage) {
Message message;
try {
message = codec.decode(rawMessage);
} catch (Exception e) {
throw new BadRequestException("Could not decode message");
}
if (message == null) {
throw new BadRequestException("Could not decode message");
}
// Ensure the decoded Message has a source, otherwise creating a ResultMessage will fail
if (isNullOrEmpty(message.getSource())) {
final String address = InetAddresses.toAddrString(remoteAddress.getAddress());
message.setSource(address);
}
// Override source
final Configuration configuration = codec.getConfiguration();
if (configuration.stringIsSet(Codec.Config.CK_OVERRIDE_SOURCE)) {
message.setSource(configuration.getString(Codec.Config.CK_OVERRIDE_SOURCE));
}
return message;
}
Aggregations