Java Code Examples for io.undertow.client.ClientRequest

The following examples show how to use io.undertow.client.ClientRequest. 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
@Override
public void sendRequest(final ClientRequest request, final ClientCallback<ClientExchange> clientCallback) {
    if(http2Delegate != null) {
        http2Delegate.sendRequest(request, clientCallback);
        return;
    }
    if (anyAreSet(state, UPGRADE_REQUESTED | UPGRADED | CLOSE_REQ | CLOSED)) {
        clientCallback.failed(UndertowClientMessages.MESSAGES.invalidConnectionState());
        return;
    }
    final HttpClientExchange httpClientExchange = new HttpClientExchange(clientCallback, request, this);
    boolean ssl = this.connection instanceof SslConnection;
    if(!ssl && !http2Tried && options.get(UndertowOptions.ENABLE_HTTP2, false) && !request.getRequestHeaders().contains(Headers.UPGRADE)) {
        //this is the first request, as we want to try a HTTP2 upgrade
        request.getRequestHeaders().put(new HttpString("HTTP2-Settings"), Http2ClearClientProvider.createSettingsFrame(options, bufferPool));
        request.getRequestHeaders().put(Headers.UPGRADE, Http2Channel.CLEARTEXT_UPGRADE_STRING);
        request.getRequestHeaders().put(Headers.CONNECTION, "Upgrade, HTTP2-Settings");
        http2Tried = true;
    }

    if (currentRequest == null) {
        initiateRequest(httpClientExchange);
    } else {
        pendingQueue.add(httpClientExchange);
    }
}
 
Example #2
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 #3
Source Project: hawkular-metrics   Author: hawkular   File: TokenAuthenticator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Executed when a pooled connection is acquired.
 */
private void sendAuthenticationRequest(HttpServerExchange serverExchange, PooledConnection connection) {
    AuthContext context = serverExchange.getAttachment(AUTH_CONTEXT_KEY);
    String verb = getVerb(serverExchange);

    String resource;
    // if we are not dealing with a query
    if (!isQuery(serverExchange)) {
        // is USER_WRITE_ACCESS is disabled, then use the legacy check.
        // Otherwise check using the actual resource (eg 'hawkular-metrics', 'hawkular-alerts', etc)
        if (USER_WRITE_ACCESS.equalsIgnoreCase("true")) {
            resource = RESOURCE;
        } else {
            resource= resourceName;
        }
    } else {
        resource = RESOURCE;
    }

    context.subjectAccessReview = generateSubjectAccessReview(context.tenant, verb, resource);
    ClientRequest request = buildClientRequest(context);
    context.clientRequestStarting();
    connection.sendRequest(request, new RequestReadyCallback(serverExchange, connection));
}
 
Example #4
Source Project: spring-analysis-note   Author: Vip-Augus   File: UndertowXhrTransport.java    License: MIT License 5 votes vote down vote up
private void executeReceiveRequest(final TransportRequest transportRequest,
		final URI url, final HttpHeaders headers, final XhrClientSockJsSession session,
		final SettableListenableFuture<WebSocketSession> connectFuture) {

	if (logger.isTraceEnabled()) {
		logger.trace("Starting XHR receive request for " + url);
	}

	ClientCallback<ClientConnection> clientCallback = new ClientCallback<ClientConnection>() {
		@Override
		public void completed(ClientConnection connection) {
			ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath(url.getPath());
			HttpString headerName = HttpString.tryFromString(HttpHeaders.HOST);
			request.getRequestHeaders().add(headerName, url.getHost());
			addHttpHeaders(request, headers);
			HttpHeaders httpHeaders = transportRequest.getHttpRequestHeaders();
			connection.sendRequest(request, createReceiveCallback(transportRequest,
					url, httpHeaders, session, connectFuture));
		}

		@Override
		public void failed(IOException ex) {
			throw new SockJsTransportFailureException("Failed to execute request to " + url, ex);
		}
	};

	this.httpClient.connect(clientCallback, url, this.worker, this.bufferPool, this.optionMap);
}
 
