List of usage examples for org.apache.http.client.utils URIUtils extractHost
public static HttpHost extractHost(final URI uri)
From source file:org.ocpsoft.rewrite.servlet.config.proxy.ProxyServlet.java
/** Copy request headers from the servlet client to the proxy request. */ protected void copyRequestHeaders(HttpServletRequest servletRequest, HttpRequest proxyRequest) { /*/*from www. j a v a 2 s .c om*/ * Get an Enumeration of all of the header names sent by the client */ Enumeration<String> enumerationOfHeaderNames = servletRequest.getHeaderNames(); while (enumerationOfHeaderNames.hasMoreElements()) { String headerName = enumerationOfHeaderNames.nextElement(); // Instead the content-length is effectively set via InputStreamEntity if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) continue; if (hopByHopHeaders.containsHeader(headerName)) continue; Enumeration<String> headers = servletRequest.getHeaders(headerName); while (headers.hasMoreElements()) { /* * sometimes more than one value */ String headerValue = headers.nextElement(); /* * In case the proxy host is running multiple virtual servers, rewrite the Host header to ensure that we get * content from the correct virtual server */ if (headerName.equalsIgnoreCase(HttpHeaders.HOST)) { HttpHost host = URIUtils.extractHost(this.targetUriObj); headerValue = host.getHostName(); if (host.getPort() != -1) headerValue += ":" + host.getPort(); } proxyRequest.addHeader(headerName, headerValue); } } }
From source file:com.springsource.insight.plugin.apache.http.hc4.HttpClientExecutionCollectionAspectTest.java
private void runHttpHostRequestTest(String testName, HttpContext context) throws Exception { runHttpRequestTest(testName, URIUtils.extractHost(new URI(createTestUri(testName))), context); }
From source file:br.com.autonomiccs.apacheCloudStack.client.ApacheCloudStackClient.java
/** * It configures the cookie domain with the domain of the Apache CloudStack that is being accessed. * The domain is extracted from {@link #url} variable. *//*w w w .jav a2 s . co m*/ protected void configureDomainForCookie(BasicClientCookie cookie) { try { HttpHost httpHost = URIUtils.extractHost(new URI(url)); String domain = httpHost.getHostName(); cookie.setDomain(domain); } catch (URISyntaxException e) { throw new ApacheCloudStackClientRuntimeException(e); } }
From source file:kornell.server.ProxyServlet.java
/** Copy request headers from the servlet client to the proxy request. */ protected void copyRequestHeaders(HttpServletRequest servletRequest, HttpRequest proxyRequest) { // Get an Enumeration of all of the header names sent by the client Enumeration enumerationOfHeaderNames = servletRequest.getHeaderNames(); while (enumerationOfHeaderNames.hasMoreElements()) { String headerName = (String) enumerationOfHeaderNames.nextElement(); //Instead the content-length is effectively set via InputStreamEntity if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) continue; if (hopByHopHeaders.containsHeader(headerName)) continue; Enumeration headers = servletRequest.getHeaders(headerName); while (headers.hasMoreElements()) {//sometimes more than one value String headerValue = (String) headers.nextElement(); // In case the proxy host is running multiple virtual servers, // rewrite the Host header to ensure that we get content from // the correct virtual server if (headerName.equalsIgnoreCase(HttpHeaders.HOST)) { HttpHost host = URIUtils.extractHost(this.targetUriObj); headerValue = host.getHostName(); if (host.getPort() != -1) headerValue += ":" + host.getPort(); }//from ww w. j a va 2 s. c om proxyRequest.addHeader(headerName, headerValue); } } }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java
@Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { String clientId = request.getParameter(OAuth2Utils.CLIENT_ID); String redirectUri = request.getParameter(OAuth2Utils.REDIRECT_URI); String[] responseTypes = ofNullable(request.getParameter(OAuth2Utils.RESPONSE_TYPE)) .map(rt -> rt.split(" ")).orElse(new String[0]); ClientDetails client;//from w w w. j a v a 2s . c o m try { client = getClientServiceExtention().loadClientByClientId(clientId, IdentityZoneHolder.get().getId()); } catch (ClientRegistrationException e) { logger.debug("[prompt=none] Unable to look up client for client_id=" + clientId, e); response.setStatus(HttpStatus.BAD_REQUEST.value()); return; } Set<String> redirectUris = ofNullable(client.getRegisteredRedirectUri()).orElse(EMPTY_SET); //if the client doesn't have a redirect uri set, the parameter is required. if (redirectUris.size() == 0 && !hasText(redirectUri)) { logger.debug("[prompt=none] Missing redirect_uri"); response.setStatus(HttpStatus.BAD_REQUEST.value()); return; } String resolvedRedirect; try { resolvedRedirect = redirectResolver.resolveRedirect(redirectUri, client); } catch (RedirectMismatchException rme) { logger.debug("[prompt=none] Invalid redirect " + redirectUri + " did not match one of the registered values"); response.setStatus(HttpStatus.BAD_REQUEST.value()); return; } HttpHost httpHost = URIUtils.extractHost(URI.create(resolvedRedirect)); String sessionState = openIdSessionStateCalculator.calculate("", clientId, httpHost.toURI()); boolean implicit = stream(responseTypes).noneMatch("code"::equalsIgnoreCase); String redirectLocation; String errorCode = authException instanceof InteractionRequiredException ? "interaction_required" : "login_required"; if (implicit) { redirectLocation = addFragmentComponent(resolvedRedirect, "error=" + errorCode); redirectLocation = addFragmentComponent(redirectLocation, "session_state=" + sessionState); } else { redirectLocation = addQueryParameter(resolvedRedirect, "error", errorCode); redirectLocation = addQueryParameter(redirectLocation, "session_state", sessionState); } response.sendRedirect(redirectLocation); }
From source file:org.opengeoportal.proxy.controllers.OldDynamicOgcController.java
@SuppressWarnings("deprecation") private void doProxy(String remoteUrl, HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // Make the Request //note: we won't transfer the protocol version because I'm not sure it would truly be compatible try {/*ww w. ja va2s .c om*/ this.targetUri = new URI(remoteUrl); } catch (URISyntaxException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //Need to handle https, but think about "restricted" layers for now. Some institutions don't really have good protection for restricted layers. Does this open up potential for security //problems for those folks? if (servletRequest.getScheme().equals("https")) { //actually, what matters the most is if the remote url is https } BasicHttpEntityEnclosingRequest proxyRequest = new BasicHttpEntityEnclosingRequest( servletRequest.getMethod(), rewriteUrlFromRequest(servletRequest)); copyRequestHeaders(servletRequest, proxyRequest); // Add the input entity (streamed) then execute the request. HttpResponse proxyResponse = null; InputStream servletRequestInputStream = servletRequest.getInputStream(); try { try { proxyRequest.setEntity( new InputStreamEntity(servletRequestInputStream, servletRequest.getContentLength())); // Execute the request logger.debug("proxy " + servletRequest.getMethod() + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest); } finally { closeQuietly(servletRequestInputStream); } // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); logger.info("Status from remote server: " + Integer.toString(statusCode)); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { EntityUtils.consume(proxyResponse.getEntity()); return; } // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the // reason along too. //noinspection deprecation servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); copyResponseHeaders(proxyResponse, servletResponse); // Send the content to the client copyResponseEntity(proxyResponse, servletResponse); } catch (Exception e) { //abort request, according to best practice with HttpClient if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } if (e instanceof RuntimeException) throw (RuntimeException) e; if (e instanceof ServletException) throw (ServletException) e; throw new RuntimeException(e); } }
From source file:org.opengeoportal.proxy.controllers.OldDynamicOgcController.java
/** Copy request headers from the servlet client to the proxy request. */ protected void copyRequestHeaders(HttpServletRequest servletRequest, HttpRequest proxyRequest) { // Get an Enumeration of all of the header names sent by the client Enumeration enumerationOfHeaderNames = servletRequest.getHeaderNames(); while (enumerationOfHeaderNames.hasMoreElements()) { String headerName = (String) enumerationOfHeaderNames.nextElement(); //TODO why? // if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) // continue; if (hopByHopHeaders.containsHeader(headerName)) continue; // As per the Java Servlet API 2.5 documentation: // Some headers, such as Accept-Language can be sent by clients // as several headers each with a different value rather than // sending the header as a comma separated list. // Thus, we get an Enumeration of the header values sent by the client Enumeration headers = servletRequest.getHeaders(headerName); while (headers.hasMoreElements()) { String headerValue = (String) headers.nextElement(); //Don't do this unless we need to /*if (headerName.equalsIgnoreCase(HttpHeaders.USER_AGENT)){ headerValue = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0"; }*///w w w. j av a 2 s. c om // In case the proxy host is running multiple virtual servers, // rewrite the Host header to ensure that we get content from // the correct virtual server if (headerName.equalsIgnoreCase(HttpHeaders.HOST)) { HttpHost host = URIUtils.extractHost(this.targetUri); headerValue = host.getHostName(); if (host.getPort() != -1) headerValue += ":" + host.getPort(); } proxyRequest.addHeader(headerName, headerValue); } } }
From source file:org.opengeoportal.proxy.controllers.DynamicOgcController.java
@SuppressWarnings("deprecation") private void doProxy(String remoteUrl, HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // Make the Request //note: we won't transfer the protocol version because I'm not sure it would truly be compatible try {//from www .j av a 2s. co m this.targetUri = new URI(remoteUrl); } catch (URISyntaxException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //Need to handle https, but think about "restricted" layers for now. Some institutions don't really have good protection for restricted layers. Does this open up potential for security //problems for those folks? if (servletRequest.getScheme().equals("https")) { //actually, what matters the most is if the remote url is https } BasicHttpEntityEnclosingRequest proxyRequest = new BasicHttpEntityEnclosingRequest( servletRequest.getMethod(), rewriteUrlFromRequest(servletRequest)); //HttpGet httpget = new HttpGet(rewriteUrlFromRequest(servletRequest)); copyRequestHeaders(servletRequest, proxyRequest); // Add the input entity (streamed) then execute the request. HttpResponse proxyResponse = null; InputStream servletRequestInputStream = servletRequest.getInputStream(); CloseableHttpClient proxyClient = ogpHttpClient.getCloseableHttpClient(); try { try { //proxyRequest.setEntity(new InputStreamEntity(servletRequestInputStream)); proxyRequest.setEntity( new InputStreamEntity(servletRequestInputStream, servletRequest.getContentLength())); // Execute the request logger.debug("proxy " + servletRequest.getMethod() + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest); } finally { IOUtils.closeQuietly(servletRequestInputStream); } // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); logger.info("Status from remote server: " + Integer.toString(statusCode)); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { EntityUtils.consume(proxyResponse.getEntity()); return; } // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the // reason along too. //noinspection deprecation servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); copyResponseHeaders(proxyResponse, servletResponse); // Send the content to the client copyResponseEntity(proxyResponse, servletResponse); } catch (Exception e) { //abort request, according to best practice with HttpClient if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } if (e instanceof RuntimeException) throw (RuntimeException) e; if (e instanceof ServletException) throw (ServletException) e; throw new RuntimeException(e); } }
From source file:org.apache.nifi.remote.util.SiteToSiteRestApiClient.java
/** * <p>/*from w w w .j av a 2 s . c o m*/ * Initiate a transaction for sending data. * </p> * * <p> * If a proxy server requires auth, the proxy server returns 407 response with available auth schema such as basic or digest. * Then client has to resend the same request with its credential added. * This mechanism is problematic for sending data from NiFi. * </p> * * <p> * In order to resend a POST request with auth param, * NiFi has to either read flow-file contents to send again, or keep the POST body somewhere. * If we store that in memory, it would causes OOM, or storing it on disk slows down performance. * Rolling back processing session would be overkill. * Reading flow-file contents only when it's ready to send in a streaming way is ideal. * </p> * * <p> * Additionally, the way proxy authentication is done is vary among Proxy server software. * Some requires 407 and resend cycle for every requests, while others keep a connection between a client and * the proxy server, then consecutive requests skip auth steps. * The problem is, that how should we behave is only told after sending a request to the proxy. * </p> * * In order to handle above concerns correctly and efficiently, this method do the followings: * * <ol> * <li>Send a GET request to controller resource, to initiate an HttpAsyncClient. The instance will be used for further requests. * This is not required by the Site-to-Site protocol, but it can setup proxy auth state safely.</li> * <li>Send a POST request to initiate a transaction. While doing so, it captures how a proxy server works. * If 407 and resend cycle occurs here, it implies that we need to do the same thing again when we actually send the data. * Because if the proxy keeps using the same connection and doesn't require an auth step, it doesn't do so here.</li> * <li>Then this method stores whether the final POST request should wait for the auth step. * So that {@link #openConnectionForSend} can determine when to produce contents.</li> * </ol> * * <p> * The above special sequence is only executed when a proxy instance is set, and its username is set. * </p> * * @param post a POST request to establish transaction * @return POST request response * @throws IOException thrown if the post request failed */ private HttpResponse initiateTransactionForSend(final HttpPost post) throws IOException { if (shouldCheckProxyAuth()) { final CloseableHttpAsyncClient asyncClient = getHttpAsyncClient(); final HttpGet get = createGetControllerRequest(); final Future<HttpResponse> getResult = asyncClient.execute(get, null); try { final HttpResponse getResponse = getResult.get(readTimeoutMillis, TimeUnit.MILLISECONDS); logger.debug("Proxy auth check has done. getResponse={}", getResponse.getStatusLine()); } catch (final ExecutionException e) { logger.debug("Something has happened at get controller requesting thread for proxy auth check. {}", e.getMessage()); throw toIOException(e); } catch (TimeoutException | InterruptedException e) { throw new IOException(e); } } final HttpAsyncRequestProducer asyncRequestProducer = new HttpAsyncRequestProducer() { private boolean requestHasBeenReset = false; @Override public HttpHost getTarget() { return URIUtils.extractHost(post.getURI()); } @Override public HttpRequest generateRequest() throws IOException, HttpException { final BasicHttpEntity entity = new BasicHttpEntity(); post.setEntity(entity); return post; } @Override public void produceContent(ContentEncoder encoder, IOControl ioctrl) throws IOException { encoder.complete(); if (shouldCheckProxyAuth() && requestHasBeenReset) { logger.debug("Produced content again, assuming the proxy server requires authentication."); proxyAuthRequiresResend.set(true); } } @Override public void requestCompleted(HttpContext context) { debugProxyAuthState(context); } @Override public void failed(Exception ex) { final String msg = String.format("Failed to create transaction for %s", post.getURI()); logger.error(msg, ex); eventReporter.reportEvent(Severity.WARNING, EVENT_CATEGORY, msg); } @Override public boolean isRepeatable() { return true; } @Override public void resetRequest() throws IOException { requestHasBeenReset = true; } @Override public void close() throws IOException { } }; final Future<HttpResponse> responseFuture = getHttpAsyncClient().execute(asyncRequestProducer, new BasicAsyncResponseConsumer(), null); final HttpResponse response; try { response = responseFuture.get(readTimeoutMillis, TimeUnit.MILLISECONDS); } catch (final ExecutionException e) { logger.debug("Something has happened at initiate transaction requesting thread. {}", e.getMessage()); throw toIOException(e); } catch (TimeoutException | InterruptedException e) { throw new IOException(e); } return response; }