Example usage for java.net URI getHost

List of usage examples for java.net URI getHost

Introduction

In this page you can find the example usage for java.net URI getHost.

Prototype

public String getHost() 

Source Link

Document

Returns the host component of this URI.

Usage

From source file:com.ibm.watson.apis.conversation_enhanced.utils.HttpSolrClientUtils.java

/**
 * Creates the {@link HttpClient} to use with the Solrj
 *
 * @param url the Solr server url/*from  w  ww  .  j a  v  a 2s  .  co m*/
 * @param username the {@link RetrieveAndRank} service username
 * @param password the {@link RetrieveAndRank} service password
 * @return the {@link HttpClient}
 */
private static HttpClient createHttpClient(String url, String username, String password) {
    final URI scopeUri = URI.create(url);
    logger.info(Messages.getString("HttpSolrClientUtils.CREATING_HTTP_CLIENT")); //$NON-NLS-1$
    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(scopeUri.getHost(), scopeUri.getPort()),
            new UsernamePasswordCredentials(username, password));

    final HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(128).setMaxConnPerRoute(32)
            .setDefaultRequestConfig(
                    RequestConfig.copy(RequestConfig.DEFAULT).setRedirectsEnabled(true).build())
            .setDefaultCredentialsProvider(credentialsProvider)
            .addInterceptorFirst(new PreemptiveAuthInterceptor());
    return builder.build();
}

From source file:ch.entwine.weblounge.common.impl.util.TestUtils.java

/**
 * Issues the the given request./*from w w w  .  j  av  a 2s. co m*/
 * 
 * @param httpClient
 *          the http client
 * @param request
 *          the request
 * @param params
 *          the request parameters
 * @throws Exception
 *           if the request fails
 */
public static HttpResponse request(HttpClient httpClient, HttpUriRequest request, String[][] params)
        throws Exception {
    if (params != null) {
        if (request instanceof HttpGet) {
            List<NameValuePair> qparams = new ArrayList<NameValuePair>();
            if (params.length > 0) {
                for (String[] param : params) {
                    if (param.length < 2)
                        continue;
                    qparams.add(new BasicNameValuePair(param[0], param[1]));
                }
            }
            URI requestURI = request.getURI();
            URI uri = URIUtils.createURI(requestURI.getScheme(), requestURI.getHost(), requestURI.getPort(),
                    requestURI.getPath(), URLEncodedUtils.format(qparams, "utf-8"), null);
            HeaderIterator headerIterator = request.headerIterator();
            request = new HttpGet(uri);
            while (headerIterator.hasNext()) {
                request.addHeader(headerIterator.nextHeader());
            }
        } else if (request instanceof HttpPost) {
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            for (String[] param : params)
                formparams.add(new BasicNameValuePair(param[0], param[1]));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "utf-8");
            ((HttpPost) request).setEntity(entity);
        } else if (request instanceof HttpPut) {
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            for (String[] param : params)
                formparams.add(new BasicNameValuePair(param[0], param[1]));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "utf-8");
            ((HttpPut) request).setEntity(entity);
        }
    } else {
        if (request instanceof HttpPost || request instanceof HttpPut) {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(new ArrayList<NameValuePair>(), "utf-8");
            ((HttpEntityEnclosingRequestBase) request).setEntity(entity);
        }
    }
    return httpClient.execute(request);
}

From source file:nl.knaw.dans.easy.sword2examples.Common.java

public static CloseableHttpClient createHttpClient(URI uri, String uid, String pw) {
    BasicCredentialsProvider credsProv = new BasicCredentialsProvider();
    credsProv.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
            new UsernamePasswordCredentials(uid, pw));
    return HttpClients.custom().setDefaultCredentialsProvider(credsProv).build();
}

From source file:eu.stratosphere.nephele.net.NetUtils.java

/**
 * Util method to build socket addr from either:
 * <host>/*  w w  w .ja  v a2  s  . c o  m*/
 * <host>:<post>
 * <fs>://<host>:<port>/<path>
 */
