javax.ws.rs.NotAcceptableException Java Examples

The following examples show how to use javax.ws.rs.NotAcceptableException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DefaultJerseyTagsProviderTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("serial")
public void exceptionsAreMappedCorrectly() {
    assertThat(tagsProvider.httpRequestTags(
        event(500, new IllegalArgumentException(), "/app", (String[]) null)))
        .containsExactlyInAnyOrder(tagsFrom("/app", 500, "IllegalArgumentException", "SERVER_ERROR"));
    assertThat(tagsProvider.httpRequestTags(event(500,
        new IllegalArgumentException(new NullPointerException()), "/app", (String[]) null)))
        .containsExactlyInAnyOrder(tagsFrom("/app", 500, "NullPointerException", "SERVER_ERROR"));
    assertThat(tagsProvider.httpRequestTags(
        event(406, new NotAcceptableException(), "/app", (String[]) null)))
        .containsExactlyInAnyOrder(tagsFrom("/app", 406, "NotAcceptableException", "CLIENT_ERROR"));
    assertThat(tagsProvider.httpRequestTags(
        event(500, new Exception("anonymous") { }, "/app", (String[]) null)))
        .containsExactlyInAnyOrder(tagsFrom("/app", 500, "io.micrometer.jersey2.server.DefaultJerseyTagsProviderTest$1", "SERVER_ERROR"));
}
 
Example #2
Source File: HttpUtils.java    From trellis with Apache License 2.0 6 votes vote down vote up
/**
 * Given a list of acceptable media types, get an RDF syntax.
 *
 * @param ioService the I/O service
 * @param acceptableTypes the types from HTTP headers
 * @param mimeType an additional "default" mimeType to match
 * @return an RDFSyntax or, in the case of binaries, null
 * @throws NotAcceptableException if no acceptable syntax is available
 */
public static RDFSyntax getSyntax(final IOService ioService, final List<MediaType> acceptableTypes,
        final String mimeType) {
    if (acceptableTypes.isEmpty()) {
        return mimeType != null ? null : TURTLE;
    }
    final MediaType mt = mimeType != null ? MediaType.valueOf(mimeType) : null;
    for (final MediaType type : acceptableTypes) {
        if (type.isCompatible(mt)) {
            return null;
        }
        final RDFSyntax syntax = ioService.supportedReadSyntaxes().stream()
            .filter(s -> MediaType.valueOf(s.mediaType()).isCompatible(type))
            .findFirst().orElse(null);
        if (syntax != null) {
            return syntax;
        }
    }
    LOGGER.debug("Valid syntax not found among {} or {}", acceptableTypes, mimeType);
    throw new NotAcceptableException();
}
 
Example #3
Source File: NotAcceptableExceptionMapper.java    From sinavi-jfw with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Response toResponse(final NotAcceptableException exception) {
    if (L.isDebugEnabled()) {
        L.debug(R.getString("D-REST-JERSEY-MAPPER#0005"));
    }
    ErrorMessage error = ErrorMessages.create(exception)
        .code(ErrorCode.NOT_ACCEPTABLE.code())
        .resolve()
        .get();
    L.warn(error.log(), exception);
    return Response.status(exception.getResponse().getStatusInfo())
        .entity(error)
        .type(MediaType.APPLICATION_JSON)
        .build();
}
 
Example #4
Source File: GameRoundService.java    From liberty-bikes with Eclipse Public License 1.0 5 votes vote down vote up
@GET
@Path("/available")
public String getAvailableRound() {
    if (isSingleParty)
        throw new NotAcceptableException("Cannot call this endpoint when game service is in single party mode");

    Optional<GameRound> availableRound = allRounds.values()
                    .stream()
                    .filter(r -> r.isOpen())
                    .findFirst();
    if (availableRound.isPresent())
        return availableRound.get().id;
    else
        return createRound();
}
 
Example #5
Source File: ClientAttributeCertificateResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Generate a new keypair and certificate, and get the private key file
 *
 * Generates a keypair and certificate and serves the private key in a specified keystore format.
 * Only generated public certificate is saved in Keycloak DB - the private key is not.
 *
 * @param config Keystore configuration as JSON
 * @return
 */