Example #5
Source Project: spring-analysis-note   Author: Vip-Augus   File: UndertowXhrTransport.java    License: MIT License 5 votes vote down vote up
private static void addHttpHeaders(ClientRequest request, HttpHeaders headers) {
	HeaderMap headerMap = request.getRequestHeaders();
	headers.forEach((key, values) -> {
		for (String value : values) {
			headerMap.add(HttpString.tryFromString(key), value);
		}
	});
}
 
Example #6
Source Project: java-technology-stack   Author: codeEngraver   File: UndertowXhrTransport.java    License: MIT License 5 votes vote down vote up
private void executeReceiveRequest(final TransportRequest transportRequest,
		final URI url, final HttpHeaders headers, final XhrClientSockJsSession session,
		final SettableListenableFuture<WebSocketSession> connectFuture) {

	if (logger.isTraceEnabled()) {
		logger.trace("Starting XHR receive request for " + url);
	}

	ClientCallback<ClientConnection> clientCallback = new ClientCallback<ClientConnection>() {
		@Override
		public void completed(ClientConnection connection) {
			ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath(url.getPath());
			HttpString headerName = HttpString.tryFromString(HttpHeaders.HOST);
			request.getRequestHeaders().add(headerName, url.getHost());
			addHttpHeaders(request, headers);
			HttpHeaders httpHeaders = transportRequest.getHttpRequestHeaders();
			connection.sendRequest(request, createReceiveCallback(transportRequest,
					url, httpHeaders, session, connectFuture));
		}

		@Override
		public void failed(IOException ex) {
			throw new SockJsTransportFailureException("Failed to execute request to " + url, ex);
		}
	};

	this.httpClient.connect(clientCallback, url, this.worker, this.bufferPool, this.optionMap);
}
 
Example #7
Source Project: java-technology-stack   Author: codeEngraver   File: UndertowXhrTransport.java    License: MIT License 5 votes vote down vote up
private static void addHttpHeaders(ClientRequest request, HttpHeaders headers) {
	HeaderMap headerMap = request.getRequestHeaders();
	headers.forEach((key, values) -> {
		for (String value : values) {
			headerMap.add(HttpString.tryFromString(key), value);
		}
	});
}
 
Example #8
Source Project: lams   Author: lamsfoundation   File: AjpClientConnection.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void sendRequest(final ClientRequest request, final ClientCallback<ClientExchange> clientCallback) {
    if (anyAreSet(state, UPGRADE_REQUESTED | UPGRADED | CLOSE_REQ | CLOSED)) {
        clientCallback.failed(UndertowClientMessages.MESSAGES.invalidConnectionState());
        return;
    }
    final AjpClientExchange AjpClientExchange = new AjpClientExchange(clientCallback, request, this);
    if (currentRequest == null) {
        initiateRequest(AjpClientExchange);
    } else {
        pendingQueue.add(AjpClientExchange);
    }
}
 
Example #9
Source Project: lams   Author: lamsfoundation   File: AjpClientExchange.java    License: GNU General Public License v2.0 5 votes vote down vote up
AjpClientExchange(ClientCallback<ClientExchange> readyCallback, ClientRequest request, AjpClientConnection clientConnection) {
    this.readyCallback = readyCallback;
    this.request = request;
    this.clientConnection = clientConnection;
    boolean reqContinue = false;
    if (request.getRequestHeaders().contains(Headers.EXPECT)) {
        for (String header : request.getRequestHeaders().get(Headers.EXPECT)) {
            if (header.equals("100-continue")) {
                reqContinue = true;
            }
        }
    }
    this.requiresContinue = reqContinue;
}
 
