com.sun.jersey.api.client.ClientHandlerException Java Examples

The following examples show how to use com.sun.jersey.api.client.ClientHandlerException. 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: RangerUgSyncRESTClient.java    From ranger with Apache License 2.0 6 votes vote down vote up
public ClientResponse get(String relativeURL, Map<String, String> params, Cookie sessionId) throws Exception {
	ClientResponse response = null;
	int startIndex = getLastKnownActiveUrlIndex();
	int currentIndex = 0;

	for (int index = 0; index < getConfiguredURLs().size(); index++) {
		try {
			currentIndex = (startIndex + index) % getConfiguredURLs().size();

			WebResource webResource = createWebResourceForCookieAuth(currentIndex, relativeURL);
			webResource = setQueryParams(webResource, params);
			WebResource.Builder br = webResource.getRequestBuilder().cookie(sessionId);
			response = br.accept(RangerRESTUtils.REST_EXPECTED_MIME_TYPE).get(ClientResponse.class);
			if (response != null) {
				setLastKnownActiveUrlIndex(currentIndex);
				break;
			}
		} catch (ClientHandlerException e) {
			LOG.warn("Failed to communicate with Ranger Admin, URL : " + getConfiguredURLs().get(currentIndex));
			processException(index, e);
		}
	}
	return response;
}
 
Example #2
Source File: RawLoggingFilter.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public ClientResponse handle(ClientRequest request)
		throws ClientHandlerException {
	if (this.logger.isLoggable(Level.FINE)) {
		long id = ++this._id;
		logRequest(id, request);
		
		ClientResponse response = getNext().handle(request);

		logResponse(id, response);

		return response;
	} else{
		return getNext().handle(request);			
	}

}
 
Example #3
Source File: HueBridge.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Determines the settings of the Hue bridge as a Json raw data String.
 *
 * @return The settings of the bridge if they could be determined. Null
 *         otherwise.
 */
private String getSettingsJson() {
    WebResource webResource = client.resource(getUrl());

    try {
        ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
        String settingsString = response.getEntity(String.class);

        if (response.getStatus() != 200) {
            logger.warn("Failed to connect to Hue bridge: HTTP error code: " + response.getStatus());
            return null;
        }
        logger.trace("Received Hue Bridge Settings: {}", settingsString);
        return settingsString;
    } catch (ClientHandlerException e) {
        logger.warn("Failed to connect to Hue bridge: HTTP request timed out.");
        return null;
    }
}
 
Example #4
Source File: RawLoggingFilter.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
private void logResponse(long id, ClientResponse response) {
	StringBuilder b = new StringBuilder();

	printResponseLine(b, id, response);
	printResponseHeaders(b, id, response.getHeaders());

	ByteArrayOutputStream out = new ByteArrayOutputStream();
	InputStream in = response.getEntityInputStream();
	try {
		ReaderWriter.writeTo(in, out);

		byte[] requestEntity = out.toByteArray();
		printEntity(b, requestEntity);
		response.setEntityInputStream(new ByteArrayInputStream(
				requestEntity));
	} catch (IOException ex) {
		throw new ClientHandlerException(ex);
	}
	log(b);
}
 
Example #5
Source File: RawLoggingFilter.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public ClientResponse handle(ClientRequest request)
		throws ClientHandlerException {
	if (this.logger.isLoggable(Level.FINE)) {
		long id = ++this._id;
		logRequest(id, request);
		
		ClientResponse response = getNext().handle(request);

		logResponse(id, response);

		return response;
	} else{
		return getNext().handle(request);			
	}

}
 
Example #6
Source File: RawLoggingFilter.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
private void logResponse(long id, ClientResponse response) {
	StringBuilder b = new StringBuilder();

	printResponseLine(b, id, response);
	printResponseHeaders(b, id, response.getHeaders());

	ByteArrayOutputStream out = new ByteArrayOutputStream();
	InputStream in = response.getEntityInputStream();
	try {
		ReaderWriter.writeTo(in, out);

		byte[] requestEntity = out.toByteArray();
		printEntity(b, requestEntity);
		response.setEntityInputStream(new ByteArrayInputStream(
				requestEntity));
	} catch (IOException ex) {
		throw new ClientHandlerException(ex);
	}
	log(b);
}
 
