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.fao.geonet.MockRequestFactoryGeonet.java

@Override
public ClientHttpResponse execute(HttpUriRequest request, Function<HttpClientBuilder, Void> configurator)
        throws IOException {
    final URI uri = request.getURI();
    final Request key = new Request(uri.getHost(), uri.getPort(), uri.getScheme(), null);
    final XmlRequest xmlRequest = (XmlRequest) getRequest(key);
    return new MockClientHttpResponse(Xml.getString(xmlRequest.execute()).getBytes(Constants.CHARSET),
            HttpStatus.OK);/*ww  w . j  ava2s  . c  o m*/
}

From source file:com.beyondj.gateway.handlers.tcp.TcpGatewayHandler.java

/**
 * Creates a new client for the given URL and handler
 *//*from w  w  w .j av a 2  s.  co  m*/
protected NetClient createClient(NetSocket socket, URI url, Handler<AsyncResult<NetSocket>> handler)
        throws MalformedURLException {
    NetClient client = vertx.createNetClient();
    int port = url.getPort();
    String host = url.getHost();
    LOG.info("Connecting " + socket.remoteAddress() + " to host " + host + " port " + port + " protocol "
            + protocol);
    return client.connect(port, host, handler);
}

From source file:com.github.sardine.AuthenticationTest.java

@Test
public void testBasicPreemptiveAuthHeader() throws Exception {
    final HttpClientBuilder client = HttpClientBuilder.create();
    client.addInterceptorFirst(new HttpRequestInterceptor() {
        public void process(final HttpRequest r, final HttpContext context) throws HttpException, IOException {
            assertNotNull(r.getHeaders(HttpHeaders.AUTHORIZATION));
            assertEquals(1, r.getHeaders(HttpHeaders.AUTHORIZATION).length);
        }/* www .j  av  a 2s  .com*/
    });
    Sardine sardine = new SardineImpl(client);
    sardine.setCredentials("anonymous", null);
    // mod_dav supports Range headers for PUT
    final URI url = URI.create("http://sardine.googlecode.com/svn/trunk/README.html");
    sardine.enablePreemptiveAuthentication(url.getHost());
    assertTrue(sardine.exists(url.toString()));
}

From source file:com.microsoft.azure.hdinsight.spark.run.SparkBatchJobDebuggerRunner.java

/**
 * Get SSH Host from the HDInsight connection URL
 *
 * @param connectionUrl the HDInsight connection URL, such as: https://spkdbg.azurehdinsight.net/batch
 * @return SSH host/*from w w w  .  java2 s  .c o m*/
 * @throws URISyntaxException connection URL is invalid
 */
protected String getSshHost(String connectionUrl) throws URISyntaxException {
    URI connectUri = new URI(connectionUrl);
    String segs[] = connectUri.getHost().split("\\.");
    segs[0] = segs[0].concat("-ssh");
    return StringUtils.join(segs, ".");
}

From source file:org.alfresco.mongo.MongoClientFactory.java

/**
 * Validates MongoClientURI /*from   ww  w. j  a  v a  2 s  .co m*/
 * @param mongoClientURI {MongoClientURI} must not be null and contain valid host and (optional) port. 
 */
private void validateMongoClientURI(MongoClientURI mongoClientURI) {
    // 1. Argument not optional
    if (null == mongoClientURI) {
        throw new IllegalArgumentException("'mongoClientURI' argument may not be null.");
    }

    // 2.  Validate host
    for (String host : mongoClientURI.getHosts()) {
        // ensure not null or empty or just whitespace chars
        if (null != host && host.trim().length() > 0) {
            try {
                // create a URI from the host name - may throw URISyntaxException
                URI uri = new URI("my://" + host);

                // get host without port from URI
                host = uri.getHost();

                if (null == host || host.trim().length() == 0) {
                    throw new IllegalArgumentException(
                            "'mongoClientURI' argument must contain a valid host: " + mongoClientURI);
                }
            } catch (URISyntaxException ex) {
                // validation failed due to malformed host
                throw new IllegalArgumentException(
                        "'mongoClientURI' argument must contain a valid host: " + mongoClientURI);
            }
        } else {
            throw new IllegalArgumentException(
                    "'mongoClientURI' argument: host is mandatory: " + mongoClientURI);
        }
    }
}

From source file:io.seldon.external.ExternalPluginServer.java

