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:org.apache.hive.jdbc.Utils.java

/**
 * Get a string representing a specific host:port
 * @param connParams/*from  www .ja v  a2  s.  c  o m*/
 * @return
 * @throws JdbcUriParseException
 * @throws ZooKeeperHiveClientException
 */
private static String resolveAuthority(JdbcConnectionParams connParams)
        throws JdbcUriParseException, ZooKeeperHiveClientException {
    String serviceDiscoveryMode = connParams.getSessionVars().get(JdbcConnectionParams.SERVICE_DISCOVERY_MODE);
    if ((serviceDiscoveryMode != null)
            && (JdbcConnectionParams.SERVICE_DISCOVERY_MODE_ZOOKEEPER.equalsIgnoreCase(serviceDiscoveryMode))) {
        // Resolve using ZooKeeper
        return resolveAuthorityUsingZooKeeper(connParams);
    } else {
        String authority = connParams.getAuthorityList()[0];
        URI jdbcURI = URI.create(URI_HIVE_PREFIX + "//" + authority);
        // Check to prevent unintentional use of embedded mode. A missing "/"
        // to separate the 'path' portion of URI can result in this.
        // The missing "/" common typo while using secure mode, eg of such url -
        // jdbc:hive2://localhost:10000;principal=hive/HiveServer2Host@YOUR-REALM.COM
        if ((jdbcURI.getAuthority() != null) && (jdbcURI.getHost() == null)) {
            throw new JdbcUriParseException(
                    "Bad URL format. Hostname not found " + " in authority part of the url: "
                            + jdbcURI.getAuthority() + ". Are you missing a '/' after the hostname ?");
        }
        // Return the 1st element of the array
        return jdbcURI.getAuthority();
    }
}

From source file:net.ripe.rpki.validator.util.UriToFileMapper.java

private String getHostPortAsString(URI uri) {
    String host = uri.getHost();
    int port = uri.getPort();
    return port == -1 ? host : (host + ":" + port);
}

From source file:TestFuseDFS.java

/**
 * Run a fuse-dfs process to mount the given DFS
 *///from   w  ww.  ja v a  2s  . co  m
private static Process establishMount(URI uri) throws IOException {
    Runtime r = Runtime.getRuntime();
    String cp = System.getProperty("java.class.path");

    String buildTestDir = System.getProperty("build.test");
    String fuseCmd = buildTestDir + "/../fuse_dfs";
    String libHdfs = buildTestDir + "/../../../c++/lib";

    String arch = System.getProperty("os.arch");
    String jvm = System.getProperty("java.home") + "/lib/" + arch + "/server";
    String lp = System.getProperty("LD_LIBRARY_PATH") + ":" + libHdfs + ":" + jvm;
    LOG.debug("LD_LIBRARY_PATH=" + lp);

    String nameNode = "dfs://" + uri.getHost() + ":" + String.valueOf(uri.getPort());

    // NB: We're mounting via an unprivileged user, therefore
    // user_allow_other needs to be set in /etc/fuse.conf, which also
    // needs to be world readable.
    String mountCmd[] = { fuseCmd, nameNode, mountPoint,
            // "-odebug",              // Don't daemonize
            "-obig_writes", // Allow >4kb writes
            "-oentry_timeout=0.1", // Don't cache dents long
            "-oattribute_timeout=0.1", // Don't cache attributes long
            "-ononempty", // Don't complain about junk in mount point
            "-f", // Don't background the process
            "-ordbuffer=32768", // Read buffer size in kb
            "rw" };

    String[] env = { "CLASSPATH=" + cp, "LD_LIBRARY_PATH=" + lp, "PATH=/usr/bin:/bin" };

    execWaitRet("fusermount -u " + mountPoint);
    execAssertSucceeds("rm -rf " + mountPoint);
    execAssertSucceeds("mkdir -p " + mountPoint);

    // Mount the mini cluster
    String cmdStr = "";
    for (String c : mountCmd) {
        cmdStr += (" " + c);
    }
    LOG.info("now mounting with:" + cmdStr);
    Process fuseProcess = r.exec(mountCmd, env);
    RedirectToStdoutThread stdoutThread = new RedirectToStdoutThread(fuseProcess.getInputStream());
    RedirectToStdoutThread stderrThread = new RedirectToStdoutThread(fuseProcess.getErrorStream());
    stdoutThread.start();
    stderrThread.start();
    // Wait for fusermount to start up, so that we know we're operating on the
    // FUSE FS when we run the tests.
    try {
        Thread.sleep(50000);
    } catch (InterruptedException e) {
    }
    return fuseProcess;
}

From source file:com.nestorledon.employeedirectory.http.HttpComponentsClientHttpRequestFactoryBasicAuth.java

protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
    HttpHost host = new HttpHost(uri.getHost(), uri.getPort());
    return createHttpContext(host);
}

From source file:org.springframework.cloud.dataflow.shell.command.support.HttpClientUtils.java

/**
 * Ensures that the passed-in {@link RestTemplate} is using the Apache HTTP Client. If the optional {@code username} AND
 * {@code password} are not empty, then a {@link BasicCredentialsProvider} will be added to the {@link CloseableHttpClient}.
 *
 * Furthermore, you can set the underlying {@link SSLContext} of the {@link HttpClient} allowing you to accept self-signed
 * certificates./*from www.  j av a2 s.c om*/
 *
 * @param restTemplate Must not be null
 * @param username Can be null
 * @param password Can be null
 * @param skipSslValidation Use with caution! If true certificate warnings will be ignored.
 */
