Example usage for org.apache.http.client.utils URIUtils extractHost

List of usage examples for org.apache.http.client.utils URIUtils extractHost

Introduction

In this page you can find the example usage for org.apache.http.client.utils URIUtils extractHost.

Prototype

public static HttpHost extractHost(final URI uri) 

Source Link

Document

Extracts target host from the given URI .

Usage

From source file:org.yamj.core.tools.web.PoolingHttpClient.java

private static HttpHost determineTarget(HttpUriRequest request) throws ClientProtocolException {
    HttpHost target = null;//from w ww. j  a  v a2s . c  o  m
    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:org.eclipse.aether.transport.http.HttpTransporter.java

HttpTransporter(RemoteRepository repository, RepositorySystemSession session) throws NoTransporterException {
    if (!"http".equalsIgnoreCase(repository.getProtocol())
            && !"https".equalsIgnoreCase(repository.getProtocol())) {
        throw new NoTransporterException(repository);
    }//from w w w  .  j av a 2 s  .c  o m
    try {
        baseUri = new URI(repository.getUrl()).parseServerAuthority();
        if (baseUri.isOpaque()) {
            throw new URISyntaxException(repository.getUrl(), "URL must not be opaque");
        }
        server = URIUtils.extractHost(baseUri);
        if (server == null) {
            throw new URISyntaxException(repository.getUrl(), "URL lacks host name");
        }
    } catch (URISyntaxException e) {
        throw new NoTransporterException(repository, e.getMessage(), e);
    }
    proxy = toHost(repository.getProxy());

    repoAuthContext = AuthenticationContext.forRepository(session, repository);
    proxyAuthContext = AuthenticationContext.forProxy(session, repository);

    state = new LocalState(session, repository, new SslConfig(session, repoAuthContext));

    headers = ConfigUtils.getMap(session, Collections.emptyMap(),
            ConfigurationProperties.HTTP_HEADERS + "." + repository.getId(),
            ConfigurationProperties.HTTP_HEADERS);

    DefaultHttpClient client = new DefaultHttpClient(state.getConnectionManager());

    configureClient(client.getParams(), session, repository, proxy);

    client.setCredentialsProvider(toCredentialsProvider(server, repoAuthContext, proxy, proxyAuthContext));

    this.client = new DecompressingHttpClient(client);
}

From source file:io.hops.hopsworks.api.admin.YarnUIProxyServlet.java

protected void initTarget() throws ServletException {
    // TODO - should get the Kibana URI from Settings.java
    //    targetUri = Settings.getKibanaUri();
    targetUri = settings.getYarnWebUIAddress();
    if (!targetUri.contains("http://")) {
        targetUri = "http://" + targetUri;
    }//from   www .ja va  2s. co  m
    if (targetUri == null) {
        throw new ServletException(P_TARGET_URI + " is required.");
    }
    //test it's valid
    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:io.hops.hopsworks.api.admin.llap.LlapMonitorProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    // Check if the user is logged in
    if (servletRequest.getUserPrincipal() == null) {
        servletResponse.sendError(403, "User is not logged in");
        return;//  w  ww .j  a  v a  2  s  . c om
    }

    // Check that the user is an admin
    boolean isAdmin = servletRequest.isUserInRole("HOPS_ADMIN");
    if (!isAdmin) {
        servletResponse.sendError(Response.Status.BAD_REQUEST.getStatusCode(),
                "You don't have the access right for this application");
        return;
    }

    // The path we will receive is [host]/llapmonitor/llaphost/
    // We need to extract the llaphost to redirect the request
    String[] pathInfoSplits = servletRequest.getPathInfo().split("/");
    String llapHost = pathInfoSplits[1];

    //Now rewrite the URL
    StringBuffer urlBuf = new StringBuffer();//note: StringBuilder isn't supported by Matcher
    Matcher matcher = TEMPLATE_PATTERN.matcher(targetUriTemplate);
    if (matcher.find()) {
        matcher.appendReplacement(urlBuf, llapHost);
    }

    matcher.appendTail(urlBuf);
    String newTargetUri = urlBuf.toString();
    servletRequest.setAttribute(ATTR_TARGET_URI, newTargetUri);
    URI targetUriObj;
    try {
        targetUriObj = new URI(newTargetUri);
    } catch (Exception e) {
        throw new ServletException("Rewritten targetUri is invalid: " + newTargetUri, e);
    }
    servletRequest.setAttribute(ATTR_TARGET_HOST, URIUtils.extractHost(targetUriObj));

    super.service(servletRequest, servletResponse);
}

From source file:xyz.cloudbans.client.DefaultClient.java

@Override
public Future<BanResponse> deleteBan(UUID banId) {
    HttpDelete httpRequest = new HttpDelete(buildSafe(createUri("/ban/" + banId)));
    initHeaders(httpRequest);//  w  w w  .j a  va2 s .co m

    return client.execute(new BasicAsyncRequestProducer(URIUtils.extractHost(config.getBaseUri()), httpRequest),
            SerializerConsumer.create(config.getSerializer(), BanResponse.class),
            DeafFutureCallback.<BanResponse>instance());
}

From source file:io.hops.hopsworks.api.admin.HDFSUIProxyServlet.java

protected void initTarget() throws ServletException {
    // TODO - should get the Kibana URI from Settings.java
    //    targetUri = Settings.getKibanaUri();
    targetUri = settings.getHDFSWebUIAddress();

    if (targetUri == null) {
        throw new ServletException(P_TARGET_URI + " is required.");
    }//w w  w  .j av a2  s . c o m

    if (settings.getHopsRpcTls()) {
        if (!targetUri.contains("https://")) {
            targetUri = "https://" + targetUri;
        }
    } else {
        if (!targetUri.contains("http://")) {
            targetUri = "http://" + targetUri;
        }
    }

    //test it's valid
    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:io.uploader.drive.drive.largefile.DriveResumableUpload.java

public String getFileId() throws IOException {
    logger.info("Querying file id of completed upload...");
    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response = null;
    try {//from  ww w.  j  a v a 2s .c om
        httpclient = getHttpClient();
        BasicHttpRequest httpreq = new BasicHttpRequest("PUT", location);
        httpreq.addHeader("Authorization", auth.getAuthHeader());
        httpreq.addHeader("Content-Length", "0");
        httpreq.addHeader("Content-Range", "bytes */" + getFileSizeString());
        response = httpclient.execute(URIUtils.extractHost(uri), httpreq);
        BufferedHttpEntity entity = new BufferedHttpEntity(response.getEntity());
        EntityUtils.consume(response.getEntity());
        String retSrc = EntityUtils.toString(entity);
        if (useOldApi) {
            // Old API will return XML!
            JSONObject result = XML.toJSONObject(retSrc);
            return result.getJSONObject("entry").getString("gd:resourceId").replace("file:", "");
        } else {
            JSONObject result = new JSONObject(retSrc);
            return result.getString("id");
        }
    } finally {
        if (response != null) {
            response.close();
        }
        if (httpclient != null) {
            httpclient.close();
        }
    }
}

From source file:org.mitre.dsmiley.httpproxy.URITemplateProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    //First collect params
    /*/*from  ww  w . ja v a  2 s . c om*/
     * Do not use servletRequest.getParameter(arg) because that will
     * typically read and consume the servlet InputStream (where our
     * form data is stored for POST). We need the InputStream later on.
     * So we'll parse the query string ourselves. A side benefit is
     * we can keep the proxy parameters in the query string and not
     * have to add them to a URL encoded form attachment.
     */
    String queryString = "?" + servletRequest.getQueryString();//no "?" but might have "#"
    int hash = queryString.indexOf('#');
    if (hash >= 0) {
        queryString = queryString.substring(0, hash);
    }
    List<NameValuePair> pairs;
    try {
        //note: HttpClient 4.2 lets you parse the string without building the URI
        pairs = URLEncodedUtils.parse(new URI(queryString), "UTF-8");
    } catch (URISyntaxException e) {
        throw new ServletException("Unexpected URI parsing error on " + queryString, e);
    }
    LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
    for (NameValuePair pair : pairs) {
        params.put(pair.getName(), pair.getValue());
    }

    //Now rewrite the URL
    StringBuffer urlBuf = new StringBuffer();//note: StringBuilder isn't supported by Matcher
    Matcher matcher = TEMPLATE_PATTERN.matcher(targetUriTemplate);
    while (matcher.find()) {
        String arg = matcher.group(1);
        String replacement = params.remove(arg);//note we remove
        if (replacement == null) {
            throw new ServletException("Missing HTTP parameter " + arg + " to fill the template");
        }
        matcher.appendReplacement(urlBuf, replacement);
    }
    matcher.appendTail(urlBuf);
    String newTargetUri = urlBuf.toString();
    servletRequest.setAttribute(ATTR_TARGET_URI, newTargetUri);
    URI targetUriObj;
    try {
        targetUriObj = new URI(newTargetUri);
    } catch (Exception e) {
        throw new ServletException("Rewritten targetUri is invalid: " + newTargetUri, e);
    }
    servletRequest.setAttribute(ATTR_TARGET_HOST, URIUtils.extractHost(targetUriObj));

    //Determine the new query string based on removing the used names
    StringBuilder newQueryBuf = new StringBuilder(queryString.length());
    for (Map.Entry<String, String> nameVal : params.entrySet()) {
        if (newQueryBuf.length() > 0)
            newQueryBuf.append('&');
        newQueryBuf.append(nameVal.getKey()).append('=');
        if (nameVal.getValue() != null)
            newQueryBuf.append(nameVal.getValue());
    }
    servletRequest.setAttribute(ATTR_QUERY_STRING, newQueryBuf.toString());

    super.service(servletRequest, servletResponse);
}

From source file:iqq.im.service.ApacheHttpService.java

@Override
public Future<QQHttpResponse> executeHttpRequest(QQHttpRequest request, QQHttpListener listener)
        throws QQException {
    try {//from www . jav  a  2 s . c om
        URI uri = URI.create(request.getUrl());

        if (request.getMethod().equals("POST")) {
            HttpPost httppost = new HttpPost(uri);
            HttpHost httphost = URIUtils.extractHost(uri);
            if (httphost == null) {
                LOG.error("host is null, url: " + uri.toString());
                httphost = new HttpHost(uri.getHost());
            }

            if (request.getReadTimeout() > 0) {
                HttpConnectionParams.setSoTimeout(httppost.getParams(), request.getReadTimeout());
            }
            if (request.getConnectTimeout() > 0) {
                HttpConnectionParams.setConnectionTimeout(httppost.getParams(), request.getConnectTimeout());
            }

            if (request.getFileMap().size() > 0) {
                MultipartEntity entity = new MultipartEntity();
                String charset = request.getCharset();

                Map<String, String> postMap = request.getPostMap();
                for (String key : postMap.keySet()) {
                    String value = postMap.get(key);
                    value = value == null ? "" : value;
                    entity.addPart(key, new StringBody(value, Charset.forName(charset)));
                }

                Map<String, File> fileMap = request.getFileMap();
                for (String key : fileMap.keySet()) {
                    File value = fileMap.get(key);
                    entity.addPart(new FormBodyPart(key, new FileBody(value, getMimeType(value))));
                }
                httppost.setEntity(entity);
            } else if (request.getPostMap().size() > 0) {
                List<NameValuePair> list = new ArrayList<NameValuePair>();

                Map<String, String> postMap = request.getPostMap();
                for (String key : postMap.keySet()) {
                    String value = postMap.get(key);
                    value = value == null ? "" : value;
                    list.add(new BasicNameValuePair(key, value));
                }
                httppost.setEntity(new UrlEncodedFormEntity(list, request.getCharset()));
            }
            Map<String, String> headerMap = request.getHeaderMap();
            for (String key : headerMap.keySet()) {
                httppost.addHeader(key, headerMap.get(key));
            }
            QQHttpPostRequestProducer producer = new QQHttpPostRequestProducer(httphost, httppost, listener);
            QQHttpResponseConsumer consumer = new QQHttpResponseConsumer(request, listener, cookieJar);
            QQHttpResponseCallback callback = new QQHttpResponseCallback(listener);
            Future<QQHttpResponse> future = asyncHttpClient.execute(producer, consumer, callback);
            return new ProxyFuture(future, consumer, producer);

        } else if (request.getMethod().equals("GET")) {
            HttpGet httpget = new HttpGet(uri);
            HttpHost httphost = URIUtils.extractHost(uri);
            if (httphost == null) {
                LOG.error("host is null, url: " + uri.toString());
                httphost = new HttpHost(uri.getHost());
            }
            Map<String, String> headerMap = request.getHeaderMap();
            for (String key : headerMap.keySet()) {
                httpget.addHeader(key, headerMap.get(key));
            }
            if (request.getReadTimeout() > 0) {
                HttpConnectionParams.setSoTimeout(httpget.getParams(), request.getReadTimeout());
            }
            if (request.getConnectTimeout() > 0) {
                HttpConnectionParams.setConnectionTimeout(httpget.getParams(), request.getConnectTimeout());
            }

            return asyncHttpClient.execute(new QQHttpGetRequestProducer(httphost, httpget),
                    new QQHttpResponseConsumer(request, listener, cookieJar),
                    new QQHttpResponseCallback(listener));

        } else {
            throw new QQException(QQErrorCode.IO_ERROR, "not support http method:" + request.getMethod());
        }
    } catch (IOException e) {
        throw new QQException(QQErrorCode.IO_ERROR);
    }
}

From source file:eionet.webq.service.CDREnvelopeServiceImpl.java

@Override
public ResponseEntity<byte[]> fetchFileFromCdr(UserFile file, String remoteFileUrl)
        throws FileNotAvailableException, URISyntaxException {

    HttpHeaders authorization = new HttpHeaders();
    // use user provided auth info only when the remote file is in the same host as UserFile.
    if (URIUtils.extractHost(new URI(remoteFileUrl))
            .equals(URIUtils.extractHost(new URI(file.getEnvelope())))) {
        authorization = getAuthorizationHeader(file);
    }/* w ww.  j a v  a  2s  . c  o  m*/
    ResponseEntity<byte[]> download = null;
    try {
        download = restOperations.exchange(new URI(remoteFileUrl), HttpMethod.GET,
                new HttpEntity<Object>(authorization), byte[].class);
    } catch (RestClientException e) {
        LOGGER.error("Unable to download remote file.", e);
    }
    if (download == null || !download.hasBody()) {
        throw new FileNotAvailableException("Response is not OK or body not attached for " + remoteFileUrl);
    }
    return download;
}