Search in sources :

Example 16 with BadRequestException

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

the class StreamAlarmCallbackResource method update.

@PUT
@Path("/{alarmCallbackId}")
@Timed
@ApiOperation(value = "Update an alarm callback")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@AuditEvent(type = AuditEventTypes.ALARM_CALLBACK_UPDATE)
public void update(@ApiParam(name = "streamid", value = "The stream id this alarm callback belongs to.", required = true) @PathParam("streamid") String streamid, @ApiParam(name = "alarmCallbackId", required = true) @PathParam("alarmCallbackId") String alarmCallbackId, @ApiParam(name = "JSON body", required = true) CreateAlarmCallbackRequest alarmCallbackRequest) throws NotFoundException {
    checkPermission(RestPermissions.STREAMS_EDIT, streamid);
    final AlarmCallbackConfiguration callbackConfiguration = alarmCallbackConfigurationService.load(alarmCallbackId);
    if (callbackConfiguration == null) {
        throw new NotFoundException("Unable to find alarm callback configuration " + alarmCallbackId);
    }
    final Map<String, Object> configuration = convertConfigurationValues(alarmCallbackRequest);
    final AlarmCallbackConfiguration updatedConfig = ((AlarmCallbackConfigurationImpl) callbackConfiguration).toBuilder().setTitle(alarmCallbackRequest.title()).setConfiguration(configuration).build();
    try {
        alarmCallbackFactory.create(updatedConfig).checkConfiguration();
        alarmCallbackConfigurationService.save(updatedConfig);
    } catch (ValidationException | AlarmCallbackConfigurationException | ConfigurationException e) {
        LOG.error("Invalid alarm callback configuration.", e);
        throw new BadRequestException(e.getMessage(), e);
    } catch (ClassNotFoundException e) {
        LOG.error("Invalid alarm callback type.", e);
        throw new BadRequestException("Invalid alarm callback type.", e);
    }
}
Also used : ValidationException(org.graylog2.plugin.database.ValidationException) AlarmCallbackConfigurationException(org.graylog2.plugin.alarms.callbacks.AlarmCallbackConfigurationException) ConfigurationException(org.graylog2.plugin.configuration.ConfigurationException) NotFoundException(org.graylog2.database.NotFoundException) BadRequestException(javax.ws.rs.BadRequestException) AlarmCallbackConfiguration(org.graylog2.alarmcallbacks.AlarmCallbackConfiguration) AlarmCallbackConfigurationException(org.graylog2.plugin.alarms.callbacks.AlarmCallbackConfigurationException) 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)

Example 17 with BadRequestException

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

the class StreamServiceImpl method updateCallbackConfiguration.