@POST
@NoCache
@Path("/generate-and-download")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Consumes(MediaType.APPLICATION_JSON)
public byte[] generateAndGetKeystore(final KeyStoreConfig config) {
    auth.clients().requireConfigure(client);

    if (config.getFormat() != null && !config.getFormat().equals("JKS") && !config.getFormat().equals("PKCS12")) {
        throw new NotAcceptableException("Only support jks or pkcs12 format.");
    }
    if (config.getKeyPassword() == null) {
        throw new ErrorResponseException("password-missing", "Need to specify a key password for jks generation and download", Response.Status.BAD_REQUEST);
    }
    if (config.getStorePassword() == null) {
        throw new ErrorResponseException("password-missing", "Need to specify a store password for jks generation and download", Response.Status.BAD_REQUEST);
    }

    CertificateRepresentation info = KeycloakModelUtils.generateKeyPairCertificate(client.getClientId());
    byte[] rtn = getKeystore(config, info.getPrivateKey(), info.getCertificate());

    info.setPrivateKey(null);

    CertificateInfoHelper.updateClientModelCertificateInfo(client, info, attributePrefix);

    adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).representation(info).success();
    return rtn;
}
 
Example #6
Source File: ClientAttributeCertificateResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Get a keystore file for the client, containing private key and public certificate
 *
 * @param config Keystore configuration as JSON
 * @return
 */
@POST
@NoCache
@Path("/download")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Consumes(MediaType.APPLICATION_JSON)
public byte[] getKeystore(final KeyStoreConfig config) {
    auth.clients().requireView(client);

    if (config.getFormat() != null && !config.getFormat().equals("JKS") && !config.getFormat().equals("PKCS12")) {
        throw new NotAcceptableException("Only support jks or pkcs12 format.");
    }

    CertificateRepresentation info = CertificateInfoHelper.getCertificateFromClient(client, attributePrefix);
    String privatePem = info.getPrivateKey();
    String certPem = info.getCertificate();

    if (privatePem == null && certPem == null) {
        throw new NotFoundException("keypair not generated for client");
    }
    if (privatePem != null && config.getKeyPassword() == null) {
        throw new ErrorResponseException("password-missing", "Need to specify a key password for jks download", Response.Status.BAD_REQUEST);
    }
    if (config.getStorePassword() == null) {
        throw new ErrorResponseException("password-missing", "Need to specify a store password for jks download", Response.Status.BAD_REQUEST);
    }

    byte[] rtn = getKeystore(config, privatePem, certPem);
    return rtn;
}
 
Example #7
Source File: JAXRSClientServerBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testServerWebApplicationExceptionXMLWithProxy() throws Exception {
    BookStore proxy = JAXRSClientFactory.create("http://localhost:" + PORT,
                                                BookStore.class);
    try {
        proxy.throwExceptionXML();
        fail("Exception expected");
    } catch (NotAcceptableException ex) {
        assertEquals(406, ex.getResponse().getStatus());
        Book exBook = ex.getResponse().readEntity(Book.class);
        assertEquals("Exception", exBook.getName());
        assertEquals(999L, exBook.getId());
    }
}
 
Example #8
Source File: JAXRSClientServerBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testServerWebApplicationExceptionXML() throws Exception {
    WebClient wc = WebClient.create("http://localhost:" + PORT + "/bookstore/webappexceptionXML");
    wc.accept("application/xml");
    try {
        wc.get(Book.class);
        fail("Exception expected");
    } catch (NotAcceptableException ex) {
        assertEquals(406, ex.getResponse().getStatus());
        Book exBook = ex.getResponse().readEntity(Book.class);
        assertEquals("Exception", exBook.getName());
        assertEquals(999L, exBook.getId());
    }
}
 
Example #9
Source File: LoggingExceptionMapper.java    From container with Apache License 2.0 5 votes vote down vote up
@Override
public Response toResponse(Throwable exception) {
    logger.error("An exception was not handled: " + exception.toString());
    if (exception instanceof NotFoundException) {
        return Response.status(Status.NOT_FOUND).build();
    } else if (exception instanceof NotAcceptableException) {
        return Response.status(Status.NOT_ACCEPTABLE).build();
    }

    return Response.serverError().entity(exception).build();
}
 
