io.undertow.client.ClientResponse Java Examples

The following examples show how to use io.undertow.client.ClientResponse. 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: ConsulClientImpl.java    From light-4j with Apache License 2.0 6 votes vote down vote up
/**
 * send to consul, init or reconnect if necessary
 * @param method http method to use
 * @param path path to send to consul
 * @param token token to put in header
 * @param json request body to send
 * @return AtomicReference<ClientResponse> response
 */
 AtomicReference<ClientResponse> send (HttpString method, String path, String token, String json) throws InterruptedException {
	final CountDownLatch latch = new CountDownLatch(1);
	final AtomicReference<ClientResponse> reference = new AtomicReference<>();

	if (needsToCreateConnection()) {
		this.connection = createConnection();
	}

	ClientRequest request = new ClientRequest().setMethod(method).setPath(path);
	request.getRequestHeaders().put(Headers.HOST, "localhost");
	if (token != null) request.getRequestHeaders().put(HttpStringConstants.CONSUL_TOKEN, token);
	logger.trace("The request sent to consul: {} = request header: {}, request body is empty", uri.toString(), request.toString());
	if(StringUtils.isBlank(json)) {
		connection.sendRequest(request, client.createClientCallback(reference, latch));
	} else {
              request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
		connection.sendRequest(request, client.createClientCallback(reference, latch, json));
	}

	latch.await();
	reqCounter.getAndIncrement();
	logger.trace("The response got from consul: {} = {}", uri.toString(), reference.get().toString());
	return reference;
}
 
Example #2
Source File: HttpClientConnection.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private void prepareResponseChannel(ClientResponse response, ClientExchange exchange) {
    String encoding = response.getResponseHeaders().getLast(Headers.TRANSFER_ENCODING);
    boolean chunked = encoding != null && Headers.CHUNKED.equals(new HttpString(encoding));
    String length = response.getResponseHeaders().getFirst(Headers.CONTENT_LENGTH);
    if (exchange.getRequest().getMethod().equals(Methods.HEAD)) {
        connection.getSourceChannel().setConduit(new FixedLengthStreamSourceConduit(connection.getSourceChannel().getConduit(), 0, responseFinishedListener));
    } else if (chunked) {
        connection.getSourceChannel().setConduit(new ChunkedStreamSourceConduit(connection.getSourceChannel().getConduit(), pushBackStreamSourceConduit, bufferPool, responseFinishedListener, exchange, connection));
    } else if (length != null) {
        try {
            long contentLength = Long.parseLong(length);
            connection.getSourceChannel().setConduit(new FixedLengthStreamSourceConduit(connection.getSourceChannel().getConduit(), contentLength, responseFinishedListener));
        } catch (NumberFormatException e) {
            handleError(e);
            throw e;
        }
    } else if (response.getProtocol().equals(Protocols.HTTP_1_1) && !Connectors.isEntityBodyAllowed(response.getResponseCode())) {
        connection.getSourceChannel().setConduit(new FixedLengthStreamSourceConduit(connection.getSourceChannel().getConduit(), 0, responseFinishedListener));
    } else {
        connection.getSourceChannel().setConduit(new FinishableStreamSourceConduit(connection.getSourceChannel().getConduit(), responseFinishedListener));
        state |= CLOSE_REQ;
    }
}
 
Example #3
Source File: ConsulClientImpl.java    From light-4j with Apache License 2.0 6 votes vote down vote up
@Override
public void checkPass(String serviceId, String token) {
	logger.trace("checkPass serviceId = {}", serviceId);
	String path = "/v1/agent/check/pass/" + "check-" + serviceId;
	try {
		ConsulConnection consulConnection = getConnection(CHECK_PASS_CONNECTION_KEY + Thread.currentThread().getId());
		AtomicReference<ClientResponse> reference = consulConnection.send(Methods.PUT, path, token, null);
		int statusCode = reference.get().getResponseCode();
		if(statusCode >= UNUSUAL_STATUS_CODE){
			logger.error("Failed to checkPass on Consul: {} : {}", statusCode, reference.get().getAttachment(Http2Client.RESPONSE_BODY));
			throw new Exception("Failed to checkPass on Consul: " + statusCode + ":" + reference.get().getAttachment(Http2Client.RESPONSE_BODY));
		}
	} catch (Exception e) {
		logger.error("CheckPass request exception", e);
	}
}
 
