List of usage examples for org.apache.http.client.utils URIUtils extractHost
public static HttpHost extractHost(final URI uri)
From source file:xyz.cloudbans.client.DefaultClient.java
@Override public Future<ServerPlayerJoinResponse> propagateJoin(ServerPlayerJoinRequest request) { HttpPost httpRequest = new HttpPost(buildSafe(createUri("/server/join"))); initHeaders(httpRequest);//from ww w. j a va 2 s.c om httpRequest.setEntity(createEntity(request)); return client.execute(new BasicAsyncRequestProducer(URIUtils.extractHost(config.getBaseUri()), httpRequest), SerializerConsumer.create(config.getSerializer(), ServerPlayerJoinResponse.class), DeafFutureCallback.<ServerPlayerJoinResponse>instance()); }
From source file:org.callimachusproject.test.TemporaryServerFactory.java
private synchronized TemporaryServer createTemporaryServer() { try {//from w w w . jav a 2 s. c o m final File dir = createCallimachus(origin); return new TemporaryServer() { private LocalRepositoryManager manager; private WebServer server; private CalliRepository repository; private boolean stopped; public synchronized void start() throws InterruptedException, Exception { manager = RepositoryProvider.getRepositoryManager(dir); File dataDir = manager.getRepositoryDir("callimachus"); Repository repo = manager.getRepository("callimachus"); repository = new CalliRepository(repo, dataDir); repository.setDatasourceManager(new DatasourceManager(manager, "callimachus") { protected CalliRepository createCalliRepository(URI uri, Repository delegate, File dataDir) throws OpenRDFException, IOException { CalliRepository secondary; secondary = super.createCalliRepository(uri, delegate, dataDir); String uriSpace = repository.getChangeFolder(); String webapp = repository.getCallimachusWebapp(uriSpace); secondary.setChangeFolder(uriSpace, webapp); return secondary; } }); String url = repository.getCallimachusUrl(origin, CHANGES_PATH); String schema = repository.getCallimachusUrl(origin, SCHEMA_GRAPH); repository.addSchemaGraphType(schema); repository.setChangeFolder(url); repository.setCompileRepository(true); server = new WebServer(new File(dataDir, "cache/server")); server.addOrigin(origin, repository); server.listen(new int[] { port }, new int[0]); server.start(); HttpHost host = URIUtils.extractHost(java.net.URI.create(origin + "/")); HttpClientFactory.getInstance().setProxy(host, server); Thread.sleep(100); } public synchronized void pause() throws Exception { } public synchronized void resume() throws Exception { synchronized (running) { TemporaryServer other = running.get(port); if (stopped || !this.equals(other)) { if (other != null) { other.stop(); } start(); running.put(port, this); } } } public synchronized void stop() throws Exception { if (!stopped) { server.stop(); server.destroy(); server = null; repository = null; manager.shutDown(); stopped = true; Thread.sleep(100); System.gc(); System.runFinalization(); } } public synchronized void destroy() throws Exception { stop(); FileUtil.deltree(dir); } @Override protected void finalize() throws Exception { destroy(); } public String getOrigin() { return origin; } public String getUsername() { return email; } public char[] getPassword() { return password; } public CalliRepository getRepository() { return this.repository; } public String toString() { return server.toString(); } }; } catch (Exception e) { throw new AssertionError(e); } }
From source file:org.jenkinsci.plugins.relution_publisher.net.requests.ZeroCopyFileRequestProducer.java
@Override public HttpHost getTarget() { final URI uri = URI.create(this.mRequest.getUri()); return URIUtils.extractHost(uri); }
From source file:com.google.gwt.jolokia.server.servlet.ProxyServlet.java
protected void initTarget() throws ServletException { // First try to get it from environment, maybe maven. targetUri = System.getProperty(P_TARGET_URI); log("unable to find in environment param"); if (targetUri == null) { targetUri = getConfigParam(P_TARGET_URI); }/*from ww w . j a v a 2 s. c o m*/ // Try to load target uri from the jndi properties if available. final String jndiPropertiesParam = getConfigParam(P_TARGET_JNDI_PROPERTIES); if (targetUri == null && jndiPropertiesParam != null) { log("Attempting to read jndi properties " + jndiPropertiesParam); Properties props = loadJndiProperties(jndiPropertiesParam); final String jndiTargetParamName = getConfigParam(P_TARGET_PROPERTIES_TARGET_URI_NAME); if (jndiTargetParamName == null) { log("You did not specify a parameter for " + P_TARGET_PROPERTIES_TARGET_URI_NAME + " targetUri will be looked for in the jndi properties"); } if (props != null) { targetUri = props.getProperty(jndiTargetParamName, P_TARGET_URI); } } if (targetUri == null) { Properties props = loadProperties(); if (props != null) { targetUri = props.getProperty("targetUri"); } } if (targetUri == null) throw new ServletException(P_TARGET_URI + " is required."); // test it's valid log("targetUri is " + targetUri); try { targetUriObj = new URI(targetUri); } catch (Exception e) { throw new ServletException("Trying to process targetUri init parameter: " + e, e); } targetHost = URIUtils.extractHost(targetUriObj); }
From source file:xyz.cloudbans.client.DefaultClient.java
@Override public Future<ServerPlayerLeaveResponse> propagateLeave(ServerPlayerLeaveRequest request) { HttpPost httpRequest = new HttpPost(buildSafe(createUri("/server/leave"))); initHeaders(httpRequest);//from www. j a v a2s . c o m httpRequest.setEntity(createEntity(request)); return client.execute(new BasicAsyncRequestProducer(URIUtils.extractHost(config.getBaseUri()), httpRequest), SerializerConsumer.create(config.getSerializer(), ServerPlayerLeaveResponse.class), DeafFutureCallback.<ServerPlayerLeaveResponse>instance()); }
From source file:org.sonatype.nexus.repository.httpclient.FilteredHttpClient.java
private static HttpHost determineTarget(final HttpUriRequest request) throws ClientProtocolException { HttpHost target = null;/*w ww.j ava 2s.c o m*/ final URI requestURI = request.getURI(); if (requestURI.isAbsolute()) { target = URIUtils.extractHost(requestURI); if (target == null) { throw new ClientProtocolException("URI does not specify a valid host name: " + requestURI); } } return target; }
From source file:kornell.server.ProxyServlet.java
@Override protected void service(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 String method = servletRequest.getMethod(); String proxyRequestUri = rewriteUrlFromRequest(servletRequest); HttpRequest proxyRequest;//from w w w. j a v a2 s . co m //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body. if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); // Add the input entity (streamed) // note: we don't bother ensuring we close the servletInputStream since the container handles it eProxyRequest.setEntity( new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength())); proxyRequest = eProxyRequest; } else proxyRequest = new BasicHttpRequest(method, proxyRequestUri); copyRequestHeaders(servletRequest, proxyRequest); setXForwardedForHeader(servletRequest, proxyRequest); HttpResponse proxyResponse = null; try { // Execute the request if (doLog) { log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUriObj), proxyRequest); // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { //the response is already "committed" now without any body to send //TODO copy response headers? 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; //noinspection ConstantConditions if (e instanceof IOException) throw (IOException) e; throw new RuntimeException(e); } finally { // make sure the entire entity was consumed, so the connection is released if (proxyResponse != null) consumeQuietly(proxyResponse.getEntity()); if (proxyResponse != null) closeQuietly(servletResponse.getOutputStream()); } }
From source file:co.paralleluniverse.fibers.httpclient.FiberHttpClient.java
private static HttpHost determineTarget(final HttpUriRequest request) throws ClientProtocolException { // A null target may be acceptable if there is a default target. // Otherwise, the null target is detected in the director. HttpHost target = null;//from w w w . j av a 2 s . c o m final URI requestURI = request.getURI(); if (requestURI.isAbsolute()) { target = URIUtils.extractHost(requestURI); if (target == null) throw new ClientProtocolException("URI does not specify a valid host name: " + requestURI); } return target; }
From source file:xyz.cloudbans.client.DefaultClient.java
@Override public void registerOneTimeListener(EventListener listener, EventType... types) { URIBuilder uriBuilder = createUri("/listen").addParameter("types", StringUtils.join(",", (Object[]) types)); HttpGet httpRequest = new HttpGet(buildSafe(uriBuilder)); initHeaders(httpRequest);// w ww . jav a 2 s . com client.execute(new BasicAsyncRequestProducer(URIUtils.extractHost(config.getBaseUri()), httpRequest), SerializerConsumer.create(config.getSerializer(), Event.class), new EventCallback(listener)); }
From source file:es.upv.grycap.coreutils.fiber.http.HttpDataFetcher.java
/** * Allows fetching and saving a bunch of objects to the specified directory from a server that uses a REST or REST-like API * where each object is retrieved from the URL formed appending the object's identifier to the path of the the base URL, and * optionally from a server that uses a parameter to identify the objects. Supports additional configuration options to name * the fetched objects./*from ww w .j av a 2 s . c om*/ * @param baseUrl - base URL from where the objects will be fetched * @param queryParam - if defined, a query parameter will be appended to the base URL with the identifier of the request * @param ids - a list with the identifiers of the all requests that will be attempted * @param prefix - optionally prepend this prefix to the filenames of the saved files * @param suffix - optionally append this suffix to the filenames of the saved files * @param outdir - directory where the files will be stored * @return A {@link CompletableFuture} that allows cancellation. Once each fetch operation is completed, its status is updated * in the future with one of the possible values provided by the enumeration {@link FetchStatus}. * @throws IOException If an error occurs during the execution of the method that prevents fetching or saving the files. */ public FecthFuture fetchToDir(final URL baseUrl, final @Nullable String queryParam, final List<String> ids, final @Nullable String prefix, final @Nullable String suffix, final File outdir) throws IOException { // check mandatory parameters requireNonNull(baseUrl, "A valid URL expected"); final FecthFuture toBeCompleted = new FecthFuture( requireNonNull(ids, "A valid list of identifiers expected").stream().map(StringUtils::trimToNull) .filter(Objects::nonNull).distinct().collect(Collectors.toList())); requireNonNull(outdir, "A valid output directory expected"); checkArgument((outdir.isDirectory() && outdir.canWrite()) || outdir.mkdirs(), new StringBuilder("Cannot write to the output directory: ").append(outdir.getAbsolutePath()) .toString()); // get optional parameters final Optional<String> queryParam2 = ofNullable(trimToNull(queryParam)); final String prefix2 = ofNullable(prefix).orElse(""); final String suffix2 = ofNullable(suffix).orElse(""); try (final CloseableHttpAsyncClient asyncHttpClient = createFiberCloseableHttpAsyncClient()) { asyncHttpClient.start(); final UrlBuilder urlBuilder = getUrlBuilder(baseUrl); // an explanation is needed since this code is instrumented by Quasar and Comsat: requests are created during the first part of // this lambda expression (map), but they are not executed until the get() method is called in the second part of the expression // (forEach). Here that parallel stream is used to block and wait for the requests to complete. In case that a single stream is // used, each request will be created and executed sequentially. Therefore, the alternative to parallel stream is to separate // the lambda expression in two loops, creating the requests in the first loop and calling get() in the second one. toBeCompleted.monList.parallelStream().map(m -> { try { // create output file final File outfile = new File(outdir, new StringBuilder(prefix2).append(m.id).append(suffix2).append(".partial").toString()); checkState(outfile.createNewFile(), new StringBuilder("Cannot create the output file: ") .append(outfile.getAbsolutePath()).toString()); // create the HTTP request final HttpHost target = URIUtils.extractHost(baseUrl.toURI()); final HttpRequest request = new BasicHttpRequest("GET", urlBuilder.buildRelativeUrl(queryParam2.isPresent() ? null : m.id, queryParam2.isPresent() ? of(queryParam2.get(), m.id) : null)); final HttpAsyncRequestProducer producer = new BasicAsyncRequestProducer(target, request); // create the consumer final ZeroCopyConsumer<File> consumer = new ZeroCopyConsumer<File>(outfile) { @Override protected File process(final HttpResponse response, final File file, final ContentType contentType) throws Exception { final StatusLine status = response.getStatusLine(); if (LOGGER.isDebugEnabled()) LOGGER.debug( new StringBuilder("Got file: statusCode=").append(status.getStatusCode()) .append(", file=").append(file.getAbsolutePath()).toString()); if (status.getStatusCode() != HttpStatus.SC_OK) throw new ClientProtocolException( new StringBuilder("Object fetch failed: ").append(status).toString()); return file; } }; // prepare request m.future = asyncHttpClient.execute(producer, consumer, new FutureCallback<File>() { @Override public void cancelled() { toBeCompleted.update(m.id, FetchStatus.CANCELLED); LOGGER.info("Task cancelled"); } @Override public void completed(final File result) { try { final Path path = result.toPath(); Files.move(path, path.resolveSibling(removeEnd(result.getName(), ".partial")), REPLACE_EXISTING); toBeCompleted.update(m.id, FetchStatus.COMPLETED); } catch (IOException ex) { toBeCompleted.update(m.id, FetchStatus.FAILED); LOGGER.error("Fecth failed to move file to its final destination with error", ex); } } @Override public void failed(final Exception ex) { toBeCompleted.update(m.id, FetchStatus.FAILED); LOGGER.error("Fecth failed with error", ex); } }); } catch (Exception e) { LOGGER.error(new StringBuilder("Failed to fetch object with id: ").append(m.id).toString(), e); } return m; }).forEach(m -> { try { // submit requests and wait for completion m.future.get(); } catch (Exception ignore) { /* exceptions are handled in the callback functions */ } }); } return toBeCompleted; }