Example #7
Source File: RawLoggingFilter.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public ClientResponse handle(ClientRequest request)
		throws ClientHandlerException {
	if (this.logger.isLoggable(Level.FINE)) {
		long id = ++this._id;
		logRequest(id, request);
		
		ClientResponse response = getNext().handle(request);

		logResponse(id, response);

		return response;
	} else{
		return getNext().handle(request);			
	}

}
 
Example #8
Source File: RestRequests.java    From usergrid with Apache License 2.0 6 votes vote down vote up
/**
 * Performs a GET HTTP operation against the /status endpoint.
 *
 * @param runner the runner to perform the status operation on
 *
 * @return the result of the operation
 */
public static Result status( Runner runner ) {
    preparations( runner );

    try {
        return newStatusOp( runner ).execute( Result.class );
    }
    catch ( ClientHandlerException e ) {
        if ( e.getCause() instanceof SSLHandshakeException &&
                e.getCause().toString().contains( "PKIX path building failed" ) ) {

            /*
             * Oddly this fails the first time but works the second time. Until
             * I get to the bottom of this and figure it out this is the work
             * around we will use to make sure this does not fail. We retry once
             * on the failure.
             */

            return newStatusOp( runner ).execute( Result.class );
        }
    }

    throw new RuntimeException( "If we got here then the retry also failed." );
}
 
Example #9
Source File: TestTimelineClient.java    From hadoop with Apache License 2.0 6 votes vote down vote up
private static ClientResponse mockEntityClientResponse(
    TimelineClientImpl client, ClientResponse.Status status,
    boolean hasError, boolean hasRuntimeError) {
  ClientResponse response = mock(ClientResponse.class);
  if (hasRuntimeError) {
    doThrow(new ClientHandlerException(new ConnectException())).when(client)
        .doPostingObject(any(TimelineEntities.class), any(String.class));
    return response;
  }
  doReturn(response).when(client)
      .doPostingObject(any(TimelineEntities.class), any(String.class));
  when(response.getClientResponseStatus()).thenReturn(status);
  TimelinePutResponse.TimelinePutError error =
      new TimelinePutResponse.TimelinePutError();
  error.setEntityId("test entity id");
  error.setEntityType("test entity type");
  error.setErrorCode(TimelinePutResponse.TimelinePutError.IO_EXCEPTION);
  TimelinePutResponse putResponse = new TimelinePutResponse();
  if (hasError) {
    putResponse.addError(error);
  }
  when(response.getEntity(TimelinePutResponse.class)).thenReturn(putResponse);
  return response;
}
 
Example #10
Source File: AtlasBaseClient.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
JSONObject callAPIWithRetries(APIInfo api, Object requestObject, ResourceCreator resourceCreator)
        throws AtlasServiceException {
    for (int i = 0; i < getNumberOfRetries(); i++) {
        WebResource resource = resourceCreator.createResource();
        try {
            LOG.debug("Using resource {} for {} times", resource.getURI(), i + 1);
            return callAPIWithResource(api, resource, requestObject, JSONObject.class);
        } catch (ClientHandlerException che) {
            if (i == (getNumberOfRetries() - 1)) {
                throw che;
            }
            LOG.warn("Handled exception in calling api {}", api.getPath(), che);
            LOG.warn("Exception's cause: {}", che.getCause().getClass());
            handleClientHandlerException(che);
        }
    }
    throw new AtlasServiceException(api, new RuntimeException("Could not get response after retries."));
}
 
Example #11
Source File: PartitionAwareServiceFactoryTest.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Test
public void testDelegateConnectionTimeoutException() throws Exception {
    doThrow(new ClientHandlerException(new ConnectTimeoutException())).when(_delegate).doIt();
    TestInterface service = _serviceFactory.create(_remoteEndPoint);

    try {
        service.doIt();
    } catch (PartitionForwardingException e) {
        assertTrue(e.getCause() instanceof ConnectTimeoutException);
    }

    assertEquals(_metricRegistry.getMeters().get("bv.emodb.web.partition-forwarding.TestInterface.errors").getCount(), 1);

    verify(_delegateServiceFactory).create(_remoteEndPoint);
    verify(_delegate).doIt();

}
 