@Override
public JsonNode execute(JsonNode payload, OptionsHolder options) {
    long timeNow = System.currentTimeMillis();
    URI uri = URI.create(options.getStringOption(URL_PROPERTY_NAME));
    try {//from w  w w  .  ja  va 2s.  c o  m
        URIBuilder builder = new URIBuilder().setScheme("http").setHost(uri.getHost()).setPort(uri.getPort())
                .setPath(uri.getPath()).setParameter("json", payload.toString());

        uri = builder.build();
    } catch (URISyntaxException e) {
        throw new APIException(APIException.GENERIC_ERROR);
    }
    HttpContext context = HttpClientContext.create();
    HttpGet httpGet = new HttpGet(uri);
    try {
        if (logger.isDebugEnabled())
            logger.debug("Requesting " + httpGet.getURI().toString());
        CloseableHttpResponse resp = httpClient.execute(httpGet, context);
        if (resp.getStatusLine().getStatusCode() == 200) {

            JsonFactory factory = mapper.getJsonFactory();
            JsonParser parser = factory.createJsonParser(resp.getEntity().getContent());
            JsonNode actualObj = mapper.readTree(parser);
            if (logger.isDebugEnabled())
                logger.debug(
                        "External prediction server took " + (System.currentTimeMillis() - timeNow) + "ms");
            return actualObj;
        } else {
            logger.error(
                    "Couldn't retrieve prediction from external prediction server -- bad http return code: "
                            + resp.getStatusLine().getStatusCode());
            throw new APIException(APIException.GENERIC_ERROR);
        }
    } catch (IOException e) {
        logger.error("Couldn't retrieve prediction from external prediction server - ", e);
        throw new APIException(APIException.GENERIC_ERROR);
    }

}

From source file:net.javacrumbs.springws.test.lookup.PayloadRootBasedResourceLookup.java

protected String getResourceName(URI uri, String payloadName, String[] expressions, int discriminatorsCount,
        Document document) {//from   w  ww  .ja  v a2 s.c  om
    String uriHost = prependUri ? (uri.getHost() + payloadDelimiter) : "";
    return pathPrefix + uriHost + payloadName + payloadDelimiter
            + getDiscriminatorExpression(uri, expressions, discriminatorsCount, document) + pathSuffix;
}

From source file:org.soyatec.windowsazure.authenticate.SharedKeyCredentialsWrapper.java

/**
 * Replace the uri container name.// w ww  .ja  v  a2 s.  com
 * 
 * @param uri
 * @param accountName
 * @return The uri after be replaced the account name with the input
 *         accountName.
 */
private URI replaceAccountName(URI uri, String accountName) {
    try {
        String host = uri.getHost();
        String[] temp = host.split("\\.");
        temp[0] = accountName;
        return URIUtils.createURI(uri.getScheme(), join(".", temp), uri.getPort(),
                HttpUtilities.getNormalizePath(uri),
                (uri.getQuery() == null ? Utilities.emptyString() : uri.getQuery()), uri.getFragment());
    } catch (URISyntaxException e) {
        Logger.error("", e);
    }
    return uri;
}

From source file:cn.ctyun.amazonaws.http.HttpRequestFactory.java

/** Configures the headers in the specified Apache HTTP request. */
private void configureHeaders(HttpRequestBase httpRequest, Request<?> request, ExecutionContext context,
        ClientConfiguration clientConfiguration) {
    /*//from  w ww. ja v a 2  s  . c  o  m
     * Apache HttpClient omits the port number in the Host header (even if
     * we explicitly specify it) if it's the default port for the protocol
     * in use. To ensure that we use the same Host header in the request and
     * in the calculated string to sign (even if Apache HttpClient changed
     * and started honoring our explicit host with endpoint), we follow this
     * same behavior here and in the QueryString signer.
     */
    URI endpoint = request.getEndpoint();
    String hostHeader = endpoint.getHost();
    if (HttpUtils.isUsingNonDefaultPort(endpoint)) {
        hostHeader += ":" + endpoint.getPort();
    }
    httpRequest.addHeader("Host", hostHeader);

    // Copy over any other headers already in our request
    for (Entry<String, String> entry : request.getHeaders().entrySet()) {
        /*
         * HttpClient4 fills in the Content-Length header and complains if
         * it's already present, so we skip it here. We also skip the Host
         * header to avoid sending it twice, which will interfere with some
         * signing schemes.
         */
        if (entry.getKey().equalsIgnoreCase("Content-Length") || entry.getKey().equalsIgnoreCase("Host"))
            continue;

        httpRequest.addHeader(entry.getKey(), entry.getValue());
    }

    /* Set content type and encoding */
    if (httpRequest.getHeaders("Content-Type") == null || httpRequest.getHeaders("Content-Type").length == 0) {
        httpRequest.addHeader("Content-Type",
                "application/x-www-form-urlencoded; " + "charset=" + DEFAULT_ENCODING.toLowerCase());
    }

    // Override the user agent string specified in the client params if the context requires it
    if (context != null && context.getContextUserAgent() != null) {
        httpRequest.addHeader("User-Agent",
                createUserAgentString(clientConfiguration, context.getContextUserAgent()));
    }
}