类javax.ws.rs.NotAcceptableException源码实例Demo

下面列出了怎么用javax.ws.rs.NotAcceptableException的API类实例代码及写法,或者点击链接到github查看源代码。

@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"));
}
 
源代码2 项目: trellis   文件: HttpUtils.java
/**
 * 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();
}
 
源代码3 项目: sinavi-jfw   文件: NotAcceptableExceptionMapper.java
/**
 * {@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();
}
 
源代码4 项目: liberty-bikes   文件: GameRoundService.java
@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();
}
 
源代码5 项目: trellis   文件: PutHandler.java
/**
 * 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);
}
 
源代码6 项目: trellis   文件: HttpUtilsTest.java
@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");
}
 
源代码7 项目: trellis   文件: GetHandlerTest.java
@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);
    }
}
 
源代码8 项目: container   文件: LoggingExceptionMapper.java
@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();
}
 
源代码9 项目: cxf   文件: JAXRSClientServerBookTest.java
@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());
    }
}
 
源代码10 项目: cxf   文件: JAXRSClientServerBookTest.java
@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());
    }
}
 
/**
 * 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;
}
 
/**
 * 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;
}
 
源代码13 项目: trellis   文件: TrellisHttpResource.java
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);
}
 
源代码14 项目: che   文件: WebApplicationExceptionMapper.java
@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();
  }
}
 
@Override
public Response toResponse(NotAcceptableException exception) {
    return ExceptionMapperUtils.buildResponse(exception, Response.Status.NOT_ACCEPTABLE);
}
 
@GET
public EmptyTest exception() {
    throw new NotAcceptableException();
}
 
源代码17 项目: cxf   文件: SpecExceptions.java
public static NotAcceptableException toNotAcceptableException(Throwable cause, Response response) {

        return new NotAcceptableException(checkResponse(response, 406), cause);
    }
 
 类所在包
 同包方法