下面列出了怎么用javax.ws.rs.ProcessingException的API类实例代码及写法,或者点击链接到github查看源代码。
public static PipelineConfigurationJson getEdgePipeline(String edgeHttpUrl, String pipelineId) throws PipelineException {
Response response = null;
try {
response = ClientBuilder.newClient()
.target(edgeHttpUrl + "/rest/v1/pipeline/" + pipelineId)
.request()
.get();
if (response.getStatus() == Response.Status.OK.getStatusCode()) {
return response.readEntity(PipelineConfigurationJson.class);
} else {
return null;
}
} catch (ProcessingException ex) {
if (ex.getCause() instanceof ConnectException) {
throw new PipelineException(ContainerError.CONTAINER_01602, edgeHttpUrl, ex);
}
throw ex;
}
finally {
if (response != null) {
response.close();
}
}
}
@Override
public boolean exitWaiting(T waitObject) {
String name = waitObject.getName();
try {
StackStatusV4Response stackStatus = waitObject.getStackEndpoint().getStatusByName(waitObject.getWorkspaceId(), name);
Map<String, Status> actualStatuses = Map.of("status", stackStatus.getStatus(), "clusterStatus", stackStatus.getClusterStatus());
if (isDeleteFailed(actualStatuses)) {
return true;
}
return waitObject.isFailed(actualStatuses);
} catch (ProcessingException clientException) {
LOGGER.error("Exit waiting! Failed to get cluster due to API client exception: {}", clientException.getMessage(), clientException);
} catch (Exception e) {
LOGGER.error("Exit waiting! Failed to get cluster, because of: {}", e.getMessage(), e);
return true;
}
return false;
}
@Override
public boolean exitWaiting(T waitObject) {
String crn = waitObject.getCrn();
try {
DetailedEnvironmentResponse environment = waitObject.getEndpoint().getByCrn(crn);
EnvironmentStatus status = environment.getEnvironmentStatus();
if (status.equals(DELETE_FAILED)) {
return true;
}
return status.isFailed();
} catch (ProcessingException clientException) {
LOGGER.error("Exit waiting! Failed to get environment due to API client exception: {}", clientException.getMessage(), clientException);
} catch (Exception e) {
LOGGER.error("Exit waiting! Failed to get environment, because of: {}", e.getMessage(), e);
return true;
}
return false;
}
@Test(expected = FailoverFailedException.class)
public void testSequentialStrategyUnavailableAlternatives() throws Exception {
FailoverFeature feature = getFeature(false,
"http://localhost:" + NON_PORT + "/non-existent",
"http://localhost:" + NON_PORT + "/non-existent2");
final BookStore bookStore = getBookStore(
"http://localhost:" + NON_PORT + "/non-existent", feature);
// First iteration is going to open all circuit breakers.
// Second iteration should not call any URL as all targets are not available.
for (int i = 0; i < 2; ++i) {
try {
bookStore.getBook(1);
fail("Exception expected");
} catch (ProcessingException ex) {
if (ex.getCause() instanceof FailoverFailedException) {
throw (FailoverFailedException) ex.getCause();
}
}
}
}
@Override
public Response execute(Request request) {
if (request.hijackedInput() != null) {
throw new UnsupportedOperationException("Does not support hijacking");
}
String url = sanitizeUrl(originalUri).toString();
if (url.endsWith("/") && request.path().startsWith("/")) {
url = url.substring(0, url.length() - 1);
}
Invocation.Builder builder = client.target(url + request.path()).request();
request.headers().forEach(builder::header);
try {
return new JerseyResponse(
builder.build(request.method(), toEntity(request)).invoke()
);
} catch (ProcessingException e) {
if (e.getCause() instanceof DockerException) {
throw (DockerException) e.getCause();
}
throw e;
}
}
@Override
public int delete(DeviceId device, String request, InputStream payload, MediaType mediaType) {
WebTarget wt = getWebTarget(device, request);
// FIXME: do we need to delete an entry by enclosing data in DELETE
// request?
// wouldn't it be nice to use PUT to implement the similar concept?
Response response = null;
try {
response = wt.request(mediaType).delete();
} catch (ProcessingException procEx) {
log.error("Cannot issue DELETE {} request on device {}", request, device);
return Status.SERVICE_UNAVAILABLE.getStatusCode();
}
return response.getStatus();
}
@Override
public boolean exitWaiting(T waitObject) {
String name = waitObject.getName();
try {
SdxClusterResponse sdx = waitObject.getEndpoint().get(name);
if (sdx == null) {
LOGGER.info("'{}' datalake was not found. Exit waiting!", name);
return true;
}
SdxClusterStatusResponse status = sdx.getStatus();
if (status.equals(PROVISIONING_FAILED)) {
return true;
}
return waitObject.isFailed(status);
} catch (ProcessingException clientException) {
LOGGER.error("Exit waiting! Failed to get datalake due to API client exception: {}", clientException.getMessage(), clientException);
} catch (Exception e) {
LOGGER.error("Exit waiting! Failed to get datalake, because of: {}", e.getMessage(), e);
return true;
}
return false;
}
private Optional<ImageStatus> handleImageNotFound(OSClient<?> osClient, String name) {
LOGGER.error("OpenStack image: {} not found", name);
List<? extends BasicResource> allImages;
try {
allImages = osClient.imagesV2().list();
} catch (ProcessingException e) {
LOGGER.debug("Exception occured during listing openstack images on V2 API. Falling back to V1 API.", e);
allImages = osClient.images().list();
}
if (allImages != null) {
for (BasicResource image : allImages) {
LOGGER.debug("Available images: {}, entry: {}", image.getName(), image);
}
}
LOGGER.debug("OpenStack image: {} not found", name);
return Optional.empty();
}
private Response processResponse(Response directDebitResponse) {
DirectDebitSearchResponse response;
try {
response = directDebitResponse.readEntity(DirectDebitSearchResponse.class);
} catch (ProcessingException ex) {
throw new SearchPaymentsException(ex);
}
List<DirectDebitPayment> paymentFromResponse =
response.getPayments()
.stream()
.map(payment -> DirectDebitPayment.from(payment, publicApiUriGenerator))
.collect(Collectors.toList());
HalRepresentation.HalRepresentationBuilder halRepresentation = HalRepresentation.builder()
.addProperty("results", paymentFromResponse);
return Response.ok().entity(paginationDecorator.decoratePagination(halRepresentation, response, PAYMENT_PATH).build().toString()).build();
}
private <T> T readData(Class<T> type, Type genericType, MediaType mediaType) {
if (data == null) {
return null;
}
try {
MessageBodyReader<T> mbr = providers.getMessageBodyReader(type, genericType, EMPTY_ANNOTATIONS,
mediaType);
if (mbr == null) {
throw new ProcessingException("No MessageBodyReader found to handle class type, " + type
+ " using MediaType, " + mediaType);
}
return mbr.readFrom(type, genericType, EMPTY_ANNOTATIONS, mediaType, new MultivaluedHashMap<>(),
new ByteArrayInputStream(data.getBytes()));
} catch (Exception ex) {
throw new ProcessingException(ex);
}
}
@Override
public boolean exitWaiting(T waitObject) {
String name = waitObject.getName();
try {
StackStatusV4Response stackStatus = waitObject.getStackEndpoint().getStatusByName(waitObject.getWorkspaceId(), name);
if (stackStatus == null) {
LOGGER.info("'{}' cluster was not found. Exit waiting!", name);
return true;
}
Map<String, Status> actualStatuses = Map.of("status", stackStatus.getStatus(), "clusterStatus", stackStatus.getClusterStatus());
if (isCreateFailed(actualStatuses)) {
return true;
}
return waitObject.isFailed(actualStatuses);
} catch (ProcessingException clientException) {
LOGGER.error("Exit waiting! Failed to get cluster due to API client exception: {}", clientException.getMessage(), clientException);
} catch (Exception e) {
LOGGER.error("Exit waiting! Failed to get cluster, because of: {}", e.getMessage(), e);
return true;
}
return false;
}
@Override
public boolean exitWaiting(T waitObject) {
String name = waitObject.getName();
try {
SdxClusterResponse sdx = waitObject.getEndpoint().get(name);
SdxClusterStatusResponse status = sdx.getStatus();
if (status.equals(DELETE_FAILED)) {
return true;
}
return waitObject.isFailed(status);
} catch (ProcessingException clientException) {
LOGGER.error("Exit waiting! Failed to get datalake due to API client exception: {}", clientException.getMessage(), clientException);
} catch (Exception e) {
LOGGER.error("Exit waiting! Failed to get datalake, because of: {}", e.getMessage(), e);
return true;
}
return false;
}
@Override
public Collection<SchemaBranch> getSchemaBranches(String schemaName) throws SchemaNotFoundException {
Response response = runRetryableBlock((SchemaRegistryTargets targets) -> {
WebTarget target = targets.schemasTarget.path(encode(schemaName) + "/branches");
try {
return login.doAction(new PrivilegedAction<Response>() {
@Override
public Response run() {
return target.request().get();
}
});
} catch (LoginException | ProcessingException e) {
throw new RegistryRetryableException(e);
}
});
int status = response.getStatus();
if (status == Response.Status.NOT_FOUND.getStatusCode()) {
throw new SchemaNotFoundException(response.readEntity(String.class));
} else if (status != Response.Status.OK.getStatusCode()) {
throw new RuntimeException(response.readEntity(String.class));
}
return parseResponseAsEntities(response.readEntity(String.class), SchemaBranch.class);
}
private void setCommitStatusPendingIfNecessary(Job<?, ?> job, H hook) {
String buildName = PendingBuildsHandler.resolvePendingBuildName(job);
if (StringUtils.isNotBlank(buildName)) {
GitLabClient client = job.getProperty(GitLabConnectionProperty.class).getClient();
BuildStatusUpdate buildStatusUpdate = retrieveBuildStatusUpdate(hook);
try {
if (client == null) {
LOGGER.log(Level.SEVERE, "No GitLab connection configured");
} else {
String ref = StringUtils.removeStart(buildStatusUpdate.getRef(), "refs/tags/");
String targetUrl = DisplayURLProvider.get().getJobURL(job);
client.changeBuildStatus(buildStatusUpdate.getProjectId(), buildStatusUpdate.getSha(),
BuildState.pending, ref, buildName, targetUrl, BuildState.pending.name());
}
} catch (WebApplicationException | ProcessingException e) {
LOGGER.log(Level.SEVERE, "Failed to set build state to pending", e);
}
}
}
protected static final void checkCfpReachable(final String baseUri) {
final boolean testingLive = Boolean.getBoolean("org.tweetwallfx.tests.executeCFPClientLiveTests");
LOG.info("Test of CFP Client against live system is {}.", testingLive ? "enabled" : "disabled");
if (!testingLive) {
return;
}
try {
LOG.info("Checking if CFP is reachable at {}", baseUri);
final Response response = ClientBuilder.newClient()
.target(baseUri)
.request(MediaType.APPLICATION_JSON)
.get();
LOG.info("Received {}", response);
CFP_REACHABLE.set(Response.Status.Family.SUCCESSFUL == response
.getStatusInfo()
.getFamily());
} catch (final ProcessingException pe) {
LogManager.getLogger(CFPClientTestBase.class).error(pe, pe);
}
}
protected void waitForResponseCode(Exchange exchange) {
synchronized (exchange) {
if (getResponseCode(exchange) == null) {
try {
exchange.wait(cfg.getSynchronousTimeout());
} catch (InterruptedException ex) {
// ignore
}
} else {
return;
}
}
if (getResponseCode(exchange) == null) {
throw new ProcessingException("Response timeout");
}
}
@Override
public void handleMessage(Message message) throws Fault {
if (!message.getExchange().isSynchronous()) {
Throwable ex = message.getContent(Exception.class);
if (ex == null) {
ex = message.getExchange().get(Exception.class);
}
if (ex != null) {
JaxrsClientCallback<?> cb = message.getExchange().get(JaxrsClientCallback.class);
if (ex instanceof Fault) {
ex = ex.getCause();
}
ex = ex instanceof ProcessingException ? ex : new ProcessingException(ex);
cb.handleException(message, ex);
}
}
}
@Override
public boolean exitWaiting(T waitObject) {
String crn = waitObject.getCrn();
try {
DatabaseServerV4Response redbeams = waitObject.getEndpoint().getByCrn(crn);
Status status = redbeams.getStatus();
if (status.equals(DELETE_FAILED)) {
return true;
}
return waitObject.isFailed(status);
} catch (ProcessingException clientException) {
LOGGER.error("Exit waiting! Failed to get redbeams due to API client exception: {}", clientException.getMessage(), clientException);
} catch (Exception e) {
LOGGER.error("Exit waiting! Failed to get redbeams, because of: {}", e.getMessage(), e);
return true;
}
return false;
}
@Override
public ClientResponse apply(ClientRequest request)
{
RequestRunner<ClientRequest> requestRunner = new RequestRunner<>(retryComponents, headerSetter, request.getUri(), request.getMethod());
while ( requestRunner.shouldContinue() )
{
URI uri = requestRunner.prepareRequest(request);
request.setUri(uri);
try
{
ClientResponse response = connector.apply(request);
if ( requestRunner.isSuccessResponse(response.getStatus()) )
{
return response;
}
}
catch ( Exception e )
{
if ( !requestRunner.shouldBeRetried(e) )
{
throw new ProcessingException(e);
}
}
}
throw new ProcessingException("Retries expired: " + requestRunner.getOriginalUri());
}
public static <T> ApiResponse<T> checkNoError(ApiResponse<T> response) {
response.getRawResponse().bufferEntity();
try {
// if ignoreUnknownProperty is true, no exception will be thrown
ApiError error = response.readError();
Status.Family responseStatus = Status.Family.familyOf(error.getStatusCode());
if (responseStatus == Status.Family.CLIENT_ERROR
|| responseStatus == Status.Family.SERVER_ERROR) {
throw new AssertionError("Expected no error, got " + error);
}
// no error
} catch (ProcessingException ex) {
// no error
}
return response;
}
@Test(expectedExceptions={ProcessingException.class})
public void testReadTimeout() throws Exception {
stubFor(get(urlEqualTo("/")).willReturn(aResponse()
.withStatus(200)
.withFixedDelay(30000)));
long startTime = System.nanoTime();
try {
getClientWithReadTimeout().executeGet();
fail("A ProcessingException should have been thrown due to a read timeout");
}
finally {
long elapsedTime = System.nanoTime() - startTime;
long elapsedSecs = TimeUnit.SECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS);
checkTimeElapsed(elapsedSecs);
}
}
@Override
public boolean exitWaiting(T waitObject) {
String name = waitObject.getName();
try {
StackStatusV4Response stackStatus = waitObject.getStackEndpoint().getStatusByName(waitObject.getWorkspaceId(), name);
if (stackStatus == null) {
LOGGER.info("'{}' cluster was not found. Exit waiting!", name);
return true;
}
} catch (ProcessingException clientException) {
LOGGER.error("Exit waiting! Failed to get cluster due to API client exception: {}", clientException.getMessage(), clientException);
} catch (Exception e) {
LOGGER.error("Exit waiting! Failed to get cluster, because of: {}", e.getMessage(), e);
return true;
}
return false;
}
private boolean transitionSchemaVersionState(Long schemaVersionId,
String operationOrTargetState,
byte[] transitionDetails) throws SchemaNotFoundException, SchemaLifecycleException {
Response response = runRetryableBlock((SchemaRegistryTargets targets) -> {
WebTarget webTarget = targets.schemaVersionsTarget.path(schemaVersionId + "/state/" + operationOrTargetState);
try {
return login.doAction(new PrivilegedAction<Response>() {
@Override
public Response run() {
return webTarget.request().post(Entity.text(transitionDetails));
}
});
} catch (LoginException | ProcessingException e) {
throw new RegistryRetryableException(e);
}
});
boolean result = handleSchemaLifeCycleResponse(response);
// invalidate this entry from cache.
schemaVersionInfoCache.invalidateSchema(SchemaVersionInfoCache.Key.of(new SchemaIdVersion(schemaVersionId)));
return result;
}
/**
* Returns the entity with the specified id. Returns null if it does not exist.
*
* @param id
* Id of the entity to find.
* @param client
* The REST client to use.
* @param <T>
* Type of entity to handle.
* @throws NotFoundException
* If 404 was returned.
* @throws TimeoutException
* If 408 was returned.
* @return The entity; null if it does not exist.
*/
public static <T> T getEntity(RESTClient<T> client, long id)
throws NotFoundException, TimeoutException {
Response response = ResponseWrapper
.wrap(HttpWrapper.wrap(client.getEndpointTarget().path(String.valueOf(id))).get());
T entity = null;
if (response != null && response.getStatus() < 400) {
try {
entity = response.readEntity(client.getEntityClass());
} catch (NullPointerException | ProcessingException e) {
LOG.warn("Response did not conform to expected entity type.");
}
} else if (response != null) {
response.bufferEntity();
}
if (response != null && response.getStatus() == Status.NOT_FOUND.getStatusCode()) {
throw new NotFoundException();
} else if (response != null && response.getStatus() == Status.REQUEST_TIMEOUT.getStatusCode()) {
throw new TimeoutException();
}
return entity;
}
@Test
public void testSequentialStrategyWithRetries() throws Exception {
String address = "http://localhost:" + NON_PORT + "/non-existent";
String address2 = "http://localhost:" + NON_PORT + "/non-existent2";
CustomRetryStrategy strategy = new CustomRetryStrategy();
strategy.setMaxNumberOfRetries(5);
strategy.setAlternateAddresses(Arrays.asList(address, address2));
FailoverFeature feature = new FailoverFeature();
feature.setStrategy(strategy);
BookStore store = getBookStore(address, feature);
try {
store.getBook("1");
fail("Exception expected");
} catch (ProcessingException ex) {
assertEquals(10, strategy.getTotalCount());
assertEquals(5, strategy.getAddressCount(address));
assertEquals(5, strategy.getAddressCount(address2));
}
}
private SnoopConfig getConfigFromSnoop() throws SnoopServiceUnavailableException {
try {
Response response = ClientBuilder.newClient()
.target(serviceUrl)
.path("api")
.path("services")
.path(applicationName)
.request(APPLICATION_JSON)
.get();
if (response.getStatus() == 200) {
return response.readEntity(SnoopConfig.class);
} else {
throw new SnoopServiceUnavailableException("Response from \"" + serviceUrl + "\"=" + response.getStatus());
}
} catch (ProcessingException e) {
throw new SnoopServiceUnavailableException(e);
}
}
public boolean bufferEntity() throws ProcessingException {
checkEntityIsClosed();
if (!entityBufferred && entity instanceof InputStream) {
try {
InputStream oldEntity = (InputStream)entity;
entity = IOUtils.loadIntoBAIS(oldEntity);
oldEntity.close();
entityBufferred = true;
} catch (IOException ex) {
throw new ResponseProcessingException(this, ex);
}
}
return entityBufferred;
}
@Test(timeout = 15000)
public void testLongWaitForResponse() {
withReplicator(replicator -> {
final Set<NodeIdentifier> nodeIds = new HashSet<>();
final NodeIdentifier nodeId = new NodeIdentifier("1", "localhost", 8000, "localhost", 8001, "localhost", 8002, 8003, false);
nodeIds.add(nodeId);
final URI uri = new URI("http://localhost:8080/processors/1");
final Entity entity = new ProcessorEntity();
// set the user
final Authentication authentication = new NiFiAuthenticationToken(new NiFiUserDetails(StandardNiFiUser.ANONYMOUS));
SecurityContextHolder.getContext().setAuthentication(authentication);
final AsyncClusterResponse response = replicator.replicate(nodeIds, HttpMethod.GET, uri, entity, new HashMap<>(), true, true);
// We should get back the same response object
assertTrue(response == replicator.getClusterResponse(response.getRequestIdentifier()));
final NodeResponse completedNodeResponse = response.awaitMergedResponse(2, TimeUnit.SECONDS);
assertNotNull(completedNodeResponse);
assertNotNull(completedNodeResponse.getThrowable());
assertEquals(500, completedNodeResponse.getStatus());
assertTrue(response.isComplete());
assertNotNull(response.getMergedResponse());
assertNull(replicator.getClusterResponse(response.getRequestIdentifier()));
}, Status.OK, 1000, new ProcessingException(new SocketTimeoutException()));
}
@Override
public <R> R apply(final Function<T, R> function) throws IOException {
final T jaxRsClient = jaxRsClientFactory.createClient(apiClass, hostName, port, pathPrefix, scheme);
try {
return function.apply(jaxRsClient);
} catch (ProcessingException e) {
throw new IOException("Communication with REST server failed", e);
}
}
@Test
public void testSendWithExceptionFromRequestSwallowed() {
when(apiResource.path("/api/put")).thenReturn(apiResource);
when(apiResource.request()).thenReturn(mockBuilder);
when(mockBuilder.post((Entity<?>) anyObject())).thenThrow(new ProcessingException("Exception from underlying jersey client"));
openTsdb.send(OpenTsdbMetric.named("foo").build());
verify(mockBuilder).post((Entity<?>) anyObject());
}