Example #4
Source File: ConsulClientImpl.java    From light-4j with Apache License 2.0 6 votes vote down vote up
@Override
public void registerService(ConsulService service, String token) {
	String json = service.toString();
	String path = "/v1/agent/service/register";
	try {
		ConsulConnection consulConnection = getConnection(REGISTER_CONNECTION_KEY + Thread.currentThread().getId());
		AtomicReference<ClientResponse> reference = consulConnection.send(Methods.PUT, path, token, json);
		int statusCode = reference.get().getResponseCode();
		if(statusCode >= UNUSUAL_STATUS_CODE){
			throw new Exception("Failed to register on Consul: " + statusCode);
		}
	} catch (Exception e) {
		logger.error("Failed to register on Consul, Exception:", e);
		throw new RuntimeException(e.getMessage());
	}
}
 
Example #5
Source File: ConsulClientImpl.java    From light-4j with Apache License 2.0 5 votes vote down vote up
@Override
public void checkFail(String serviceId, String token) {
	logger.trace("checkFail serviceId = {}", serviceId);
	String path = "/v1/agent/check/fail/" + "check-" + serviceId;
	try {
		ConsulConnection consulConnection = getConnection(CHECK_FAIL_CONNECTION_KEY + Thread.currentThread().getId());
		AtomicReference<ClientResponse> reference = consulConnection.send(Methods.PUT, path, token, null);
		int statusCode = reference.get().getResponseCode();
		if(statusCode >= UNUSUAL_STATUS_CODE){
			logger.error("Failed to checkFail on Consul: {} : {}", statusCode, reference.get().getAttachment(Http2Client.RESPONSE_BODY));
		}
	} catch (Exception e) {
		logger.error("CheckFail request exception", e);
	}
}
 
Example #6
Source File: ValidatorHandlerTest.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoResponseContentValidation() throws ClientException, URISyntaxException, ExecutionException, InterruptedException, TimeoutException {
    ClientRequest clientRequest = new ClientRequest();
    clientRequest.getRequestHeaders().put(new HttpString("todo_Header1"), "header_1");
    CompletableFuture<ClientResponse> future = sendResponse(clientRequest, "");
    String statusCode = future.get().getStatus();
    Assert.assertNotEquals("OK", statusCode);
}
 
Example #7
Source File: ValidatorHandlerTest.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testResponseContentValidationWithError() throws ClientException, URISyntaxException, ExecutionException, InterruptedException, TimeoutException {
    ClientRequest clientRequest = new ClientRequest();
    clientRequest.getRequestHeaders().put(new HttpString("todo_Header1"), "header_1");
    CompletableFuture<ClientResponse> future = sendResponse(clientRequest, "response2");
    String statusCode = future.get().getStatus();
    Assert.assertEquals("OK", statusCode);
    List<String> errorLines = getErrorLinesFromLogFile();
    Assert.assertTrue(errorLines.size() > 0);
}
 
Example #8
Source File: ValidatorHandlerTest.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testResponseContentValidationWithNoError() throws ClientException, URISyntaxException, ExecutionException, InterruptedException {
    ClientRequest clientRequest = new ClientRequest();
    clientRequest.getRequestHeaders().put(new HttpString("todo_Header1"), "header_1");
    CompletableFuture<ClientResponse> future = sendResponse(clientRequest, "response1");
    String statusCode = future.get().getStatus();
    Assert.assertEquals("OK", statusCode);
    List<String> errorLines = getErrorLinesFromLogFile();
    Assert.assertTrue(errorLines.size() == 0);
}
 
Example #9
Source File: ValidatorHandlerTest.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testResponseHeaderValidationWithNoError() throws ClientException, URISyntaxException, ExecutionException, InterruptedException {
    ClientRequest clientRequest = new ClientRequest();
    clientRequest.getRequestHeaders().put(new HttpString("todo_Header1"), "header_1");
    clientRequest.getRequestHeaders().put(new HttpString("todo_Header2"), "123");
    CompletableFuture<ClientResponse> future = sendResponse(clientRequest, "response1");
    String statusCode = future.get().getStatus();
    Assert.assertEquals("OK", statusCode);
    List<String> errorLines = getErrorLinesFromLogFile();
    Assert.assertTrue(errorLines.size() == 0);
}
 