Example #12
Source File: AtlasClientTest.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
@Test(expectedExceptions = IllegalArgumentException.class)
public void shouldThrowExceptionIfActiveServerIsNotFound() {
    setupRetryParams();

    when(client.resource(UriBuilder.fromUri("http://localhost:31000").build())).thenReturn(service);
    WebResource.Builder builder = setupBuilder(AtlasClient.API.STATUS, service);
    ClientResponse response = mock(ClientResponse.class);
    when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode());
    when(response.getEntity(String.class)).thenReturn("{\"Status\":\"BECOMING_ACTIVE\"}");
    when(builder.method(AtlasClient.API.STATUS.getMethod(), ClientResponse.class, null)).
            thenThrow(new ClientHandlerException("Simulating connection exception")).
            thenReturn(response).
            thenReturn(response);

    AtlasClient atlasClient = new AtlasClient(service, configuration);

    String serviceURL = atlasClient.determineActiveServiceURL(
            new String[] {"http://localhost:31000","http://localhost:41000"},
            client);
    assertNull(serviceURL);
}
 
Example #13
Source File: RequestLogger.java    From qaf with MIT License 6 votes vote down vote up
private StringBuilder logResponse(long id, ClientResponse response) {
	StringBuilder b = new StringBuilder();

	printResponseLine(b, id, response);
	printResponseHeaders(b, id, response.getHeaders());

	ByteArrayOutputStream out = new ByteArrayOutputStream();
	InputStream in = response.getEntityInputStream();
	try {
		ReaderWriter.writeTo(in, out);

		byte[] requestEntity = out.toByteArray();
		printEntity(b, requestEntity);
		response.setEntityInputStream(new ByteArrayInputStream(requestEntity));
	} catch (IOException ex) {
		throw new ClientHandlerException(ex);
	}
	log(b.toString());
	return b;
}
 
Example #14
Source File: RangerUgSyncRESTClient.java    From ranger with Apache License 2.0 6 votes vote down vote up
public ClientResponse post(String relativeURL, Map<String, String> params, Object obj, Cookie sessionId)
		throws Exception {
	ClientResponse response = null;
	int startIndex = getLastKnownActiveUrlIndex();
	int currentIndex = 0;

	for (int index = 0; index < getConfiguredURLs().size(); index++) {
		try {
			currentIndex = (startIndex + index) % getConfiguredURLs().size();

			WebResource webResource = createWebResourceForCookieAuth(currentIndex, relativeURL);
			webResource = setQueryParams(webResource, params);
			WebResource.Builder br = webResource.getRequestBuilder().cookie(sessionId);
			response = br.accept(RangerRESTUtils.REST_EXPECTED_MIME_TYPE).type(RangerRESTUtils.REST_MIME_TYPE_JSON)
					.post(ClientResponse.class, toJson(obj));
			if (response != null) {
				setLastKnownActiveUrlIndex(currentIndex);
				break;
			}
		} catch (ClientHandlerException e) {
			LOG.warn("Failed to communicate with Ranger Admin, URL : " + getConfiguredURLs().get(currentIndex));
			processException(index, e);
		}
	}
	return response;
}
 
Example #15
Source File: RangerAdminJersey2RESTClient.java    From ranger with Apache License 2.0 6 votes vote down vote up
private Response get(Map<String, String> queyParams, String relativeURL) {
	Response response = null;
	int startIndex = this.lastKnownActiveUrlIndex;
       int currentIndex = 0;

	for (int index = 0; index < configURLs.size(); index++) {
		try {
			currentIndex = (startIndex + index) % configURLs.size();

			WebTarget target = _client.target(configURLs.get(currentIndex) + relativeURL);
			response = setQueryParams(target, queyParams).request(MediaType.APPLICATION_JSON_TYPE).get();
			if (response != null) {
				setLastKnownActiveUrlIndex(currentIndex);
				break;
			}
		} catch (ProcessingException e) {
			LOG.warn("Failed to communicate with Ranger Admin, URL : " + configURLs.get(currentIndex));
			if (index == configURLs.size() - 1) {
				throw new ClientHandlerException(
						"Failed to communicate with all Ranger Admin's URL's : [ " + configURLs + " ]", e);
			}
		}
	}
	return response;
}
 
