Search in sources :

Example 26 with InternalServerErrorException

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

the class AlarmCallbacksResource method test.

@POST
@Timed
@Path("/{alarmCallbackId}/test")
@ApiOperation(value = "Send a test alert for a given alarm callback")
@ApiResponses(value = { @ApiResponse(code = 404, message = "Alarm callback not found."), @ApiResponse(code = 400, message = "Invalid ObjectId."), @ApiResponse(code = 500, message = "Error while testing alarm callback") })
@NoAuditEvent("only used to test alert notifications")
public Response test(@ApiParam(name = "alarmCallbackId", value = "The alarm callback id to send a test alert for.", required = true) @PathParam("alarmCallbackId") String alarmCallbackId) throws TransportConfigurationException, EmailException, NotFoundException {
    final AlarmCallbackConfiguration alarmCallbackConfiguration = alarmCallbackConfigurationService.load(alarmCallbackId);
    final String streamId = alarmCallbackConfiguration.getStreamId();
    checkPermission(RestPermissions.STREAMS_EDIT, streamId);
    final Stream stream = streamService.load(streamId);
    final DummyAlertCondition testAlertCondition = new DummyAlertCondition(stream, null, Tools.nowUTC(), getSubject().getPrincipal().toString(), Collections.emptyMap(), "Test Alert");
    try {
        AbstractAlertCondition.CheckResult checkResult = testAlertCondition.runCheck();
        AlarmCallback alarmCallback = alarmCallbackFactory.create(alarmCallbackConfiguration);
        alarmCallback.call(stream, checkResult);
    } catch (Exception e) {
        throw new InternalServerErrorException(e.getMessage(), e);
    }
    return Response.ok().build();
}
Also used : InternalServerErrorException(javax.ws.rs.InternalServerErrorException) Stream(org.graylog2.plugin.streams.Stream) EmailAlarmCallback(org.graylog2.alarmcallbacks.EmailAlarmCallback) AlarmCallback(org.graylog2.plugin.alarms.callbacks.AlarmCallback) AbstractAlertCondition(org.graylog2.alerts.AbstractAlertCondition) DummyAlertCondition(org.graylog2.alerts.types.DummyAlertCondition) TransportConfigurationException(org.graylog2.plugin.alarms.transports.TransportConfigurationException) NotFoundException(org.graylog2.database.NotFoundException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) EmailException(org.apache.commons.mail.EmailException) AlarmCallbackConfiguration(org.graylog2.alarmcallbacks.AlarmCallbackConfiguration) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Timed(com.codahale.metrics.annotation.Timed) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent)

Example 27 with InternalServerErrorException

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

the class BlacklistSourceResource method create.

@POST
@Timed
@ApiOperation(value = "Create a blacklist filter", notes = "It can take up to a second until the change is applied")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@AuditEvent(type = AuditEventTypes.BLACKLIST_FILTER_CREATE)
public Response create(@ApiParam(name = "filterEntry", required = true) @Valid @NotNull FilterDescription filterDescription) throws ValidationException {
    checkPermission(RestPermissions.BLACKLISTENTRY_CREATE);
    // force the user name to be consistent with the requesting user
    final User currentUser = getCurrentUser();
    if (currentUser == null) {
        throw new InternalServerErrorException("Could not load user.");
    }
    filterDescription.creatorUserId = currentUser.getName();
    final FilterDescription savedFilter = filterService.save(filterDescription);
    clusterEventBus.post(FilterDescriptionUpdateEvent.create(savedFilter._id.toHexString()));
    final URI filterUri = getUriBuilderToSelf().path(BlacklistSourceResource.class).path("{filterId}").build(savedFilter._id);
    return Response.created(filterUri).entity(savedFilter).build();
}
Also used : User(org.graylog2.plugin.database.users.User) FilterDescription(org.graylog2.filters.blacklist.FilterDescription) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) 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 28 with InternalServerErrorException

use of javax.ws.rs.InternalServerErrorException 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);
    }
}
Also used : QueryParser(org.apache.lucene.queryparser.classic.QueryParser) QueryParseError(org.graylog2.rest.resources.search.responses.QueryParseError) StandardAnalyzer(org.apache.lucene.analysis.standard.StandardAnalyzer) BadRequestException(javax.ws.rs.BadRequestException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) Token(org.apache.lucene.queryparser.classic.Token) ParseException(org.apache.lucene.queryparser.classic.ParseException)

