io.undertow.client.ClientRequest Java Examples
The following examples show how to use
io.undertow.client.ClientRequest.
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: TokenAuthenticator.java From hawkular-metrics with Apache License 2.0 | 6 votes |
/** * 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 #2
Source File: ConsulClientImpl.java From light-4j with Apache License 2.0 | 6 votes |
/** * 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 File: HttpClientConnection.java From lams with GNU General Public License v2.0 | 6 votes |
@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 #4
Source File: ClientRequestComposerProvider.java From light-4j with Apache License 2.0 | 5 votes |
@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 #5
Source File: ValidatorHandlerTest.java From light-rest-4j with Apache License 2.0 | 5 votes |
@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 #6
Source File: ValidatorHandlerTest.java From light-rest-4j with Apache License 2.0 | 5 votes |
@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 |
@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 #8
Source File: ValidatorHandlerTest.java From light-rest-4j with Apache License 2.0 | 5 votes |
@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 #9
Source File: ValidatorHandlerTest.java From light-rest-4j with Apache License 2.0 | 5 votes |
@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 #10
Source File: ValidatorHandlerTest.java From light-rest-4j with Apache License 2.0 | 5 votes |
@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 #11
Source File: TokenManager.java From light-4j with Apache License 2.0 | 5 votes |
/** * 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 #12
Source File: UndertowXhrTransport.java From spring-analysis-note with MIT License | 5 votes |
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 #13
Source File: ClientRequestComposerProvider.java From light-4j with Apache License 2.0 | 5 votes |
@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 #14
Source File: DefaultConfigLoader.java From light-4j with Apache License 2.0 | 5 votes |
/** * 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 #15
Source File: DefaultConfigLoader.java From light-4j with Apache License 2.0 | 5 votes |
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: UndertowXhrTransport.java From spring4-understanding with Apache License 2.0 | 5 votes |
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 #17
Source File: UndertowXhrTransport.java From spring4-understanding with Apache License 2.0 | 5 votes |
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 #18
Source File: TokenAuthenticator.java From hawkular-metrics with Apache License 2.0 | 5 votes |
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 #19
Source File: UndertowXhrTransport.java From spring-analysis-note with MIT License | 5 votes |
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 #20
Source File: UndertowXhrTransport.java From java-technology-stack with MIT License | 5 votes |
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 #21
Source File: HttpClientExchange.java From lams with GNU General Public License v2.0 | 5 votes |
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 #22
Source File: UndertowXhrTransport.java From java-technology-stack with MIT License | 5 votes |
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 #23
Source File: AjpClientConnection.java From lams with GNU General Public License v2.0 | 5 votes |
@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 #24
Source File: Http2ClientConnection.java From lams with GNU General Public License v2.0 | 5 votes |
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 #25
Source File: AjpClientExchange.java From lams with GNU General Public License v2.0 | 5 votes |
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 #26
Source File: ResponseValidatorTest.java From light-rest-4j with Apache License 2.0 | 4 votes |
@Test public void testValidateResponseContentWithExchange() throws InterruptedException, ClientException, URISyntaxException, TimeoutException, ExecutionException { ClientRequest clientRequest = new ClientRequest(); CompletableFuture<ClientResponse> future = sendResponse(clientRequest, "response1"); Assert.assertTrue(future.get(3, TimeUnit.SECONDS).getResponseCode() == 200); }
Example #27
Source File: TokenAuthenticator.java From hawkular-metrics with Apache License 2.0 | 4 votes |
private void sendRequest(ClientRequest request, ClientCallback<ClientExchange> clientCallback) { clientConnection.sendRequest(request, clientCallback); }
Example #28
Source File: AjpClientConnection.java From lams with GNU General Public License v2.0 | 4 votes |
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 #29
Source File: AjpClientExchange.java From lams with GNU General Public License v2.0 | 4 votes |
@Override public ClientRequest getRequest() { return request; }
Example #30
Source File: ClientRequestCarrier.java From light-4j with Apache License 2.0 | 4 votes |
public ClientRequestCarrier(ClientRequest clientRequest) { this.clientRequest = clientRequest; }