Example #10
Source File: ValidatorHandlerTest.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testResponseHeaderValidationWithError() throws ClientException, URISyntaxException, ExecutionException, InterruptedException {
    ClientRequest clientRequest = new ClientRequest();
    clientRequest.getRequestHeaders().put(new HttpString("todo_Header1"), "header_1");
    clientRequest.getRequestHeaders().put(new HttpString("todo_Header2"), "header_2");
    CompletableFuture<ClientResponse> future = sendResponse(clientRequest, "response1");
    String statusCode = future.get().getStatus();
    Assert.assertEquals("OK", statusCode);
    List<String> errorLines = getErrorLinesFromLogFile();
    Assert.assertTrue(errorLines.size() > 0);
}
 
Example #11
Source File: ValidatorHandlerTest.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testResponseHeaderRequiredValidationWithError() throws ClientException, URISyntaxException, ExecutionException, InterruptedException {
    ClientRequest clientRequest = new ClientRequest();
    CompletableFuture<ClientResponse> future = sendResponse(clientRequest, "response1");
    String statusCode = future.get().getStatus();
    Assert.assertEquals("OK", statusCode);
    List<String> errorLines = getErrorLinesFromLogFile();
    Assert.assertTrue(errorLines.size() > 0);
}
 
Example #12
Source File: DefaultConfigLoader.java    From light-4j with Apache License 2.0 5 votes vote down vote up
/**
 * This is a public method that is used to test the connectivity in the integration test to ensure that the
 * light-config-server can be connected with the default bootstrap.truststore. There is no real value for
 * this method other than that.
 *
 * @return String of OK
 */
public static String getConfigServerHealth(String host, String path) {
    String result = null;
    try {
        final CountDownLatch latch = new CountDownLatch(1);
        ClientConnection connection = client.connect(new URI(host), Http2Client.WORKER, client.createXnioSsl(createBootstrapContext()), Http2Client.BUFFER_POOL, OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)).get();
        final AtomicReference<ClientResponse> reference = new AtomicReference<>();
        try {
            final ClientRequest request = new ClientRequest().setMethod(Methods.GET).setPath(path);
            request.getRequestHeaders().put(Headers.HOST, host);
            connection.sendRequest(request, client.createClientCallback(reference, latch));
            latch.await(1000, TimeUnit.MILLISECONDS);
        } finally {
            // here the connection is closed after one request. It should be used for in frequent
            // request as creating a new connection is costly with TLS handshake and ALPN.
            IoUtils.safeClose(connection);
        }
        int statusCode = reference.get().getResponseCode();
        String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
        if (statusCode >= 300) {
            logger.error("Failed to load configs from config server" + statusCode + ":" + body);
            throw new Exception("Failed to load configs from config server: " + statusCode);
        } else {
            result = body;
        }
    } catch (Exception e) {
        logger.error("Exception while calling config server:", e);
    }
    return result;
}
 
Example #13
Source File: Http2ClientExchange.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
ClientResponse createResponse(Http2StreamSourceChannel result) {
    HeaderMap headers = result.getHeaders();
    final String status = result.getHeaders().getFirst(Http2Channel.STATUS);
    int statusCode = Integer.parseInt(status);
    headers.remove(Http2Channel.STATUS);
    return new ClientResponse(statusCode, status.substring(3), Protocols.HTTP_2_0, headers);
}
 
Example #14
Source File: Http2ClientExchange.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
void responseReady(Http2StreamSourceChannel result) {
    this.response = result;
    ClientResponse clientResponse = createResponse(result);
    this.clientResponse = clientResponse;
    if (responseListener != null) {
        responseListener.completed(this);
    }
}
 
Example #15
Source File: DefaultConfigLoader.java    From light-4j with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> getServiceConfigs(String configServerPath) {
    String authorization = System.getenv(AUTHORIZATION);
    String verifyHostname = System.getenv(VERIFY_HOST_NAME);

    Map<String, Object> configs = new HashMap<>();

    logger.debug("Calling Config Server endpoint:{}{}", configServerUri, configServerPath);

    try {
        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicReference<ClientResponse> reference = new AtomicReference<>();

        final ClientRequest request = new ClientRequest().setMethod(Methods.GET).setPath(configServerPath);
        request.getRequestHeaders().put(Headers.AUTHORIZATION, authorization);
        request.getRequestHeaders().put(Headers.HOST, configServerUri);
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await(10000, TimeUnit.MILLISECONDS);

        int statusCode = reference.get().getResponseCode();
        String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
        if (statusCode >= 300) {
            logger.error("Failed to load configs from config server" + statusCode + ":" + body);
            throw new Exception("Failed to load configs from config server: " + statusCode);
        } else {
            // Get the response
            Map<String, Object> responseMap = (Map<String, Object>) mapper.readValue(body, new TypeReference<Map<String, Object>>() {});
            configs = (Map<String, Object>) responseMap.get("configProperties");
        }
    } catch (Exception e) {
        logger.error("Exception while calling config server:", e);
    }
    return configs;
}
 
