Search in sources :

Example 1 with InternalServerErrorException

use of javax.ws.rs.InternalServerErrorException in project dropwizard by dropwizard.

the class AuthFilter method authenticate.

/**
     * Authenticates a request with user credentials and setup the security context.
     *
     * @param requestContext the context of the request
     * @param credentials    the user credentials
     * @param scheme         the authentication scheme; one of {@code BASIC_AUTH, FORM_AUTH, CLIENT_CERT_AUTH, DIGEST_AUTH}.
     *                       See {@link SecurityContext}
     * @return {@code true}, if the request is authenticated, otherwise {@code false}
     */
protected boolean authenticate(ContainerRequestContext requestContext, C credentials, String scheme) {
    try {
        if (credentials == null) {
            return false;
        }
        final Optional<P> principal = authenticator.authenticate(credentials);
        if (!principal.isPresent()) {
            return false;
        }
        final SecurityContext securityContext = requestContext.getSecurityContext();
        final boolean secure = securityContext != null && securityContext.isSecure();
        requestContext.setSecurityContext(new SecurityContext() {

            @Override
            public Principal getUserPrincipal() {
                return principal.get();
            }

            @Override
            public boolean isUserInRole(String role) {
                return authorizer.authorize(principal.get(), role);
            }

            @Override
            public boolean isSecure() {
                return secure;
            }

            @Override
            public String getAuthenticationScheme() {
                return scheme;
            }
        });
        return true;
    } catch (AuthenticationException e) {
        logger.warn("Error authenticating credentials", e);
        throw new InternalServerErrorException();
    }
}
Also used : SecurityContext(javax.ws.rs.core.SecurityContext) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) Principal(java.security.Principal)

Example 2 with InternalServerErrorException

use of javax.ws.rs.InternalServerErrorException in project jersey by jersey.

the class JerseyInvocation method convertToException.

private ProcessingException convertToException(final Response response) {
    try {
        // Buffer and close entity input stream (if any) to prevent
        // leaking connections (see JERSEY-2157).
        response.bufferEntity();
        final WebApplicationException webAppException;
        final int statusCode = response.getStatus();
        final Response.Status status = Response.Status.fromStatusCode(statusCode);
        if (status == null) {
            final Response.Status.Family statusFamily = response.getStatusInfo().getFamily();
            webAppException = createExceptionForFamily(response, statusFamily);
        } else {
            switch(status) {
                case BAD_REQUEST:
                    webAppException = new BadRequestException(response);
                    break;
                case UNAUTHORIZED:
                    webAppException = new NotAuthorizedException(response);
                    break;
                case FORBIDDEN:
                    webAppException = new ForbiddenException(response);
                    break;
                case NOT_FOUND:
                    webAppException = new NotFoundException(response);
                    break;
                case METHOD_NOT_ALLOWED:
                    webAppException = new NotAllowedException(response);
                    break;
                case NOT_ACCEPTABLE:
                    webAppException = new NotAcceptableException(response);
                    break;
                case UNSUPPORTED_MEDIA_TYPE:
                    webAppException = new NotSupportedException(response);
                    break;
                case INTERNAL_SERVER_ERROR:
                    webAppException = new InternalServerErrorException(response);
                    break;
                case SERVICE_UNAVAILABLE:
                    webAppException = new ServiceUnavailableException(response);
                    break;
                default:
                    final Response.Status.Family statusFamily = response.getStatusInfo().getFamily();
                    webAppException = createExceptionForFamily(response, statusFamily);
            }
        }
        return new ResponseProcessingException(response, webAppException);
    } catch (final Throwable t) {
        return new ResponseProcessingException(response, LocalizationMessages.RESPONSE_TO_EXCEPTION_CONVERSION_FAILED(), t);
    }
}
Also used : ForbiddenException(javax.ws.rs.ForbiddenException) WebApplicationException(javax.ws.rs.WebApplicationException) NotAllowedException(javax.ws.rs.NotAllowedException) NotFoundException(javax.ws.rs.NotFoundException) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) ServiceUnavailableException(javax.ws.rs.ServiceUnavailableException) Response(javax.ws.rs.core.Response) NotAcceptableException(javax.ws.rs.NotAcceptableException) BadRequestException(javax.ws.rs.BadRequestException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) ResponseProcessingException(javax.ws.rs.client.ResponseProcessingException) NotSupportedException(javax.ws.rs.NotSupportedException)

Example 3 with InternalServerErrorException

use of javax.ws.rs.InternalServerErrorException in project jersey by jersey.

the class AbstractCollectionJaxbProvider method writeTo.

