Search in sources :

Example 71 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);
    checkNotEditable(streamid, "Cannot update stream rules on non-editable streams.");
    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);
    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 72 with BadRequestException

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

the class ContentPackResource method createContentPack.

@POST
@Timed
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Upload a content pack")
@ApiResponses(value = { @ApiResponse(code = 400, message = "Missing or invalid content pack"), @ApiResponse(code = 500, message = "Error while saving content pack") })
@AuditEvent(type = AuditEventTypes.CONTENT_PACK_CREATE)
@JsonView(ContentPackView.HttpView.class)
public Response createContentPack(@ApiParam(name = "Request body", value = "Content pack", required = true) @NotNull @Valid final ContentPack contentPack) {
    checkPermission(RestPermissions.CONTENT_PACK_CREATE);
    final ContentPack pack = contentPackPersistenceService.filterMissingResourcesAndInsert(contentPack).orElseThrow(() -> new BadRequestException("Content pack " + contentPack.id() + " with this revision " + contentPack.revision() + " already found!"));
    final URI packUri = getUriBuilderToSelf().path(ContentPackResource.class).path("{contentPackId}").build(pack.id());
    return Response.created(packUri).build();
}
Also used : ContentPack(org.graylog2.contentpacks.model.ContentPack) BadRequestException(javax.ws.rs.BadRequestException) URI(java.net.URI) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Timed(com.codahale.metrics.annotation.Timed) ApiOperation(io.swagger.annotations.ApiOperation) JsonView(com.fasterxml.jackson.annotation.JsonView) AuditEvent(org.graylog2.audit.jersey.AuditEvent) ApiResponses(io.swagger.annotations.ApiResponses)

Example 73 with BadRequestException

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

the class SessionsResource method newSession.

@POST
@ApiOperation(value = "Create a new session", notes = "This request creates a new session for a user or " + "reactivates an existing session: the equivalent of logging in.")
@NoAuditEvent("dispatches audit events in the method body")
public JsonNode newSession(@Context ContainerRequestContext requestContext, @ApiParam(name = "Login request", value = "Credentials. The default " + "implementation requires presence of two properties: 'username' and " + "'password'. However a plugin may customize which kind of credentials " + "are accepted and therefore expect different properties.", required = true) @NotNull JsonNode createRequest) {
    final SecurityContext securityContext = requestContext.getSecurityContext();
    if (!(securityContext instanceof ShiroSecurityContext)) {
        throw new InternalServerErrorException("Unsupported SecurityContext class, this is a bug!");
    }
    final ShiroSecurityContext shiroSecurityContext = (ShiroSecurityContext) securityContext;
    final ActorAwareAuthenticationToken authToken;
    try {
        authToken = tokenFactory.forRequestBody(createRequest);
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(e.getMessage());
    }
    // we treat the BASIC auth username as the sessionid
    final String sessionId = shiroSecurityContext.getUsername();
    final String host = RestTools.getRemoteAddrFromRequest(grizzlyRequest, trustedSubnets);
    try {
        Optional<Session> session = sessionCreator.create(sessionId, host, authToken);
        if (session.isPresent()) {
            return sessionResponseFactory.forSession(session.get());
        } else {
            throw new NotAuthorizedException("Invalid credentials.", "Basic realm=\"Graylog Server session\"");
        }
    } catch (AuthenticationServiceUnavailableException e) {
        throw new ServiceUnavailableException("Authentication service unavailable");
    }
}
Also used : SecurityContext(javax.ws.rs.core.SecurityContext) ShiroSecurityContext(org.graylog2.shared.security.ShiroSecurityContext) ActorAwareAuthenticationToken(org.graylog2.shared.security.ActorAwareAuthenticationToken) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) BadRequestException(javax.ws.rs.BadRequestException) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) ServiceUnavailableException(javax.ws.rs.ServiceUnavailableException) AuthenticationServiceUnavailableException(org.graylog2.shared.security.AuthenticationServiceUnavailableException) AuthenticationServiceUnavailableException(org.graylog2.shared.security.AuthenticationServiceUnavailableException) ShiroSecurityContext(org.graylog2.shared.security.ShiroSecurityContext) Session(org.apache.shiro.session.Session) POST(javax.ws.rs.POST) ApiOperation(io.swagger.annotations.ApiOperation) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent)

