Search in sources :

Example 21 with ValidationException

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

the class StreamRuleResource method create.

@POST
@Timed
@ApiOperation(value = "Create a stream rule")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@AuditEvent(type = AuditEventTypes.STREAM_RULE_CREATE)
public Response create(@ApiParam(name = "streamid", value = "The stream id this new rule belongs to.", required = true) @PathParam("streamid") String streamId, @ApiParam(name = "JSON body", required = true) @Valid @NotNull CreateStreamRuleRequest cr) throws NotFoundException, ValidationException {
    checkPermission(RestPermissions.STREAMS_EDIT, streamId);
    checkNotDefaultStream(streamId, "Cannot add stream rules to the default stream.");
    final Stream stream = streamService.load(streamId);
    final StreamRule streamRule = streamRuleService.create(streamId, cr);
    final String id = streamService.save(streamRule);
    clusterEventBus.post(StreamsChangedEvent.create(stream.getId()));
    final SingleStreamRuleSummaryResponse response = SingleStreamRuleSummaryResponse.create(id);
    final URI streamRuleUri = getUriBuilderToSelf().path(StreamRuleResource.class).path("{streamRuleId}").build(streamId, id);
    return Response.created(streamRuleUri).entity(response).build();
}
Also used : SingleStreamRuleSummaryResponse(org.graylog2.rest.resources.streams.responses.SingleStreamRuleSummaryResponse) StreamRule(org.graylog2.plugin.streams.StreamRule) Stream(org.graylog2.plugin.streams.Stream) 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)

Example 22 with ValidationException

use of org.graylog2.plugin.database.ValidationException 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 23 with ValidationException

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

the class InputsResource method update.

@PUT
@Timed
@Path("/{inputId}")
@ApiOperation(value = "Update input on this node", response = InputCreated.class)
@ApiResponses(value = { @ApiResponse(code = 404, message = "No such input on this node."), @ApiResponse(code = 400, message = "Missing or invalid input configuration.") })
@AuditEvent(type = AuditEventTypes.MESSAGE_INPUT_UPDATE)
public Response update(@ApiParam(name = "JSON body", required = true) @Valid @NotNull InputCreateRequest lr, @ApiParam(name = "inputId", required = true) @PathParam("inputId") String inputId) throws org.graylog2.database.NotFoundException, NoSuchInputTypeException, ConfigurationException, ValidationException {
    checkPermission(RestPermissions.INPUTS_EDIT, inputId);
    final Input input = inputService.find(inputId);
    final Map<String, Object> mergedInput = input.getFields();
    final MessageInput messageInput = messageInputFactory.create(lr, getCurrentUser().getName(), lr.node());
    messageInput.checkConfiguration();
    mergedInput.putAll(messageInput.asMap());
    final Input newInput = inputService.create(input.getId(), mergedInput);
    inputService.save(newInput);
    final URI inputUri = getUriBuilderToSelf().path(InputsResource.class).path("{inputId}").build(input.getId());
    return Response.created(inputUri).entity(InputCreated.create(input.getId())).build();
}
Also used : Input(org.graylog2.inputs.Input) MessageInput(org.graylog2.plugin.inputs.MessageInput) MessageInput(org.graylog2.plugin.inputs.MessageInput) URI(java.net.URI) Path(javax.ws.rs.Path) 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 ValidationException

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

the class LdapResource method updateGroupMappingSettings.

