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

The following examples show how to use com.sun.jersey.api.client.ClientHandlerException. These examples are extracted from open source projects. 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 Project: atlas   Source File: AtlasBaseClient.java    License: Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
ObjectNode callAPIWithRetries(API 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, ObjectNode.class);
        } catch (ClientHandlerException che) {
            if (i == (getNumberOfRetries() - 1)) {
                throw che;
            }
            LOG.warn("Handled exception in calling api {}", api.getNormalizedPath(), che);
            LOG.warn("Exception's cause: {}", che.getCause().getClass());
            handleClientHandlerException(che);
        }
    }
    throw new AtlasServiceException(api, new RuntimeException("Could not get response after retries."));
}
 
Example 2
Source Project: phoebus   Source File: RawLoggingFilter.java    License: 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 Project: phoebus   Source File: RawLoggingFilter.java    License: 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 4
Source Project: phoebus   Source File: RawLoggingFilter.java    License: 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 5
Source Project: phoebus   Source File: RawLoggingFilter.java    License: 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 6
Source Project: phoebus   Source File: RawLoggingFilter.java    License: 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 7
Source Project: openhab1-addons   Source File: HueBridge.java    License: 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 8
Source Project: hadoop   Source File: TestTimelineClient.java    License: 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 9
Source Project: qaf   Source File: RequestLogger.java    License: 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 10
Source Project: emodb   Source File: PartitionAwareServiceFactoryTest.java    License: 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 11
Source Project: usergrid   Source File: RestRequests.java    License: 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 12
Source Project: incubator-atlas   Source File: AtlasBaseClient.java    License: 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 13
Source Project: incubator-atlas   Source File: AtlasClientTest.java    License: 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 14
Source Project: ranger   Source File: RangerAdminJersey2RESTClient.java    License: 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 15
Source Project: ranger   Source File: RangerRESTClient.java    License: 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 16
Source Project: ranger   Source File: RangerRESTClient.java    License: 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 17
Source Project: ranger   Source File: RangerRESTClient.java    License: 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 18
Source Project: ranger   Source File: RangerRESTClient.java    License: 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 Project: ranger   Source File: RangerRESTClient.java    License: 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 20
Source Project: ranger   Source File: RangerUgSyncRESTClient.java    License: 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 21
Source Project: ranger   Source File: RangerUgSyncRESTClient.java    License: 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 22
Source Project: ribbon   Source File: SecureGetTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFailsWithHostNameValidationOn() throws Exception {

	AbstractConfiguration cm = ConfigurationManager.getConfigInstance();

	String name = "GetPostSecureTest" + ".testFailsWithHostNameValidationOn";

	String configPrefix = name + "." + "ribbon";

	cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsSecure, "true");
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.SecurePort, Integer.toString(testServer2.getPort()));
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsHostnameValidationRequired, "true"); // <--
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsClientAuthRequired, "true");
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStore, FILE_KS1.getAbsolutePath());
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStorePassword, PASSWORD);
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStore, FILE_TS1.getAbsolutePath());
	cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStorePassword, PASSWORD);

	RestClient rc = (RestClient) ClientFactory.getNamedClient(name);

	testServer1.accept();

	URI getUri = new URI(SERVICE_URI1 + "test/");
	MultivaluedMapImpl params = new MultivaluedMapImpl();
	params.add("name", "test");
       HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build();

	try{
		rc.execute(request);

		fail("expecting ssl hostname validation error");
	}catch(ClientHandlerException che){
		assertTrue(che.getMessage().indexOf("hostname in certificate didn't match") > -1);
	}
}
 
Example 23
Source Project: Bats   Source File: HeaderClientFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ClientResponse handle(ClientRequest clientRequest) throws ClientHandlerException
{
  final MultivaluedMap<String, Object> headers = clientRequest.getHeaders();
  List<Object> hcookies = headers.get(COOKIE_HEADER);
  if (hcookies == null) {
    hcookies = new ArrayList<>();
  }
  hcookies.addAll(cookies);
  headers.put(COOKIE_HEADER, hcookies);
  return getNext().handle(clientRequest);
}
 
Example 24
Source Project: mPaaS   Source File: DiscoveryHeaderClientFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ClientResponse handle(ClientRequest cr) throws ClientHandlerException {
    Map<String, String> headers = DiscoveryHeaderHelper.getInstance().getRequestHeaderInfo();
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        cr.getHeaders().put(entry.getKey(), Collections.singletonList(entry.getValue()));
    }
    return getNext().handle(cr);
}
 
Example 25
Source Project: localization_nifi   Source File: ClientUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets the content at the specified URI using the given query parameters.
 *
 * @param uri the URI to get the content of
 * @param queryParams the query parameters to use in the request
 * @return the client response resulting from getting the content of the URI
 * @throws ClientHandlerException if issues occur handling the request
 * @throws UniformInterfaceException if any interface violations occur
 */
public ClientResponse get(final URI uri, final Map<String, String> queryParams) throws ClientHandlerException, UniformInterfaceException {
    // perform the request
    WebResource webResource = client.resource(uri);
    if (queryParams != null) {
        for (final Map.Entry<String, String> queryEntry : queryParams.entrySet()) {
            webResource = webResource.queryParam(queryEntry.getKey(), queryEntry.getValue());
        }
    }

    return webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
}
 
Example 26
Source Project: localization_nifi   Source File: ClientUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Performs a POST using the specified url and entity body.
 *
 * @param uri the URI to post to
 * @param entity the item to post
 * @return the client response of the request
 */
public ClientResponse post(URI uri, Object entity) throws ClientHandlerException, UniformInterfaceException {
    // get the resource
    WebResource.Builder resourceBuilder = client.resource(uri).accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON);

    // include the request entity
    if (entity != null) {
        resourceBuilder = resourceBuilder.entity(entity);
    }

    // perform the request
    return resourceBuilder.post(ClientResponse.class);
}
 
Example 27
@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 ClientHandlerException(new SocketTimeoutException()));
}
 
Example 28
Source Project: localization_nifi   Source File: FlowController.java    License: Apache License 2.0 5 votes vote down vote up
private void updateRemoteProcessGroups() {
    final List<RemoteProcessGroup> remoteGroups = getGroup(getRootGroupId()).findAllRemoteProcessGroups();
    for (final RemoteProcessGroup remoteGroup : remoteGroups) {
        try {
            remoteGroup.refreshFlowContents();
        } catch (final CommunicationsException | ClientHandlerException e) {
            LOG.warn("Unable to communicate with remote instance {} due to {}", remoteGroup, e.toString());
            if (LOG.isDebugEnabled()) {
                LOG.warn("", e);
            }
        }
    }
}
 
Example 29
void loadAppRunningState() {
    try {
        for (MesosStateService.ExecutorStateInfo each : facadeService.loadExecutorInfo()) {
            runningApps.add(each.getId());
        }
    } catch (final JSONException | UniformInterfaceException | ClientHandlerException e) {
        clearAppRunningState();
    }
}
 
Example 30
Source Project: atlas   Source File: AtlasClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnFalseIfServerIsNotReady() throws AtlasServiceException {
    setupRetryParams();
    AtlasClient atlasClient = new AtlasClient(service, configuration);
    WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.VERSION, service);
    when(builder.method(AtlasClient.API_V1.VERSION.getMethod(), ClientResponse.class, null)).thenThrow(
            new ClientHandlerException());
    assertFalse(atlasClient.isServerReady());
}