public static InetSocketAddress createSocketAddr(String target, int defaultPort) {
    int colonIndex = target.indexOf(':');
    if (colonIndex < 0 && defaultPort == -1) {
        throw new RuntimeException("Not a host:port pair: " + target);
    }
    String hostname = "";
    int port = -1;
    if (!target.contains("/")) {
        if (colonIndex == -1) {
            hostname = target;
        } else {
            // must be the old style <host>:<port>
            hostname = target.substring(0, colonIndex);
            port = Integer.parseInt(target.substring(colonIndex + 1));
        }
    } else {
        // a new uri
        try {
            URI addr = new URI(target);
            hostname = addr.getHost();
            port = addr.getPort();
        } catch (URISyntaxException use) {
            LOG.fatal(use);
        }
    }

    if (port == -1) {
        port = defaultPort;
    }

    if (getStaticResolution(hostname) != null) {
        hostname = getStaticResolution(hostname);
    }
    return new InetSocketAddress(hostname, port);
}

From source file:com.vmware.identity.openidconnect.protocol.URIUtils.java

public static boolean areEqual(URI lhs, URI rhs) {
    Validate.notNull(lhs, "lhs");
    Validate.notNull(rhs, "rhs");

    URI lhsCopy;/*from  w ww  .j  av  a  2  s  .c  om*/
    URI rhsCopy;
    try {
        lhsCopy = new URI(lhs.getScheme(), lhs.getUserInfo(), lhs.getHost(), URIUtils.getPort(lhs),
                lhs.getPath(), lhs.getQuery(), lhs.getFragment());
        rhsCopy = new URI(rhs.getScheme(), rhs.getUserInfo(), rhs.getHost(), URIUtils.getPort(rhs),
                rhs.getPath(), rhs.getQuery(), rhs.getFragment());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("failed to transform uri for equality check", e);
    }

    return lhsCopy.equals(rhsCopy);
}

From source file:com.cloud.utils.UriUtils.java

public static boolean hostAndPathPresent(URI uri) {
    return !(uri.getHost() == null || uri.getHost().trim().isEmpty() || uri.getPath() == null
            || uri.getPath().trim().isEmpty());
}

From source file:info.ajaxplorer.client.http.AjxpHttpClient.java

public static List<Cookie> getCookies(URI uri) {
    // Duplicate and prune
    List<Cookie> originalCookies = cookieStore.getCookies();
    List<Cookie> cookies = new ArrayList<Cookie>(originalCookies);
    for (int i = 0; i < originalCookies.size(); i++) {
        if (!originalCookies.get(i).getDomain().equals(uri.getHost())) {
            cookies.remove(originalCookies.get(i));
        }/*from w w w .j  a  v a 2 s . c om*/
    }
    return cookies;
}

From source file:com.google.cloud.hadoop.util.HttpTransportFactory.java

/**
 * Create an {@link HttpTransport} based on an type class and an optional HTTP proxy.
 *
 * @param type The type of HttpTransport to use.
 * @param proxyAddress The HTTP proxy to use with the transport. Of the form hostname:port. If
 * empty no proxy will be used.//ww  w .j  av  a  2 s .  co m
 * @return The resulting HttpTransport.
 * @throws IllegalArgumentException If the proxy address is invalid.
 * @throws IOException If there is an issue connecting to Google's Certification server.
 */
public static HttpTransport createHttpTransport(HttpTransportType type, @Nullable String proxyAddress)
        throws IOException {
    try {
        URI proxyUri = parseProxyAddress(proxyAddress);
        switch (type) {
        case APACHE:
            HttpHost proxyHost = null;
            if (proxyUri != null) {
                proxyHost = new HttpHost(proxyUri.getHost(), proxyUri.getPort());
            }
            return createApacheHttpTransport(proxyHost);
        case JAVA_NET:
            Proxy proxy = null;
            if (proxyUri != null) {
                proxy = new Proxy(Proxy.Type.HTTP,
                        new InetSocketAddress(proxyUri.getHost(), proxyUri.getPort()));
            }
            return createNetHttpTransport(proxy);
        default:
            throw new IllegalArgumentException(String.format("Invalid HttpTransport type '%s'", type.name()));
        }
    } catch (GeneralSecurityException e) {
        throw new IOException(e);
    }
}