Example 74 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 75 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 : IndexSetConfig(org.graylog2.indexer.indexset.IndexSetConfig) Tools(org.graylog2.plugin.Tools) LoggerFactory(org.slf4j.LoggerFactory) AlarmCallbackConfiguration(org.graylog2.alarmcallbacks.AlarmCallbackConfiguration) AlertService(org.graylog2.alerts.AlertService) StreamRule(org.graylog2.plugin.streams.StreamRule) BasicDBList(com.mongodb.BasicDBList) DBObject(com.mongodb.DBObject) Map(java.util.Map) EmbeddedPersistable(org.graylog2.plugin.database.EmbeddedPersistable) BadRequestException(javax.ws.rs.BadRequestException) IndexSet(org.graylog2.indexer.IndexSet) StreamsChangedEvent(org.graylog2.streams.events.StreamsChangedEvent) PersistedServiceImpl(org.graylog2.database.PersistedServiceImpl) ImmutableSet(com.google.common.collect.ImmutableSet) NotificationService(org.graylog2.notifications.NotificationService) Collection(java.util.Collection) Set(java.util.Set) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) CreateStreamRequest(org.graylog2.rest.resources.streams.requests.CreateStreamRequest) List(java.util.List) ClusterEventBus(org.graylog2.events.ClusterEventBus) IndexSetService(org.graylog2.indexer.indexset.IndexSetService) Stream(org.graylog2.plugin.streams.Stream) AlertCondition(org.graylog2.plugin.alarms.AlertCondition) Optional(java.util.Optional) MongoConnection(org.graylog2.database.MongoConnection) EntityOwnershipService(org.graylog.security.entities.EntityOwnershipService) QueryBuilder(com.mongodb.QueryBuilder) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Strings.isNullOrEmpty(com.google.common.base.Strings.isNullOrEmpty) EmailAlarmCallback(org.graylog2.alarmcallbacks.EmailAlarmCallback) HashMap(java.util.HashMap) Function(java.util.function.Function) DBProjection(org.mongojack.DBProjection) Inject(javax.inject.Inject) HashSet(java.util.HashSet) Strings(com.google.common.base.Strings) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) MongoIndexSet(org.graylog2.indexer.MongoIndexSet) StreamSupport(java.util.stream.StreamSupport) Alert(org.graylog2.alerts.Alert) NotFoundException(org.graylog2.database.NotFoundException) Nullable(javax.annotation.Nullable) Notification(org.graylog2.notifications.Notification) Logger(org.slf4j.Logger) BasicDBObject(com.mongodb.BasicDBObject) StreamDeletedEvent(org.graylog2.streams.events.StreamDeletedEvent) Maps(com.google.common.collect.Maps) AlarmCallbackConfigurationImpl(org.graylog2.alarmcallbacks.AlarmCallbackConfigurationImpl) AlarmCallbackConfigurationService(org.graylog2.alarmcallbacks.AlarmCallbackConfigurationService) DBCursor(com.mongodb.DBCursor) Output(org.graylog2.plugin.streams.Output) ValidationException(org.graylog2.plugin.database.ValidationException) ObjectId(org.bson.types.ObjectId) User(org.graylog2.plugin.database.users.User) 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) BasicDBList(com.mongodb.BasicDBList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) EmailAlarmCallback(org.graylog2.alarmcallbacks.EmailAlarmCallback) AlarmCallbackConfigurationImpl(org.graylog2.alarmcallbacks.AlarmCallbackConfigurationImpl) AlarmCallbackConfiguration(org.graylog2.alarmcallbacks.AlarmCallbackConfiguration)

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