@PUT
@RequiresPermissions(value = { RestPermissions.LDAPGROUPS_EDIT, RestPermissions.LDAP_EDIT }, logical = OR)
@ApiOperation(value = "Update the LDAP group to Graylog role mapping", notes = "Corresponds directly to the output of GET /system/ldap/settings/groups")
@Path("/settings/groups")
@Consumes(MediaType.APPLICATION_JSON)
@AuditEvent(type = AuditEventTypes.LDAP_GROUP_MAPPING_UPDATE)
public Response updateGroupMappingSettings(@ApiParam(name = "JSON body", required = true, value = "A hash in which the keys are the LDAP group names and values is the Graylog role name.") @NotNull Map<String, String> groupMapping) throws ValidationException {
    final LdapSettings ldapSettings = firstNonNull(ldapSettingsService.load(), ldapSettingsFactory.createEmpty());
    ldapSettings.setGroupMapping(groupMapping);
    ldapSettingsService.save(ldapSettings);
    return Response.noContent().build();
}
Also used : LdapSettings(org.graylog2.shared.security.ldap.LdapSettings) Path(javax.ws.rs.Path) RequiresPermissions(org.apache.shiro.authz.annotation.RequiresPermissions) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent) AuditEvent(org.graylog2.audit.jersey.AuditEvent) PUT(javax.ws.rs.PUT)

Example 25 with ValidationException

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

the class ExtractorsResource method order.

@POST
@Timed
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Update extractor order of an input")
@ApiResponses(value = { @ApiResponse(code = 404, message = "No such input on this node.") })
@Path("order")
@AuditEvent(type = AuditEventTypes.EXTRACTOR_ORDER_UPDATE)
public void order(@ApiParam(name = "inputId", value = "Persist ID (!) of input.", required = true) @PathParam("inputId") String inputPersistId, @ApiParam(name = "JSON body", required = true) OrderExtractorsRequest oer) throws NotFoundException {
    checkPermission(RestPermissions.INPUTS_EDIT, inputPersistId);
    final Input mongoInput = inputService.find(inputPersistId);
    for (Extractor extractor : inputService.getExtractors(mongoInput)) {
        if (oer.order().containsValue(extractor.getId())) {
            extractor.setOrder(Tools.getKeyByValue(oer.order(), extractor.getId()));
        }
        // Docs embedded in MongoDB array cannot be updated atomically... :/
        inputService.removeExtractor(mongoInput, extractor.getId());
        try {
            inputService.addExtractor(mongoInput, extractor);
        } catch (ValidationException e) {
            LOG.warn("Validation error for extractor update.", e);
        }
    }
    LOG.info("Updated extractor ordering of input <persist:{}>.", inputPersistId);
}
Also used : Input(org.graylog2.inputs.Input) MessageInput(org.graylog2.plugin.inputs.MessageInput) ValidationException(org.graylog2.plugin.database.ValidationException) Extractor(org.graylog2.plugin.inputs.Extractor) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Timed(com.codahale.metrics.annotation.Timed) ApiOperation(io.swagger.annotations.ApiOperation) AuditEvent(org.graylog2.audit.jersey.AuditEvent) ApiResponses(io.swagger.annotations.ApiResponses)

Aggregations

ApiOperation (io.swagger.annotations.ApiOperation)47 AuditEvent (org.graylog2.audit.jersey.AuditEvent)47 Timed (com.codahale.metrics.annotation.Timed)36 ValidationException (org.graylog2.plugin.database.ValidationException)32 ApiResponses (io.swagger.annotations.ApiResponses)29 Path (javax.ws.rs.Path)29 BadRequestException (javax.ws.rs.BadRequestException)25 PUT (javax.ws.rs.PUT)24 Produces (javax.ws.rs.Produces)23 Consumes (javax.ws.rs.Consumes)22 POST (javax.ws.rs.POST)21 URI (java.net.URI)18 RequiresPermissions (org.apache.shiro.authz.annotation.RequiresPermissions)13 Stream (org.graylog2.plugin.streams.Stream)12 User (org.graylog2.plugin.database.users.User)11 MessageInput (org.graylog2.plugin.inputs.MessageInput)11 NotFoundException (org.graylog2.database.NotFoundException)10 List (java.util.List)7 NoAuditEvent (org.graylog2.audit.jersey.NoAuditEvent)7 Dashboard (org.graylog2.dashboards.Dashboard)7