Example #16
Source File: ConsulClientImpl.java    From light-4j with Apache License 2.0 5 votes vote down vote up
@Override
public void unregisterService(String serviceId, String token) {
	String path = "/v1/agent/service/deregister/" + serviceId;
	try {
		ConsulConnection connection = getConnection(UNREGISTER_CONNECTION_KEY + Thread.currentThread().getId());
           final AtomicReference<ClientResponse> reference = connection.send(Methods.PUT, path, token, null);
           int statusCode = reference.get().getResponseCode();
           if(statusCode >= UNUSUAL_STATUS_CODE){
               logger.error("Failed to unregister on Consul, body = {}", reference.get().getAttachment(Http2Client.RESPONSE_BODY));
           }
	} catch (Exception e) {
		logger.error("Failed to unregister on Consul, Exception:", e);
	}
}
 
Example #17
Source File: ResponseValidatorTest.java    From light-rest-4j with Apache License 2.0 4 votes vote down vote up
@Test
public void testValidateResponseContentWithExchangeError() throws InterruptedException, ClientException, URISyntaxException, TimeoutException, ExecutionException {
    ClientRequest clientRequest = new ClientRequest();
    CompletableFuture<ClientResponse> future = sendResponse(clientRequest, "response2");
    Assert.assertTrue(future.get(3, TimeUnit.SECONDS).getResponseCode() > 300);
}
 
Example #18
Source File: AsyncResponse.java    From light-4j with Apache License 2.0 4 votes vote down vote up
public void setClientResponse(ClientResponse clientResponse) {
    this.clientResponse = clientResponse;
}
 
Example #19
Source File: AsyncResponse.java    From light-4j with Apache License 2.0 4 votes vote down vote up
public ClientResponse getClientResponse() {
    return clientResponse;
}
 
Example #20
Source File: AsyncResponse.java    From light-4j with Apache License 2.0 4 votes vote down vote up
public AsyncResponse(ClientResponse clientResponse, String responseBody, long responseTime) {
    this.clientResponse = clientResponse;
    this.responseBody = responseBody;
    this.responseTime = responseTime;
}
 
Example #21
Source File: CircuitBreaker.java    From light-4j with Apache License 2.0 4 votes vote down vote up
public CircuitBreaker(Supplier<CompletableFuture<ClientResponse>> supplier) {
    this.supplier = supplier;
    this.timeoutCount = new AtomicInteger(0);
}
 
Example #22
Source File: GithubUtil.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
/**
 * Get the user roles from github.com repository.
 *
 * @param username String username
 * @return A set of group attributes for the username on github DB. You can
 *         only call this method if the username has been authenticated
 * @throws ClientException ClientException
 */
public static Set<String> authorize(String username) throws Exception {
	Set<String> groups = new HashSet<String>();

	String apiURL = config.protocol + "://" + config.host;
	String contentsURL = config.pathPrefix + "/repos/" + config.owner + "/" + config.repo + "/contents/" + config.path;

	final Http2Client client = Http2Client.getInstance();
       final CountDownLatch latch = new CountDownLatch(1);
       
       final ClientConnection connection = client.connect(new URI(apiURL), Http2Client.WORKER, Http2Client.SSL, Http2Client.BUFFER_POOL, OptionMap.EMPTY).get();
       final AtomicReference<ClientResponse> reference = new AtomicReference<>();
       try {
				logger.info("Create request to github path: " + contentsURL);
       	final ClientRequest request = new ClientRequest().setMethod(Methods.GET).setPath(contentsURL);
		request.getRequestHeaders().put(Headers.AUTHORIZATION, "token " + githubToken);
		request.getRequestHeaders().put(Headers.HOST, config.host);
		request.getRequestHeaders().put(Headers.ACCEPT, "application/vnd.github.v3.raw");
		request.getRequestHeaders().put(Headers.CACHE_CONTROL, "no-cache");
		request.getRequestHeaders().put(Headers.USER_AGENT, "stevehu");
		connection.sendRequest(request, client.createClientCallback(reference, latch));
		latch.await(); 
       } catch (Exception e) {
           logger.error("Exception: ", e);
           throw new ClientException(e);
       } finally {
           IoUtils.safeClose(connection);
       }
	int statusCode = reference.get().getResponseCode();
	String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
	if(logger.isDebugEnabled()) logger.debug("testHttp2Get: statusCode = " + statusCode + " body = " + body);

	if (statusCode == 200) {
		ObjectMapper objectMapper = new ObjectMapper();
		List<GithubMetadata> listMeta = objectMapper.readValue(body, new TypeReference<List<GithubMetadata>>(){});
		for (GithubMetadata meta : listMeta) {
			if (meta.userID.equals(username)) {
				groups.add("primary." + meta.groups.primary);
				for (String group: meta.groups.secondary) {
					groups.add("secondary." + group);
				}
				if(logger.isDebugEnabled()) logger.debug(meta.userID + " is attached to the following primary group: " + meta.groups.primary + " and secondary groups: " + Arrays.toString(meta.groups.secondary));
			}
		}
	}
	
	return groups;
}
 