public static void prepareRestTemplate(RestTemplate restTemplate, URI host, String username, String password,
        boolean skipSslValidation) {

    Assert.notNull(restTemplate, "The provided RestTemplate must not be null.");

    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
        final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }

    if (skipSslValidation) {
        httpClientBuilder.setSSLContext(HttpClientUtils.buildCertificateIgnoringSslContext());
        httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }

    final CloseableHttpClient httpClient = httpClientBuilder.build();
    final HttpHost targetHost = new HttpHost(host.getHost(), host.getPort(), host.getScheme());

    final HttpComponentsClientHttpRequestFactory requestFactory = new PreemptiveBasicAuthHttpComponentsClientHttpRequestFactory(
            httpClient, targetHost);
    restTemplate.setRequestFactory(requestFactory);
}

From source file:com.ctriposs.r2.message.rest.QueryTunnelUtil.java

/**
 * @param request   a RestRequest object to be encoded as a tunneled POST
 * @param threshold the size of the query params above which the request will be encoded
 *
 * @return an encoded RestRequest//from  w ww .  ja  v a2s  . co m
 */
public static RestRequest encode(final RestRequest request, int threshold)
        throws URISyntaxException, MessagingException, IOException {
    URI uri = request.getURI();

    // Check to see if we should tunnel this request by testing the length of the query
    // if the query is NULL, we won't bother to encode.
    // 0 length is a special case that could occur with a url like http://www.foo.com?
    // which we don't want to encode, because we'll lose the "?" in the process
    // Otherwise only encode queries whose length is greater than or equal to the
    // threshold value.

    String query = uri.getRawQuery();

    if (query == null || query.length() == 0 || query.length() < threshold) {
        return request;
    }

    RestRequestBuilder requestBuilder = new RestRequestBuilder(request);

    // reconstruct URI without query
    uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), null,
            uri.getFragment());

    // If there's no existing body, just pass the request as x-www-form-urlencoded
    ByteString entity = request.getEntity();
    if (entity == null || entity.length() == 0) {
        requestBuilder.setHeader(HEADER_CONTENT_TYPE, FORM_URL_ENCODED);
        requestBuilder.setEntity(ByteString.copyString(query, Data.UTF_8_CHARSET));
    } else {
        // If we have a body, we must preserve it, so use multipart/mixed encoding

        MimeMultipart multi = createMultiPartEntity(entity, request.getHeader(HEADER_CONTENT_TYPE), query);
        requestBuilder.setHeader(HEADER_CONTENT_TYPE, multi.getContentType());
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        multi.writeTo(os);
        requestBuilder.setEntity(ByteString.copy(os.toByteArray()));
    }

    // Set the base uri, supply the original method in the override header, and change method to POST
    requestBuilder.setURI(uri);
    requestBuilder.setHeader(HEADER_METHOD_OVERRIDE, requestBuilder.getMethod());
    requestBuilder.setMethod(RestMethod.POST);

    return requestBuilder.build();
}

From source file:org.apache.hive.jdbc.Utils.java

/**
 * Read the next server coordinates (host:port combo) from ZooKeeper. Ignore the znodes already
 * explored. Also update the host, port, jdbcUriString fields of connParams.
 *
 * @param connParams//from w w w.jav a 2 s .c  o  m
 * @throws ZooKeeperHiveClientException
 */
static void updateConnParamsFromZooKeeper(JdbcConnectionParams connParams) throws ZooKeeperHiveClientException {
    // Add current host to the rejected list
    connParams.getRejectedHostZnodePaths().add(connParams.getCurrentHostZnodePath());
    // Get another HiveServer2 uri from ZooKeeper
    String serverUriString = ZooKeeperHiveClientHelper.getNextServerUriFromZooKeeper(connParams);
    // Parse serverUri to a java URI and extract host, port
    URI serverUri = null;
    try {
        // Note URL_PREFIX is not a valid scheme format, therefore leaving it null in the constructor
        // to construct a valid URI
        serverUri = new URI(null, serverUriString, null, null, null);
    } catch (URISyntaxException e) {
        throw new ZooKeeperHiveClientException(e);
    }
    String oldServerHost = connParams.getHost();
    int oldServerPort = connParams.getPort();
    String newServerHost = serverUri.getHost();
    int newServerPort = serverUri.getPort();
    connParams.setHost(newServerHost);
    connParams.setPort(newServerPort);
    connParams.setJdbcUriString(connParams.getJdbcUriString().replace(oldServerHost + ":" + oldServerPort,
            newServerHost + ":" + newServerPort));
}

From source file:cz.cvut.fel.webrtc.GroupCallApp.java

@Bean
public SipHandler sipHandler() throws URISyntaxException {
    URI uri = new URI(xivo_ws);
    return new SipHandler(uri.getHost());
}

From source file:com.orange.ngsi.ProtocolRegistry.java

private String getHost(String url) throws URISyntaxException {
    URI uri = new URI(url);
    return uri.getHost() + ":" + uri.getPort();
}

From source file:io.servicecomb.foundation.common.net.URIEndpointObject.java

public URIEndpointObject(String endpoint) {
    URI uri = URI.create(endpoint);
    setHostOrIp(uri.getHost());
    if (uri.getPort() < 0) {
        // do not use default port
        throw new IllegalArgumentException("port not specified.");
    }/*from w  w  w  .j a  va  2 s .  c  o  m*/
    setPort(uri.getPort());
    querys = splitQuery(uri);
    sslEnabled = Boolean.parseBoolean(getFirst(SSL_ENABLED_KEY));
}