Example #10
Source File: GetHandlerTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testNotAcceptableLdprs() {
    when(mockTrellisRequest.getAcceptableMediaTypes()).thenReturn(singletonList(APPLICATION_JSON_TYPE));

    final GetConfiguration config = new GetConfiguration(false, true, true, null, baseUrl);
    final GetHandler handler = new GetHandler(mockTrellisRequest, mockBundler, extensions, config);

    try (final Response res = assertThrows(NotAcceptableException.class, () -> handler.initialize(mockResource),
            "No error thrown when given an unaccepable media type!").getResponse()) {
        assertEquals(NOT_ACCEPTABLE, res.getStatusInfo(), ERR_RESPONSE_CODE);
    }
}
 
Example #11
Source File: HttpUtilsTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testGetSyntaxError() {
    final List<MediaType> types = asList(APPLICATION_JSON_TYPE, TEXT_XML_TYPE);

    assertThrows(NotAcceptableException.class, () -> HttpUtils.getSyntax(ioService, types, null),
            "Not-Acceptable Exception should be thrown when nothing matches");
}
 
Example #12
Source File: PutHandler.java    From trellis with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the response handler.
 * @param parent the parent resource
 * @param resource the resource
 * @return the response builder
 */
public ResponseBuilder initialize(final Resource parent, final Resource resource) {
    setResource(exists(resource) ? resource : null);

    // Check the cache
    if (getResource() != null) {
        final Instant modified = getResource().getModified();

        // Check the cache
        checkRequiredPreconditions(preconditionRequired, getRequest().getHeaders().getFirst(IF_MATCH),
                getRequest().getHeaders().getFirst(IF_UNMODIFIED_SINCE));
        checkCache(modified, generateEtag(getResource()));
    }

    // One cannot put binaries into extension graphs
    if (getExtensionGraphName() != null && rdfSyntax == null) {
        throw new NotAcceptableException();
    }

    // For operations that modify resources, the parent resource may need to be updated via
    // ResourceService::touch. This allows us to keep a reference to the parent resource
    // since it has already been looked up. However, access to the parent resource is not necessary
    // if, in the case of creation/deletion, PUT operations are configured as 'uncontained' (not the default)
    // or, in the case of updates, the resource has no parent container.
    // Here, the `resource` object is used directly rather than doing a null check on `getResource()` since
    // in this case, they amount to the same thing.
    if (!createUncontained || resource.getContainer().isPresent()) {
        setParent(parent);
    }
    return status(NO_CONTENT);
}
 
Example #13
Source File: NotAcceptableExceptionMapper.java    From hawkular-metrics with Apache License 2.0 4 votes vote down vote up
@Override
public Response toResponse(NotAcceptableException exception) {
    return ExceptionMapperUtils.buildResponse(exception, Response.Status.NOT_ACCEPTABLE);
}
 