Example #23
Source File: ConsulClientImpl.java    From light-4j with Apache License 2.0 4 votes vote down vote up
/**
 * to lookup health services based on serviceName,
 * if lastConsulIndex == 0, will get result right away.
 * if lastConsulIndex != 0, will establish a long query with consul with {@link #wait} seconds.
 * @param serviceName service name
 * @param tag tag that is used for filtering
 * @param lastConsulIndex last consul index
 * @param token consul token for security
 * @return null if serviceName is blank
 */
@Override
public ConsulResponse<List<ConsulService>> lookupHealthService(String serviceName, String tag, long lastConsulIndex, String token) {

	ConsulResponse<List<ConsulService>> newResponse = null;

	if(StringUtils.isBlank(serviceName)) {
		return null;
	}

	ConsulConnection connection = getConnection(serviceName + Thread.currentThread().getId());

	String path = "/v1/health/service/" + serviceName + "?passing&wait="+wait+"&index=" + lastConsulIndex;
	if(tag != null) {
		path = path + "&tag=" + tag;
	}
	logger.trace("path = {}", path);
	try {
		AtomicReference<ClientResponse> reference  = connection.send(Methods.GET, path, token, null);
		int statusCode = reference.get().getResponseCode();
		if(statusCode >= UNUSUAL_STATUS_CODE){
			throw new Exception("Failed to unregister on Consul: " + statusCode);
		} else {
			String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
			List<Map<String, Object>> services = Config.getInstance().getMapper().readValue(body, new TypeReference<List<Map<String, Object>>>(){});
			List<ConsulService> ConsulServcies = new ArrayList<>(
					services.size());
			for (Map<String, Object> service : services) {
				ConsulService newService = convertToConsulService((Map<String,Object>)service.get("Service"));
				ConsulServcies.add(newService);
			}
			if (!ConsulServcies.isEmpty()) {
				newResponse = new ConsulResponse<>();
				newResponse.setValue(ConsulServcies);
				newResponse.setConsulIndex(Long.parseLong(reference.get().getResponseHeaders().getFirst("X-Consul-Index")));
				newResponse.setConsulLastContact(Long.parseLong(reference.get().getResponseHeaders().getFirst("X-Consul-Lastcontact")));
				newResponse.setConsulKnownLeader(Boolean.parseBoolean(reference.get().getResponseHeaders().getFirst("X-Consul-Knownleader")));
			}
		}
	} catch (Exception e) {
		logger.error("Exception:", e);
	}
	return newResponse;
}
 
Example #24
Source File: HttpClientExchange.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
void setContinueResponse(ClientResponse response) {
    this.continueResponse = response;
    if (continueNotification != null) {
        this.continueNotification.handleContinue(this);
    }
}
 
Example #25
Source File: AjpClientExchange.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
void setContinueResponse(ClientResponse response) {
    this.continueResponse = response;
    if (continueNotification != null) {
        this.continueNotification.handleContinue(this);
    }
}
 
Example #26
Source File: AjpClientExchange.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
void setResponse(ClientResponse response) {
    this.response = response;
    if (responseCallback != null) {
        this.responseCallback.completed(this);
    }
}
 
Example #27
Source File: AjpClientExchange.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public ClientResponse getResponse() {
    return response;
}
 
Example #28
Source File: AjpClientExchange.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public ClientResponse getContinueResponse() {
    return continueResponse;
}
 
Example #29
Source File: Http2ClientExchange.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
void setContinueResponse(ClientResponse response) {
    this.continueResponse = response;
    if (continueNotification != null) {
        this.continueNotification.handleContinue(this);
    }
}
 
Example #30
Source File: Http2ClientExchange.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public ClientResponse getResponse() {
    return clientResponse;
}