Example #10
Source Project: lams   Author: lamsfoundation   File: Http2ClientConnection.java    License: GNU General Public License v2.0 5 votes vote down vote up
public Http2ClientConnection(Http2Channel http2Channel, ClientCallback<ClientExchange> upgradeReadyCallback, ClientRequest clientRequest, String defaultHost, ClientStatistics clientStatistics, boolean secure) {

        this.http2Channel = http2Channel;
        this.defaultHost = defaultHost;
        this.clientStatistics = clientStatistics;
        this.secure = secure;
        http2Channel.getReceiveSetter().set(new Http2ReceiveListener());
        http2Channel.resumeReceives();
        http2Channel.addCloseTask(closeTask);
        this.initialUpgradeRequest = false;

        Http2ClientExchange exchange = new Http2ClientExchange(this, null, clientRequest);
        exchange.setResponseListener(upgradeReadyCallback);
        currentExchanges.put(1, exchange);
    }
 
Example #11
Source Project: lams   Author: lamsfoundation   File: HttpClientExchange.java    License: GNU General Public License v2.0 5 votes vote down vote up
HttpClientExchange(ClientCallback<ClientExchange> readyCallback, ClientRequest request, HttpClientConnection clientConnection) {
    this.readyCallback = readyCallback;
    this.request = request;
    this.clientConnection = clientConnection;
    boolean reqContinue = false;
    if (request.getRequestHeaders().contains(Headers.EXPECT)) {
        for (String header : request.getRequestHeaders().get(Headers.EXPECT)) {
            if (header.equals("100-continue")) {
                reqContinue = true;
            }
        }
    }
    this.requiresContinue = reqContinue;
}
 
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 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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
Source Project: light-4j   Author: networknt   File: TokenManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * get a Jwt with a provided clientRequest,
 * it will get token based on Jwt.Key (either scope or service_id)
 * if the user declared both scope and service_id in header, it will get jwt based on scope
 * @param clientRequest client request
 * @return Result
 */
public Result<Jwt> getJwt(ClientRequest clientRequest) {
    HeaderValues scope = clientRequest.getRequestHeaders().get(ClientConfig.SCOPE);
    if(scope != null) {
        String scopeStr = scope.getFirst();
        Set<String> scopeSet = new HashSet<>();
        scopeSet.addAll(Arrays.asList(scopeStr.split(" ")));
        return getJwt(new Jwt.Key(scopeSet));
    }
    HeaderValues serviceId = clientRequest.getRequestHeaders().get(ClientConfig.SERVICE_ID);
    if(serviceId != null) {
        return getJwt(new Jwt.Key(serviceId.getFirst()));
    }
    return getJwt(new Jwt.Key());
}
 
Example #19
Source Project: light-4j   Author: networknt   File: ClientRequestComposerProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ClientRequest composeClientRequest(TokenRequest tokenRequest) {
    ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath(tokenRequest.getUri());
    request.getRequestHeaders().put(Headers.HOST, "localhost");
    request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
    request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/x-www-form-urlencoded");
    return request;
}
 
Example #20
Source Project: light-4j   Author: networknt   File: ClientRequestComposerProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ClientRequest composeClientRequest(TokenRequest tokenRequest) {
    final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath(tokenRequest.getUri());
    request.getRequestHeaders().put(Headers.HOST, "localhost");
    request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
    request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/x-www-form-urlencoded");
    request.getRequestHeaders().put(Headers.AUTHORIZATION, OauthHelper.getBasicAuthHeader(tokenRequest.getClientId(), tokenRequest.getClientSecret()));
    return request;
}
 
Example #21
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 #22
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 #23
Source Project: spring4-understanding   Author: langtianya   File: UndertowXhrTransport.java    License: Apache License 2.0 5 votes vote down vote up
private void executeReceiveRequest(final TransportRequest transportRequest,
		final URI url, final HttpHeaders headers, final XhrClientSockJsSession session,
		final SettableListenableFuture<WebSocketSession> connectFuture) {

	if (logger.isTraceEnabled()) {
		logger.trace("Starting XHR receive request for " + url);
	}

	ClientCallback<ClientConnection> clientCallback = new ClientCallback<ClientConnection>() {
		@Override
		public void completed(ClientConnection connection) {
			ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath(url.getPath());
			HttpString headerName = HttpString.tryFromString(HttpHeaders.HOST);
			request.getRequestHeaders().add(headerName, url.getHost());
			addHttpHeaders(request, headers);
			HttpHeaders httpHeaders = transportRequest.getHttpRequestHeaders();
			connection.sendRequest(request, createReceiveCallback(transportRequest,
					url, httpHeaders, session, connectFuture));
		}

		@Override
		public void failed(IOException ex) {
			throw new SockJsTransportFailureException("Failed to execute request to " + url, ex);
		}
	};

	this.undertowBufferSupport.httpClientConnect(this.httpClient, clientCallback, url, worker, this.optionMap);
}
 