Example #14
Source File: WebApplicationExceptionMapper.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Response toResponse(WebApplicationException exception) {

  ServiceError error = newDto(ServiceError.class).withMessage(exception.getMessage());

  if (exception instanceof BadRequestException) {
    return Response.status(Response.Status.BAD_REQUEST)
        .entity(DtoFactory.getInstance().toJson(error))
        .type(MediaType.APPLICATION_JSON)
        .build();
  } else if (exception instanceof ForbiddenException) {
    return Response.status(Response.Status.FORBIDDEN)
        .entity(DtoFactory.getInstance().toJson(error))
        .type(MediaType.APPLICATION_JSON)
        .build();
  } else if (exception instanceof NotFoundException) {
    return Response.status(Response.Status.NOT_FOUND)
        .entity(DtoFactory.getInstance().toJson(error))
        .type(MediaType.APPLICATION_JSON)
        .build();
  } else if (exception instanceof NotAuthorizedException) {
    return Response.status(Response.Status.UNAUTHORIZED)
        .entity(DtoFactory.getInstance().toJson(error))
        .type(MediaType.APPLICATION_JSON)
        .build();
  } else if (exception instanceof NotAcceptableException) {
    return Response.status(Status.NOT_ACCEPTABLE)
        .entity(DtoFactory.getInstance().toJson(error))
        .type(MediaType.APPLICATION_JSON)
        .build();
  } else if (exception instanceof NotAllowedException) {
    return Response.status(Status.METHOD_NOT_ALLOWED)
        .entity(DtoFactory.getInstance().toJson(error))
        .type(MediaType.APPLICATION_JSON)
        .build();
  } else if (exception instanceof NotSupportedException) {
    return Response.status(Status.UNSUPPORTED_MEDIA_TYPE)
        .entity(DtoFactory.getInstance().toJson(error))
        .type(MediaType.APPLICATION_JSON)
        .build();
  } else {
    return Response.serverError()
        .entity(DtoFactory.getInstance().toJson(error))
        .type(MediaType.APPLICATION_JSON)
        .build();
  }
}
 
Example #15
Source File: NotAcceptableExceptionResourceTest.java    From sinavi-jfw with Apache License 2.0 4 votes vote down vote up
@GET
public EmptyTest exception() {
    throw new NotAcceptableException();
}
 
Example #16
Source File: TrellisHttpResource.java    From trellis with Apache License 2.0 4 votes vote down vote up
private CompletionStage<ResponseBuilder> fetchResource(final TrellisRequest req) {
    final String urlBase = getBaseUrl(req);
    final IRI identifier = buildTrellisIdentifier(req.getPath());
    final GetConfiguration config = new GetConfiguration(req.getVersion() != null,
            weakEtags, includeMementoDates, defaultJsonLdProfile, urlBase);
    final GetHandler getHandler = new GetHandler(req, trellis, extensions, config);

    // Fetch a memento
    if (req.getVersion() != null) {
        LOGGER.debug("Getting versioned resource: {}", req.getVersion());
        return trellis.getMementoService().get(identifier, req.getVersion().getInstant())
            .thenApply(getHandler::initialize).thenApply(getHandler::standardHeaders)
            .thenCombine(trellis.getMementoService().mementos(identifier), getHandler::addMementoHeaders)
            .thenCompose(getHandler::getRepresentation);

    // Fetch a timemap
    } else if (TIMEMAP.equals(req.getExt())) {
        LOGGER.debug("Getting timemap resource: {}", req.getPath());
        return trellis.getResourceService().get(identifier)
            .thenCombine(trellis.getMementoService().mementos(identifier), (res, mementos) -> {
                if (MISSING_RESOURCE.equals(res)) {
                    throw new NotFoundException();
                }
                return new MementoResource(trellis, includeMementoDates).getTimeMapBuilder(mementos, req, urlBase);
            });

    // Fetch a timegate
    } else if (req.getDatetime() != null) {
        LOGGER.debug("Getting timegate resource: {}", req.getDatetime().getInstant());
        return trellis.getMementoService().get(identifier, req.getDatetime().getInstant())
            .thenCombine(trellis.getMementoService().mementos(identifier), (res, mementos) -> {
                if (MISSING_RESOURCE.equals(res)) {
                    throw new NotAcceptableException();
                }
                return new MementoResource(trellis, includeMementoDates).getTimeGateBuilder(mementos, req, urlBase);
            });
    }

    // Fetch the current state of the resource
    LOGGER.debug("Getting resource at: {}", identifier);
    return trellis.getResourceService().get(identifier).thenApply(getHandler::initialize)
        .thenApply(getHandler::standardHeaders)
        .thenCombine(trellis.getMementoService().mementos(identifier), getHandler::addMementoHeaders)
        .thenCompose(getHandler::getRepresentation);
}
 
Example #17
Source File: SpecExceptions.java    From cxf with Apache License 2.0 2 votes vote down vote up
public static NotAcceptableException toNotAcceptableException(Throwable cause, Response response) {

        return new NotAcceptableException(checkResponse(response, 406), cause);
    }