Example #16
Source File: RangerRESTClient.java    From ranger with Apache License 2.0 6 votes vote down vote up
public ClientResponse put(String relativeURL, Object request, Cookie sessionId) throws Exception {
	ClientResponse response = null;
	int startIndex = this.lastKnownActiveUrlIndex;
	int currentIndex = 0;

	for (int index = 0; index < configuredURLs.size(); index++) {
		try {
			currentIndex = (startIndex + index) % configuredURLs.size();

			WebResource webResource = createWebResourceForCookieAuth(currentIndex, relativeURL);
			WebResource.Builder br = webResource.getRequestBuilder().cookie(sessionId);
			response = br.accept(RangerRESTUtils.REST_EXPECTED_MIME_TYPE).type(RangerRESTUtils.REST_MIME_TYPE_JSON)
					.put(ClientResponse.class, toJson(request));
			if (response != null) {
				setLastKnownActiveUrlIndex(currentIndex);
				break;
			}
		} catch (ClientHandlerException e) {
			LOG.warn("Failed to communicate with Ranger Admin, URL : " + configuredURLs.get(currentIndex));
			processException(index, e);
		}
	}
	return response;
}
 
Example #17
Source File: RangerRESTClient.java    From ranger with Apache License 2.0 6 votes vote down vote up
public ClientResponse get(String relativeUrl, Map<String, String> params) throws Exception {
	ClientResponse finalResponse = null;
	int startIndex = this.lastKnownActiveUrlIndex;
	int currentIndex = 0;

	for (int index = 0; index < configuredURLs.size(); index++) {
		try {
			currentIndex = (startIndex + index) % configuredURLs.size();

			WebResource webResource = getClient().resource(configuredURLs.get(currentIndex) + relativeUrl);
			webResource = setQueryParams(webResource, params);

			finalResponse = webResource.accept(RangerRESTUtils.REST_EXPECTED_MIME_TYPE).type(RangerRESTUtils.REST_MIME_TYPE_JSON).get(ClientResponse.class);

			if (finalResponse != null) {
				setLastKnownActiveUrlIndex(currentIndex);
				break;
			}
		} catch (ClientHandlerException ex) {
			LOG.warn("Failed to communicate with Ranger Admin, URL : " + configuredURLs.get(currentIndex));
			processException(index, ex);
		}
	}
	return finalResponse;
}
 
Example #18
Source File: RangerRESTClient.java    From ranger with Apache License 2.0 6 votes vote down vote up
public ClientResponse put(String relativeUrl, Map<String, String> params, Object obj) throws Exception {
	ClientResponse finalResponse = null;
	int startIndex = this.lastKnownActiveUrlIndex;
	int currentIndex = 0;
	for (int index = 0; index < configuredURLs.size(); index++) {
		try {
			currentIndex = (startIndex + index) % configuredURLs.size();

			WebResource webResource = getClient().resource(configuredURLs.get(currentIndex) + relativeUrl);
			webResource = setQueryParams(webResource, params);
			finalResponse = webResource.accept(RangerRESTUtils.REST_EXPECTED_MIME_TYPE).type(RangerRESTUtils.REST_MIME_TYPE_JSON).put(ClientResponse.class, toJson(obj));
			if (finalResponse != null) {
				setLastKnownActiveUrlIndex(currentIndex);
				break;
			}
		} catch (ClientHandlerException ex) {
			LOG.warn("Failed to communicate with Ranger Admin, URL : " + configuredURLs.get(currentIndex));
			processException(index, ex);
		}
	}
	return finalResponse;
}
 
Example #19
Source File: RangerRESTClient.java    From ranger with Apache License 2.0 6 votes vote down vote up
public ClientResponse post(String relativeUrl, Map<String, String> params, Object obj) throws Exception {
	ClientResponse finalResponse = null;
	int startIndex = this.lastKnownActiveUrlIndex;
	int currentIndex = 0;

	for (int index = 0; index < configuredURLs.size(); index++) {
		try {
			currentIndex = (startIndex + index) % configuredURLs.size();

			WebResource webResource = getClient().resource(configuredURLs.get(currentIndex) + relativeUrl);
			webResource = setQueryParams(webResource, params);
			finalResponse = webResource.accept(RangerRESTUtils.REST_EXPECTED_MIME_TYPE).type(RangerRESTUtils.REST_MIME_TYPE_JSON).post(ClientResponse.class, toJson(obj));
			if (finalResponse != null) {
				setLastKnownActiveUrlIndex(currentIndex);
				break;
			}
		} catch (ClientHandlerException ex) {
			LOG.warn("Failed to communicate with Ranger Admin, URL : " + configuredURLs.get(currentIndex));
			processException(index, ex);
		}
	}
	return finalResponse;
}
 