Example 29 with InternalServerErrorException

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

the class ClusterDeflectorResource method getDeflectorResource.

private RemoteDeflectorResource getDeflectorResource() {
    final Node master = findMasterNode();
    final Function<String, Optional<RemoteDeflectorResource>> remoteInterfaceProvider = createRemoteInterfaceProvider(RemoteDeflectorResource.class);
    final Optional<RemoteDeflectorResource> deflectorResource = remoteInterfaceProvider.apply(master.getNodeId());
    return deflectorResource.orElseThrow(() -> new InternalServerErrorException("Unable to get remote deflector resource."));
}
Also used : RemoteDeflectorResource(org.graylog2.shared.rest.resources.system.RemoteDeflectorResource) Optional(java.util.Optional) Node(org.graylog2.cluster.Node) InternalServerErrorException(javax.ws.rs.InternalServerErrorException)

Example 30 with InternalServerErrorException

use of javax.ws.rs.InternalServerErrorException in project keywhiz by square.

the class SecretDeliveryResource method getSecret.

/**
   * Retrieve Secret by name
   *
   * @excludeParams client
   * @param secretName the name of the Secret to retrieve
   *
   * @description Returns a single Secret if found
   * @responseMessage 200 Found and retrieved Secret with given name
   * @responseMessage 403 Secret is not assigned to Client
   * @responseMessage 404 Secret with given name not found
   * @responseMessage 500 Secret response could not be generated for given Secret
   */
@Timed
@ExceptionMetered
@GET
public SecretDeliveryResponse getSecret(@NotEmpty @PathParam("secretName") String secretName, @Auth Client client) {
    Optional<SanitizedSecret> sanitizedSecret = aclDAO.getSanitizedSecretFor(client, secretName);
    Optional<Secret> secret = secretController.getSecretByName(secretName);
    if (!sanitizedSecret.isPresent()) {
        boolean clientExists = clientDAO.getClient(client.getName()).isPresent();
        boolean secretExists = secret.isPresent();
        if (clientExists && secretExists) {
            throw new ForbiddenException(format("Access denied: %s at '%s' by '%s'", client.getName(), "/secret/" + secretName, client));
        } else {
            if (clientExists) {
                logger.info("Client {} requested unknown secret {}", client.getName(), secretName);
            }
            throw new NotFoundException();
        }
    }
    logger.info("Client {} granted access to {}.", client.getName(), secretName);
    try {
        return SecretDeliveryResponse.fromSecret(secret.get());
    } catch (IllegalArgumentException e) {
        logger.error(format("Failed creating response for secret %s", secretName), e);
        throw new InternalServerErrorException();
    }
}
Also used : Secret(keywhiz.api.model.Secret) SanitizedSecret(keywhiz.api.model.SanitizedSecret) SanitizedSecret(keywhiz.api.model.SanitizedSecret) ForbiddenException(javax.ws.rs.ForbiddenException) NotFoundException(javax.ws.rs.NotFoundException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Aggregations

InternalServerErrorException (javax.ws.rs.InternalServerErrorException)36 ApiOperation (io.swagger.annotations.ApiOperation)14 Timed (com.codahale.metrics.annotation.Timed)13 Path (javax.ws.rs.Path)13 GET (javax.ws.rs.GET)9 NotFoundException (javax.ws.rs.NotFoundException)9 IOException (java.io.IOException)8 BadRequestException (javax.ws.rs.BadRequestException)8 Produces (javax.ws.rs.Produces)6 ApiResponses (io.swagger.annotations.ApiResponses)5 POST (javax.ws.rs.POST)5 JAXBException (javax.xml.bind.JAXBException)5 AuditEvent (org.graylog2.audit.jersey.AuditEvent)5 JsonMappingException (com.fasterxml.jackson.databind.JsonMappingException)4 Consumes (javax.ws.rs.Consumes)4 IndexManagementConfig (org.graylog2.indexer.management.IndexManagementConfig)4 SchemaFactoryWrapper (com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper)3 Charset (java.nio.charset.Charset)3 HashMap (java.util.HashMap)3 RequiresPermissions (org.apache.shiro.authz.annotation.RequiresPermissions)3