Java Code Examples for io.undertow.client.ClientResponse

The following examples show how to use io.undertow.client.ClientResponse. 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: lams   Author: lamsfoundation   File: HttpClientConnection.java    License: 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 #2
Source Project: light-4j   Author: networknt   File: ConsulClientImpl.java    License: 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 #3
Source Project: light-4j   Author: networknt   File: ConsulClientImpl.java    License: 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 #4
Source Project: light-4j   Author: networknt   File: ConsulClientImpl.java    License: 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 #5
Source Project: lams   Author: lamsfoundation   File: Http2ClientExchange.java    License: 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 #6
Source Project: lams   Author: lamsfoundation   File: Http2ClientExchange.java    License: 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 #7
Source Project: light-rest-4j   Author: networknt   File: ValidatorHandlerTest.java    License: 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 Project: light-rest-4j   Author: networknt   File: ValidatorHandlerTest.java    License: 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 #9
Source Project: light-rest-4j   Author: networknt   File: ValidatorHandlerTest.java    License: 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 #10
Source Project: light-rest-4j   Author: networknt   File: ValidatorHandlerTest.java    License: 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 #11
Source Project: light-rest-4j   Author: networknt   File: ValidatorHandlerTest.java    License: 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 #12
Source Project: light-rest-4j   Author: networknt   File: ValidatorHandlerTest.java    License: 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 #13
Source Project: light-4j   Author: networknt   File: DefaultConfigLoader.java    License: 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 #14
Source Project: light-4j   Author: networknt   File: DefaultConfigLoader.java    License: 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 #15
Source Project: light-4j   Author: networknt   File: ConsulClientImpl.java    License: 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 #16
Source Project: light-4j   Author: networknt   File: ConsulClientImpl.java    License: 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 Project: lams   Author: lamsfoundation   File: AjpClientConnection.java    License: GNU General Public License v2.0 4 votes vote down vote up
public void handleEvent(AjpClientChannel channel) {
    try {
        AbstractAjpClientStreamSourceChannel result = channel.receive();
        if(result == null) {
            if(!channel.isOpen()) {
                //we execute this in a runnable
                //as there may be close/data frames that need to be processed
                getIoThread().execute(new Runnable() {
                    @Override
                    public void run() {
                        if(currentRequest != null) {
                            currentRequest.setFailed(new ClosedChannelException());
                        }
                    }
                });
            }
            return;
        }

        if(result instanceof AjpClientResponseStreamSourceChannel) {
            AjpClientResponseStreamSourceChannel response = (AjpClientResponseStreamSourceChannel) result;
            response.setFinishListener(responseFinishedListener);
            ClientResponse cr = new ClientResponse(response.getStatusCode(), response.getReasonPhrase(), currentRequest.getRequest().getProtocol(), response.getHeaders());
            if (response.getStatusCode() == 100) {
                currentRequest.setContinueResponse(cr);
            } else {
                currentRequest.setResponseChannel(response);
                currentRequest.setResponse(cr);
            }
        } else {
            //TODO: ping, pong ETC
            Channels.drain(result, Long.MAX_VALUE);
        }

    } catch (Throwable e) {
        UndertowLogger.CLIENT_LOGGER.exceptionProcessingRequest(e);
        safeClose(connection);
        if(currentRequest != null) {
            currentRequest.setFailed(e instanceof IOException ? (IOException) e : new IOException(e));
        }
    }
}
 
Example #18
Source Project: lams   Author: lamsfoundation   File: AjpClientExchange.java    License: 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 #19
Source Project: lams   Author: lamsfoundation   File: AjpClientExchange.java    License: 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 #20
Source Project: lams   Author: lamsfoundation   File: AjpClientExchange.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public ClientResponse getResponse() {
    return response;
}
 
Example #21
Source Project: lams   Author: lamsfoundation   File: AjpClientExchange.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public ClientResponse getContinueResponse() {
    return continueResponse;
}
 
Example #22
Source Project: lams   Author: lamsfoundation   File: Http2ClientExchange.java    License: 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 #23
Source Project: lams   Author: lamsfoundation   File: Http2ClientExchange.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public ClientResponse getResponse() {
    return clientResponse;
}
 
Example #24
Source Project: lams   Author: lamsfoundation   File: Http2ClientExchange.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public ClientResponse getContinueResponse() {
    return continueResponse;
}
 
Example #25
Source Project: lams   Author: lamsfoundation   File: HttpResponseBuilder.java    License: GNU General Public License v2.0 4 votes vote down vote up
public ClientResponse build() {
  return new ClientResponse(statusCode, reasonPhrase, protocol, responseHeaders);
}
 
Example #26
Source Project: lams   Author: lamsfoundation   File: HttpClientExchange.java    License: 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 #27
Source Project: lams   Author: lamsfoundation   File: HttpClientExchange.java    License: 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 #28
Source Project: lams   Author: lamsfoundation   File: HttpClientExchange.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public ClientResponse getResponse() {
    return response;
}
 
Example #29
Source Project: lams   Author: lamsfoundation   File: HttpClientExchange.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public ClientResponse getContinueResponse() {
    return continueResponse;
}
 
Example #30
Source Project: lams   Author: lamsfoundation   File: NodeHealthChecker.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public boolean checkResponse(ClientResponse response) {
    return true;
}