Example #20
Source File: RangerRESTClient.java    From ranger with Apache License 2.0 6 votes vote down vote up
public ClientResponse delete(String relativeUrl, Map<String, String> params) throws Exception {
	ClientResponse finalResponse = null;
	int startIndex = this.lastKnownActiveUrlIndex;
	int currentIndex = 0;

	for (int index = 0; index < configuredURLs.size(); index++) {
		try {
			currentIndex = (startIndex + index) % configuredURLs.size();

			WebResource webResource = getClient().resource(configuredURLs.get(currentIndex) + relativeUrl);
			webResource = setQueryParams(webResource, params);

			finalResponse = webResource.accept(RangerRESTUtils.REST_EXPECTED_MIME_TYPE).type(RangerRESTUtils.REST_MIME_TYPE_JSON).delete(ClientResponse.class);
			if (finalResponse != null) {
				setLastKnownActiveUrlIndex(currentIndex);
				break;
			}
		} catch (ClientHandlerException ex) {
			LOG.warn("Failed to communicate with Ranger Admin, URL : " + configuredURLs.get(currentIndex));
			processException(index, ex);
		}
	}
	return finalResponse;
}
 
Example #21
Source File: QueueClientFactory.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isRetriableException(Exception e) {
    return super.isRetriableException(e) ||
            (e instanceof UniformInterfaceException &&
                    ((UniformInterfaceException) e).getResponse().getStatus() >= 500) ||
            Iterables.any(Throwables.getCausalChain(e), Predicates.instanceOf(ClientHandlerException.class));
}
 
Example #22
Source File: AtlasClientTest.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRetryIfCannotConnectToServiceInitially() {
    setupRetryParams();

    when(client.resource(UriBuilder.fromUri("http://localhost:31000").build())).thenReturn(service);
    WebResource.Builder builder = setupBuilder(AtlasClient.API.STATUS, service);
    ClientResponse response = mock(ClientResponse.class);
    when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode());
    when(response.getEntity(String.class)).thenReturn("{\"Status\":\"BECOMING_ACTIVE\"}");
    ClientResponse nextResponse = mock(ClientResponse.class);
    when(nextResponse.getStatus()).thenReturn(Response.Status.OK.getStatusCode());
    String activeStatus = "{\"Status\":\"ACTIVE\"}";
    when(response.getEntity(String.class)).thenReturn(activeStatus);
    when(response.getLength()).thenReturn(activeStatus.length());
    when(builder.method(AtlasClient.API.STATUS.getMethod(), ClientResponse.class, null)).
            thenThrow(new ClientHandlerException("Simulating connection exception")).
            thenReturn(response).
            thenReturn(nextResponse);

    AtlasClient atlasClient = new AtlasClient(service, configuration);
    atlasClient.setService(service);
    atlasClient.setConfiguration(configuration);

    String serviceURL = atlasClient.determineActiveServiceURL(
            new String[] {"http://localhost:31000","http://localhost:41000"},
            client);
    assertEquals(serviceURL, "http://localhost:31000");
}
 
Example #23
Source File: DedupQueueClientFactory.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isRetriableException(Exception e) {
    return super.isRetriableException(e) ||
            (e instanceof UniformInterfaceException &&
                    ((UniformInterfaceException) e).getResponse().getStatus() >= 500) ||
            Iterables.any(Throwables.getCausalChain(e), Predicates.instanceOf(ClientHandlerException.class));
}
 
Example #24
Source File: JIRAHTTPClient.java    From jira-rest-client with Apache License 2.0 5 votes vote down vote up
private ClientResponse checkStatus(ClientResponse response) {
	if (response.getStatus() != Status.OK.getStatusCode() && response.getStatus() != Status.CREATED.getStatusCode()) {
		throw new ClientHandlerException("Failed : HTTP error code : "	+ response.getStatus());
	}
	
	return response;
}
 