@Override
public final void writeTo(Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
    try {
        final Collection c = (type.isArray()) ? Arrays.asList((Object[]) t) : (Collection) t;
        final Class elementType = getElementClass(type, genericType);
        final Charset charset = getCharset(mediaType);
        final String charsetName = charset.name();
        final Marshaller m = getMarshaller(elementType, mediaType);
        m.setProperty(Marshaller.JAXB_FRAGMENT, true);
        if (charset != UTF8) {
            m.setProperty(Marshaller.JAXB_ENCODING, charsetName);
        }
        setHeader(m, annotations);
        writeCollection(elementType, c, mediaType, charset, m, entityStream);
    } catch (JAXBException ex) {
        throw new InternalServerErrorException(ex);
    }
}
Also used : Marshaller(javax.xml.bind.Marshaller) JAXBException(javax.xml.bind.JAXBException) Collection(java.util.Collection) Charset(java.nio.charset.Charset) InternalServerErrorException(javax.ws.rs.InternalServerErrorException)

Example 4 with InternalServerErrorException

use of javax.ws.rs.InternalServerErrorException in project jersey by jersey.

the class AbstractJaxbElementProvider method readFrom.

@Override
public final JAXBElement<?> readFrom(Class<JAXBElement<?>> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream inputStream) throws IOException {
    final EntityInputStream entityStream = EntityInputStream.create(inputStream);
    if (entityStream.isEmpty()) {
        throw new NoContentException(LocalizationMessages.ERROR_READING_ENTITY_MISSING());
    }
    final ParameterizedType pt = (ParameterizedType) genericType;
    final Class ta = (Class) pt.getActualTypeArguments()[0];
    try {
        return readFrom(ta, mediaType, getUnmarshaller(ta, mediaType), entityStream);
    } catch (UnmarshalException ex) {
        throw new BadRequestException(ex);
    } catch (JAXBException ex) {
        throw new InternalServerErrorException(ex);
    }
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) UnmarshalException(javax.xml.bind.UnmarshalException) JAXBException(javax.xml.bind.JAXBException) BadRequestException(javax.ws.rs.BadRequestException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) EntityInputStream(org.glassfish.jersey.message.internal.EntityInputStream) NoContentException(javax.ws.rs.core.NoContentException)

Example 5 with InternalServerErrorException

use of javax.ws.rs.InternalServerErrorException in project pulsar by yahoo.

the class AuthenticatedProducerConsumerTest method testInternalServerExceptionOnLookup.

/**
     * verifies that topicLookup/PartitionMetadataLookup gives InternalServerError(500) instead 401(auth_failed) on
     * unknown-exception failure
     * 
     * @throws Exception
     */
@Test
public void testInternalServerExceptionOnLookup() throws Exception {
    log.info("-- Starting {} test --", methodName);
    Map<String, String> authParams = new HashMap<>();
    authParams.put("tlsCertFile", TLS_CLIENT_CERT_FILE_PATH);
    authParams.put("tlsKeyFile", TLS_CLIENT_KEY_FILE_PATH);
    Authentication authTls = new AuthenticationTls();
    authTls.configure(authParams);
    internalSetup(authTls);
    admin.clusters().createCluster("use", new ClusterData(brokerUrl.toString(), brokerUrlTls.toString(), "pulsar://localhost:" + BROKER_PORT, "pulsar+ssl://localhost:" + BROKER_PORT_TLS));
    admin.properties().createProperty("my-property", new PropertyAdmin(Lists.newArrayList("appid1", "appid2"), Sets.newHashSet("use")));
    String namespace = "my-property/use/my-ns";
    admin.namespaces().createNamespace(namespace);
    String destination = "persistent://" + namespace + "1/topic1";
    // this will cause NPE and it should throw 500
    mockZookKeeper.shutdown();
    pulsar.getConfiguration().setSuperUserRoles(Sets.newHashSet());
    try {
        admin.persistentTopics().getPartitionedTopicMetadata(destination);
    } catch (PulsarAdminException e) {
        Assert.assertTrue(e.getCause() instanceof InternalServerErrorException);
    }
    try {
        admin.lookups().lookupDestination(destination);
    } catch (PulsarAdminException e) {
        Assert.assertTrue(e.getCause() instanceof InternalServerErrorException);
    }
}
Also used : AuthenticationTls(com.yahoo.pulsar.client.impl.auth.AuthenticationTls) ClusterData(com.yahoo.pulsar.common.policies.data.ClusterData) PropertyAdmin(com.yahoo.pulsar.common.policies.data.PropertyAdmin) HashMap(java.util.HashMap) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) PulsarAdminException(com.yahoo.pulsar.client.admin.PulsarAdminException) Test(org.testng.annotations.Test)

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