From source file:com.microsoft.gittf.core.util.URIUtil.java

/**
 * Ensures that git tf is connecting to the right hosted server scheme and
 * path.//  w w w .j a  v a  2 s.  co  m
 * 
 * @param uri
 * @return
 * @throws URISyntaxException
 */
private static URI updateIfNeededForHostedService(URI uri) throws URISyntaxException {
    Check.notNull(uri, "uri"); //$NON-NLS-1$

    String hostedServer = System.getProperty("tfs.hosted"); //$NON-NLS-1$
    if (hostedServer == null || hostedServer.length() == 0) {
        hostedServer = hostedServerName;
    }

    if (uri.getHost().toLowerCase().contains(hostedServer)
            || uri.getHost().toLowerCase().contains(hostedServerPreviewName)) {
        String uriPath = uri.getPath().replaceAll("[/]+$", ""); //$NON-NLS-1$ //$NON-NLS-2$
        if (uriPath == null || uriPath.length() == 0) {
            uriPath = hostedServerPath;
        }

        return new URI(hostedServerScheme, uri.getHost(), uriPath, null);
    }

    return uri;
}

From source file:org.switchyard.component.http.endpoint.StandaloneEndpointPublisher.java

/**
 * Method for get request information from a http exchange.
 *
 * @param request HttpExchange/* w ww . j av a  2s  .com*/
 * @param type ContentType
 * @return Request information from a http exchange
 * @throws IOException when the request information could not be read
 */
public static HttpRequestInfo getRequestInfo(HttpExchange request, ContentType type) throws IOException {
    HttpRequestInfo requestInfo = new HttpRequestInfo();

    if (request.getHttpContext().getAuthenticator() instanceof BasicAuthenticator) {
        requestInfo.setAuthType(HttpServletRequest.BASIC_AUTH);
    }
    URI u = request.getRequestURI();
    URI requestURI = null;
    try {
        requestURI = new URI(u.getScheme(), u.getUserInfo(), u.getHost(), u.getPort(), u.getPath(), null, null);
    } catch (URISyntaxException e) {
        // Strange that this could happen when copying from another URI.
        LOGGER.debug(e);
    }
    requestInfo.setCharacterEncoding(type.getCharset());
    requestInfo.setContentType(type.toString());
    requestInfo.setContextPath(request.getHttpContext().getPath());
    requestInfo.setLocalAddr(request.getLocalAddress().getAddress().getHostAddress());
    requestInfo.setLocalName(request.getLocalAddress().getAddress().getHostName());
    requestInfo.setMethod(request.getRequestMethod());
    requestInfo.setProtocol(request.getProtocol());
    requestInfo.setQueryString(u.getQuery());
    requestInfo.setRemoteAddr(request.getRemoteAddress().getAddress().getHostAddress());
    requestInfo.setRemoteHost(request.getRemoteAddress().getAddress().getHostName());
    if (request.getHttpContext().getAuthenticator() instanceof BasicAuthenticator) {
        requestInfo.setRemoteUser(request.getPrincipal().getUsername());
    }
    requestInfo.setContentLength(request.getRequestBody().available());
    // requestInfo.setRequestSessionId(request.getRequestedSessionId());
    if (requestURI != null) {
        requestInfo.setRequestURI(requestURI.toString());
    }
    requestInfo.setScheme(u.getScheme());
    requestInfo.setServerName(u.getHost());
    requestInfo.setRequestPath(u.getPath());

    // Http Query params...
    if (requestInfo.getQueryString() != null) {
        Charset charset = null;
        if (type.getCharset() != null) {
            try {
                charset = Charset.forName(type.getCharset());
            } catch (Exception exception) {
                LOGGER.debug(exception);
            }
        }
        for (NameValuePair nameValuePair : URLEncodedUtils.parse(requestInfo.getQueryString(), charset)) {
            requestInfo.addQueryParam(nameValuePair.getName(), nameValuePair.getValue());
        }
    }

    // Credentials...
    requestInfo.getCredentials().addAll(new HttpExchangeCredentialExtractor().extract(request));

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace(requestInfo);
    }

    return requestInfo;
}