Example #25
Source File: HttpBasicAuthenticationFilter.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
public ClientResponse handle(ClientRequest request) throws ClientHandlerException {
	if (!request.getHeaders().containsKey(HttpHeaders.AUTHORIZATION)) {
		request.getHeaders().add(HttpHeaders.AUTHORIZATION, authentication);
	}

	return getNext().handle(request);
}
 
Example #26
Source File: DatabusClientFactory.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isRetriableException(Exception e) {
    return super.isRetriableException(e) ||
            (e instanceof UniformInterfaceException &&
                    ((UniformInterfaceException) e).getResponse().getStatus() >= 500) ||
            Iterables.any(Throwables.getCausalChain(e), Predicates.instanceOf(ClientHandlerException.class));
}
 
Example #27
Source File: BlobStoreClientFactory.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isRetriableException(Exception e) {
    return super.isRetriableException(e) ||
            (e instanceof UniformInterfaceException &&
                    ((UniformInterfaceException) e).getResponse().getStatus() >= 500) ||
            Iterables.any(Throwables.getCausalChain(e), Predicates.instanceOf(ClientHandlerException.class));
}
 
Example #28
Source File: TeamctiyRest.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Trigger a build on the Teamcity instance using vcs root
 *
 * @param repository - {@link Repository}
 * @param url - url to TeamCity server
 * @param username - TeamCity user name
 * @param password - TeamCity user password
 * @return "OK" if it worked. Otherwise, an error message.
 */
@GET
@Path(value = "testconnection")
@Produces("text/plain; charset=UTF-8")
public Response testconnection(
        @Context final Repository repository,
        @QueryParam("url") final String url,
        @QueryParam("username") final String username,
        @QueryParam("password") final String password,
        @QueryParam("debugon") final String isDebugOn) {

  String realPasswordValue = password;
  if (Constant.TEAMCITY_PASSWORD_SAVED_VALUE.equals(realPasswordValue)) {
    realPasswordValue = this.connectionSettings.getPassword(repository);
  }

  final Client restClient = Client.create(Constant.REST_CLIENT_CONFIG);
  restClient.addFilter(new HTTPBasicAuthFilter(username, realPasswordValue));

  try {
    final ClientResponse response = restClient.resource(url + "/app/rest/builds?locator=lookupLimit:0").accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
    if (ClientResponse.Status.OK == response.getClientResponseStatus()) {
      this.connectionSettings.savePassword(realPasswordValue, repository);
      return Response.ok(Constant.TEAMCITY_PASSWORD_SAVED_VALUE).build();
    } else {
      return Response.status(response.getClientResponseStatus()).entity(response.getEntity(String.class)).build();
    }
  } catch (final UniformInterfaceException | ClientHandlerException e) {
    return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
  } finally {
    restClient.destroy();
  }
}
 
Example #29
Source File: PartitionAwareServiceFactory.java    From emodb with Apache License 2.0 5 votes vote down vote up
private S createDelegate(ServiceEndPoint endPoint) {
    final S delegateService = _delegate.create(endPoint);

    S proxiedService = Reflection.newProxy(_serviceClass, new AbstractInvocationHandler() {
        @Override
        protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
            try {
                return method.invoke(delegateService, args);
            } catch (InvocationTargetException e) {
                // If the target exception is a declared exception then rethrow as-is
                Throwable targetException = e.getTargetException();
                for (Class<?> declaredException : method.getExceptionTypes()) {
                    // noinspection unchecked
                    Throwables.propagateIfInstanceOf(targetException, (Class<? extends Throwable>) declaredException);
                }
                // If the exception was due to connection issues and not necessarily the target let the caller know.
                // It's possible the connection timed out due to a problem on the target, but from our perspective
                // there's no definitive way of knowing.
                if (targetException instanceof ClientHandlerException) {
                    _errorMeter.mark();
                    throw new PartitionForwardingException("Failed to handle request at endpoint", targetException.getCause());
                }
                throw Throwables.propagate(targetException);
            }
        }
    });

    _proxiedToDelegateServices.put(proxiedService, delegateService);
    return proxiedService;
}
 
Example #30
Source File: RequestTracker.java    From qaf with MIT License 5 votes vote down vote up
@Override
public ClientResponse handle(ClientRequest request) throws ClientHandlerException {

	ClientResponse response = getNext().handle(request);
	clientRequest = request;
	clientResponse = response;
	return response;
}