Example #24
Source Project: spring4-understanding   Author: langtianya   File: UndertowXhrTransport.java    License: Apache License 2.0 5 votes vote down vote up
private static void addHttpHeaders(ClientRequest request, HttpHeaders headers) {
	HeaderMap headerMap = request.getRequestHeaders();
	for (String name : headers.keySet()) {
		for (String value : headers.get(name)) {
			headerMap.add(HttpString.tryFromString(name), value);
		}
	}
}
 
Example #25
Source Project: hawkular-metrics   Author: hawkular   File: TokenAuthenticator.java    License: Apache License 2.0 5 votes vote down vote up
private ClientRequest buildClientRequest(AuthContext context) {
    ClientRequest request = new ClientRequest().setMethod(POST).setPath(ACCESS_URI);
    String host = kubernetesMasterUri.getHost();
    int port = kubernetesMasterUri.getPort();
    String hostHeader = (port == -1) ? host : (host + ":" + port);
    request.getRequestHeaders()
            .add(HOST, hostHeader)
            .add(ACCEPT, "application/json")
            .add(CONTENT_TYPE, "application/json")
            .add(AUTHORIZATION, context.authorizationHeader)
            .add(CONTENT_LENGTH, context.subjectAccessReview.length());
    return request;
}
 
Example #26
Source Project: lams   Author: lamsfoundation   File: AjpClientConnection.java    License: GNU General Public License v2.0 4 votes vote down vote up
private void initiateRequest(AjpClientExchange AjpClientExchange) {
    currentRequest = AjpClientExchange;
    ClientRequest request = AjpClientExchange.getRequest();

    String connectionString = request.getRequestHeaders().getFirst(CONNECTION);
    if (connectionString != null) {
        if (CLOSE.equalToString(connectionString)) {
            state |= CLOSE_REQ;
        }
    } else if (request.getProtocol() != Protocols.HTTP_1_1) {
        state |= CLOSE_REQ;
    }
    if (request.getRequestHeaders().contains(UPGRADE)) {
        state |= UPGRADE_REQUESTED;
    }

    long length = 0;
    String fixedLengthString = request.getRequestHeaders().getFirst(CONTENT_LENGTH);
    String transferEncodingString = request.getRequestHeaders().getLast(TRANSFER_ENCODING);

    if (fixedLengthString != null) {
        length = Long.parseLong(fixedLengthString);
    } else if (transferEncodingString != null) {
        length = -1;
    }

    AjpClientRequestClientStreamSinkChannel sinkChannel = connection.sendRequest(request.getMethod(), request.getPath(), request.getProtocol(), request.getRequestHeaders(), request, requestFinishListener);
    currentRequest.setRequestChannel(sinkChannel);

    AjpClientExchange.invokeReadReadyCallback(AjpClientExchange);
    if (length == 0) {
        //if there is no content we flush the response channel.
        //otherwise it is up to the user
        try {
            sinkChannel.shutdownWrites();
            if (!sinkChannel.flush()) {
                handleFailedFlush(sinkChannel);
            }
        } catch (Throwable t) {
            handleError((t instanceof IOException) ? (IOException) t : new IOException(t));
        }
    }
}
 
Example #27
Source Project: lams   Author: lamsfoundation   File: AjpClientExchange.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public ClientRequest getRequest() {
    return request;
}
 
Example #28
Source Project: lams   Author: lamsfoundation   File: Http2ClientExchange.java    License: GNU General Public License v2.0 4 votes vote down vote up
public Http2ClientExchange(ClientConnection clientConnection, Http2StreamSinkChannel request, ClientRequest clientRequest) {
    this.clientConnection = clientConnection;
    this.request = request;
    this.clientRequest = clientRequest;
}
 