// I tried to be sorry, really. https://www.youtube.com/watch?v=3KVyRqloGmk
private void updateCallbackConfiguration(String action, String type, String entity, List<AlarmCallbackConfiguration> streamCallbacks) {
    final AtomicBoolean ran = new AtomicBoolean(false);
    streamCallbacks.stream().filter(callback -> callback.getType().equals(EmailAlarmCallback.class.getCanonicalName())).forEach(callback -> {
        ran.set(true);
        final Map<String, Object> configuration = callback.getConfiguration();
        String key;
        if ("users".equals(type)) {
            key = EmailAlarmCallback.CK_USER_RECEIVERS;
        } else {
            key = EmailAlarmCallback.CK_EMAIL_RECEIVERS;
        }
        @SuppressWarnings("unchecked") final List<String> recipients = (List<String>) configuration.get(key);
        if ("add".equals(action)) {
            if (!recipients.contains(entity)) {
                recipients.add(entity);
            }
        } else {
            if (recipients.contains(entity)) {
                recipients.remove(entity);
            }
        }
        configuration.put(key, recipients);
        final AlarmCallbackConfiguration updatedConfig = ((AlarmCallbackConfigurationImpl) callback).toBuilder().setConfiguration(configuration).build();
        try {
            alarmCallbackConfigurationService.save(updatedConfig);
        } catch (ValidationException e) {
            throw new BadRequestException("Unable to save alarm callback configuration", e);
        }
    });
    if (!ran.get()) {
        throw new BadRequestException("Unable to " + action + " receiver: Stream has no email alarm callback.");
    }
}
Also used : QueryBuilder(com.mongodb.QueryBuilder) IndexSetConfig(org.graylog2.indexer.indexset.IndexSetConfig) Tools(org.graylog2.plugin.Tools) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Strings.isNullOrEmpty(com.google.common.base.Strings.isNullOrEmpty) EmailAlarmCallback(org.graylog2.alarmcallbacks.EmailAlarmCallback) HashMap(java.util.HashMap) AlarmCallbackConfiguration(org.graylog2.alarmcallbacks.AlarmCallbackConfiguration) AlertService(org.graylog2.alerts.AlertService) StreamRule(org.graylog2.plugin.streams.StreamRule) Inject(javax.inject.Inject) HashSet(java.util.HashSet) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) DBObject(com.mongodb.DBObject) Map(java.util.Map) MongoIndexSet(org.graylog2.indexer.MongoIndexSet) EmbeddedPersistable(org.graylog2.plugin.database.EmbeddedPersistable) BadRequestException(javax.ws.rs.BadRequestException) IndexSet(org.graylog2.indexer.IndexSet) Alert(org.graylog2.alerts.Alert) PersistedServiceImpl(org.graylog2.database.PersistedServiceImpl) NotFoundException(org.graylog2.database.NotFoundException) Nullable(javax.annotation.Nullable) Notification(org.graylog2.notifications.Notification) Logger(org.slf4j.Logger) NotificationService(org.graylog2.notifications.NotificationService) BasicDBObject(com.mongodb.BasicDBObject) Set(java.util.Set) Maps(com.google.common.collect.Maps) Collectors(java.util.stream.Collectors) AlarmCallbackConfigurationImpl(org.graylog2.alarmcallbacks.AlarmCallbackConfigurationImpl) AlarmCallbackConfigurationService(org.graylog2.alarmcallbacks.AlarmCallbackConfigurationService) CreateStreamRequest(org.graylog2.rest.resources.streams.requests.CreateStreamRequest) List(java.util.List) IndexSetService(org.graylog2.indexer.indexset.IndexSetService) Output(org.graylog2.plugin.streams.Output) Stream(org.graylog2.plugin.streams.Stream) ValidationException(org.graylog2.plugin.database.ValidationException) AlertCondition(org.graylog2.plugin.alarms.AlertCondition) ObjectId(org.bson.types.ObjectId) Optional(java.util.Optional) MongoConnection(org.graylog2.database.MongoConnection) Collections(java.util.Collections) ValidationException(org.graylog2.plugin.database.ValidationException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BadRequestException(javax.ws.rs.BadRequestException) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) EmailAlarmCallback(org.graylog2.alarmcallbacks.EmailAlarmCallback) AlarmCallbackConfigurationImpl(org.graylog2.alarmcallbacks.AlarmCallbackConfigurationImpl) AlarmCallbackConfiguration(org.graylog2.alarmcallbacks.AlarmCallbackConfiguration)

Example 18 with BadRequestException

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

the class IndexRangesResource method show.

@GET
@Path("/{index: [a-z_0-9]+}")
@Timed
@ApiOperation(value = "Show single index range")
@Produces(MediaType.APPLICATION_JSON)
public IndexRangeSummary show(@ApiParam(name = "index", value = "The name of the Graylog-managed Elasticsearch index", required = true) @PathParam("index") @NotEmpty String index) throws NotFoundException {
    if (!indexSetRegistry.isManagedIndex(index)) {
        throw new BadRequestException(index + " is not a Graylog-managed Elasticsearch index.");
    }
    checkPermission(RestPermissions.INDEXRANGES_READ, index);
    final IndexRange indexRange = indexRangeService.get(index);
    return IndexRangeSummary.create(indexRange.indexName(), indexRange.begin(), indexRange.end(), indexRange.calculatedAt(), indexRange.calculationDuration());
}
Also used : IndexRange(org.graylog2.indexer.ranges.IndexRange) BadRequestException(javax.ws.rs.BadRequestException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation)

Example 19 with BadRequestException

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

the class JsonTesterResource method testJsonExtractor.

private JsonTesterResponse testJsonExtractor(String testString, boolean flatten, String listSeparator, String keySeparator, String kvSeparator, boolean replaceKeyWhitespace, String keyWhitespaceReplacement, String keyPrefix) {
    final Map<String, Object> config = ImmutableMap.<String, Object>builder().put("flatten", flatten).put("list_separator", listSeparator).put("key_separator", keySeparator).put("kv_separator", kvSeparator).put("replace_key_whitespace", replaceKeyWhitespace).put("key_whitespace_replacement", keyWhitespaceReplacement).put("key_prefix", keyPrefix).build();
    final JsonExtractor extractor;
    try {
        extractor = new JsonExtractor(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 Map<String, Object> result = extractor.extractJson(testString);
    return JsonTesterResponse.create(result, flatten, listSeparator, keySeparator, kvSeparator, testString);
}
Also used : ConfigurationException(org.graylog2.ConfigurationException) MetricRegistry(com.codahale.metrics.MetricRegistry) JsonExtractor(org.graylog2.inputs.extractors.JsonExtractor) Converter(org.graylog2.plugin.inputs.Converter) BadRequestException(javax.ws.rs.BadRequestException) Extractor(org.graylog2.plugin.inputs.Extractor) JsonExtractor(org.graylog2.inputs.extractors.JsonExtractor)

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

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