Example #29
Source Project: lams   Author: lamsfoundation   File: Http2ClientExchange.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public ClientRequest getRequest() {
    return clientRequest;
}
 
Example #30
Source Project: lams   Author: lamsfoundation   File: HttpClientConnection.java    License: GNU General Public License v2.0 4 votes vote down vote up
private void initiateRequest(HttpClientExchange httpClientExchange) {
    this.requestCount++;
    currentRequest = httpClientExchange;
    pendingResponse = new HttpResponseBuilder();
    ClientRequest request = httpClientExchange.getRequest();

    String connectionString = request.getRequestHeaders().getFirst(Headers.CONNECTION);
    if (connectionString != null) {
        if (Headers.CLOSE.equalToString(connectionString)) {
            state |= CLOSE_REQ;
        } else if (Headers.UPGRADE.equalToString(connectionString)) {
            state |= UPGRADE_REQUESTED;
        }
    } else if (request.getProtocol() != Protocols.HTTP_1_1) {
        state |= CLOSE_REQ;
    }
    if (request.getRequestHeaders().contains(Headers.UPGRADE)) {
        state |= UPGRADE_REQUESTED;
    }
    if(request.getMethod().equals(Methods.CONNECT)) {
        //we treat CONNECT like upgrade requests
        state |= UPGRADE_REQUESTED;
    }

    //setup the client request conduits
    final ConduitStreamSourceChannel sourceChannel = connection.getSourceChannel();
    sourceChannel.setReadListener(clientReadListener);
    sourceChannel.resumeReads();

    ConduitStreamSinkChannel sinkChannel = connection.getSinkChannel();
    StreamSinkConduit conduit = originalSinkConduit;
    HttpRequestConduit httpRequestConduit = new HttpRequestConduit(conduit, bufferPool, request);
    httpClientExchange.setRequestConduit(httpRequestConduit);
    conduit = httpRequestConduit;

    String fixedLengthString = request.getRequestHeaders().getFirst(Headers.CONTENT_LENGTH);
    String transferEncodingString = request.getRequestHeaders().getLast(Headers.TRANSFER_ENCODING);

    boolean hasContent = true;

    if (fixedLengthString != null) {
        try {
            long length = Long.parseLong(fixedLengthString);
            conduit = new ClientFixedLengthStreamSinkConduit(conduit, length, false, false, currentRequest);
            hasContent = length != 0;
        } catch (NumberFormatException e) {
            handleError(e);
            return;
        }
    } else if (transferEncodingString != null) {
        if (!transferEncodingString.toLowerCase(Locale.ENGLISH).contains(Headers.CHUNKED.toString())) {
            handleError(UndertowClientMessages.MESSAGES.unknownTransferEncoding(transferEncodingString));
            return;
        }
        conduit = new ChunkedStreamSinkConduit(conduit, httpClientExchange.getConnection().getBufferPool(), false, false, httpClientExchange.getRequest().getRequestHeaders(), requestFinishListener, httpClientExchange);
    } else {
        conduit = new ClientFixedLengthStreamSinkConduit(conduit, 0, false, false, currentRequest);
        hasContent = false;
    }
    sinkChannel.setConduit(conduit);

    httpClientExchange.invokeReadReadyCallback();
    if (!hasContent) {
        //if there is no content we flush the response channel.
        //otherwise it is up to the user
        try {
            sinkChannel.shutdownWrites();
            if (!sinkChannel.flush()) {
                sinkChannel.setWriteListener(ChannelListeners.flushingChannelListener(null, new ChannelExceptionHandler<ConduitStreamSinkChannel>() {
                    @Override
                    public void handleException(ConduitStreamSinkChannel channel, IOException exception) {
                        handleError(exception);
                    }
                }));
                sinkChannel.resumeWrites();
            }
        } catch (Throwable t) {
            handleError(t);
        }
    }
}