Example usage for java.net URL getHost

List of usage examples for java.net URL getHost

Introduction

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

Prototype

public String getHost() 

Source Link

Document

Gets the host name of this URL , if applicable.

Usage

From source file:URLUtil.java

/**
 * Method that tries to get a stream (ideally, optimal one) to write to the
 * resource specified by given URL. Currently it just means creating a simple
 * file output stream if the URL points to a (local) file, and otherwise
 * relying on URL classes input stream creation method.
 *//*from  w w  w  . j  a  va2s .c om*/
public static OutputStream outputStreamFromURL(URL url) throws IOException {
    if ("file".equals(url.getProtocol())) {
        /*
         * As per [WSTX-82], can not do this if the path refers to a network drive
         * on windows.
         */
        String host = url.getHost();
        if (host == null || host.length() == 0) {
            return new FileOutputStream(url.getPath());
        }
    }
    return url.openConnection().getOutputStream();
}

From source file:fr.cnes.sitools.metacatalogue.resources.proxyservices.RedirectorHttps.java

/**
 * getDomainName//from w  ww  .  ja  v a  2s .c om
 * 
 * @param url
 * @return
 * @throws MalformedURLException
 */
public static String getDomainName(String url) throws MalformedURLException {
    if (!url.startsWith("http") && !url.startsWith("https")) {
        url = "http://" + url;
    }
    URL netUrl = new URL(url);
    String host = netUrl.getHost();
    if (host.startsWith("www")) {
        host = host.substring("www".length() + 1);
    }
    return host;
}

From source file:com.bfd.harpc.common.configure.PathUtils.java

/**
 * Normalize the path by suppressing sequences like "path/.." and inner
 * simple dots./*ww w .  j a  v a2 s  .c  o  m*/
 * <p>
 * The result is convenient for path comparison. For other uses, notice that
 * Windows separators ("\") are replaced by simple slashes.
 * 
 * @param originalUrl
 *            the url with original path
 * @return the url with normalized path
 * @throws MalformedURLException
 * @throws URISyntaxException
 */
public static URL cleanPath(URL originalUrl) throws MalformedURLException, URISyntaxException {
    String path = originalUrl.toString();
    if (StringUtils.isEmpty(path)) {
        return null;
    }
    URL curl = new URL(cleanPath(path));
    // curl.toURI().getPath()?
    return new URL(curl.getProtocol(), curl.getHost(), curl.toURI().getPath());
}

From source file:edu.uci.ics.crawler4j.url.URLCanonicalizer.java

public static String getCanonicalURL(String href, String context) {

    try {/* w w w  .ja  v a 2 s .co  m*/
        URL canonicalURL = new URL(UrlResolver.resolveUrl(context == null ? "" : context, href));

        String host = canonicalURL.getHost().toLowerCase();
        if (StringUtils.isBlank(host)) {
            // This is an invalid Url.
            return null;
        }

        String path = canonicalURL.getPath();

        /*
         * Normalize: no empty segments (i.e., "//"), no segments equal to
         * ".", and no segments equal to ".." that are preceded by a segment
         * not equal to "..".
         */
        path = new URI(path).normalize().toString();

        /*
         * Convert '//' -> '/'
         */
        int idx = path.indexOf("//");
        while (idx >= 0) {
            path = path.replace("//", "/");
            idx = path.indexOf("//");
        }

        /*
         * Drop starting '/../'
         */
        while (path.startsWith("/../")) {
            path = path.substring(3);
        }

        /*
         * Trim
         */
        path = path.trim();

        final SortedMap<String, String> params = createParameterMap(canonicalURL.getQuery());
        final String queryString;

        if (params != null && params.size() > 0) {
            String canonicalParams = canonicalize(params);
            queryString = (canonicalParams.isEmpty() ? "" : "?" + canonicalParams);
        } else {
            queryString = "";
        }

        /*
         * Add starting slash if needed
         */
        if (path.length() == 0) {
            path = "/" + path;
        }

        /*
         * Drop default port: example.com:80 -> example.com
         */
        int port = canonicalURL.getPort();
        if (port == canonicalURL.getDefaultPort()) {
            port = -1;
        }

        String protocol = canonicalURL.getProtocol().toLowerCase();
        String pathAndQueryString = normalizePath(path) + queryString;

        URL result = new URL(protocol, host, port, pathAndQueryString);
        return result.toExternalForm();

    } catch (MalformedURLException ex) {
        return null;
    } catch (URISyntaxException ex) {
        return null;
    }
}

From source file:org.duracloud.duradmin.spaces.controller.ContentItemController.java

public static String getBaseURL(HttpServletRequest request) throws MalformedURLException {
    URL url = new URL(request.getRequestURL().toString());
    int port = url.getPort();
    String baseURL = url.getProtocol() + "://" + url.getHost() + ":"
            + (port > 0 && port != 80 ? url.getPort() : "") + request.getContextPath();
    return baseURL;
}

From source file:de.arago.rike.commons.util.ViewHelper.java

public static String formatURL(String path) {
    if (path == null || path.length() == 0) {
        return "";
    }// w ww .ja v  a2 s  .  c  o  m

    try {
        URL url = new URL(path);
        return "<a target='_blank' title='" + escape(path) + "' href='" + escape(path) + "'>"
                + escape(url.getHost()) + "</a>";
    } catch (MalformedURLException ex) {
        return "<a target='_blank' href='" + escape(path) + "'>" + escape(path) + "</a>";
    }
}

From source file:com.doculibre.constellio.utils.ConnectorManagerRequestUtils.java

public static Element sendPost(ConnectorManager connectorManager, String servletPath, Document document) {
    try {//from   w  ww .  j  a va  2  s  .  c  om
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
        HttpProtocolParams.setUseExpectContinue(params, true);

        BasicHttpProcessor httpproc = new BasicHttpProcessor();
        // Required protocol interceptors
        httpproc.addInterceptor(new RequestContent());
        httpproc.addInterceptor(new RequestTargetHost());
        // Recommended protocol interceptors
        httpproc.addInterceptor(new RequestConnControl());
        httpproc.addInterceptor(new RequestUserAgent());
        httpproc.addInterceptor(new RequestExpectContinue());

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

        HttpContext context = new BasicHttpContext(null);

        URL connectorManagerURL = new URL(connectorManager.getUrl());
        HttpHost host = new HttpHost(connectorManagerURL.getHost(), connectorManagerURL.getPort());

        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
        ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

        try {
            HttpEntity requestBody;
            if (document != null) {
                //                 OutputFormat format = OutputFormat.createPrettyPrint();
                OutputFormat format = OutputFormat.createCompactFormat();
                StringWriter stringWriter = new StringWriter();
                XMLWriter xmlWriter = new XMLWriter(stringWriter, format);
                xmlWriter.write(document);
                String xmlAsString = stringWriter.toString();
                requestBody = new StringEntity(xmlAsString, "UTF-8");
            } else {
                requestBody = null;
            }
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }

            String target = connectorManager.getUrl() + servletPath;

            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", target);
            request.setEntity(requestBody);
            LOGGER.info(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            LOGGER.info("<< Response: " + response.getStatusLine());
            String entityText = EntityUtils.toString(response.getEntity());
            LOGGER.info(entityText);
            LOGGER.info("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                LOGGER.info("Connection kept alive...");
            }

            Document xml = DocumentHelper.parseText(entityText);
            return xml.getRootElement();
        } finally {
            conn.close();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.elasticsearch.test.rest.client.RestTestClient.java

private static RestClient createRestClient(URL[] urls, Settings settings) throws IOException {
    String protocol = settings.get(PROTOCOL, "http");
    HttpHost[] hosts = new HttpHost[urls.length];
    for (int i = 0; i < hosts.length; i++) {
        URL url = urls[i];
        hosts[i] = new HttpHost(url.getHost(), url.getPort(), protocol);
    }/*from w w w. j a v  a2  s. c  o m*/
    RestClient.Builder builder = RestClient.builder(hosts).setMaxRetryTimeoutMillis(30000)
            .setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder.setSocketTimeout(30000));

    String keystorePath = settings.get(TRUSTSTORE_PATH);
    if (keystorePath != null) {
        final String keystorePass = settings.get(TRUSTSTORE_PASSWORD);
        if (keystorePass == null) {
            throw new IllegalStateException(TRUSTSTORE_PATH + " is provided but not " + TRUSTSTORE_PASSWORD);
        }
        Path path = PathUtils.get(keystorePath);
        if (!Files.exists(path)) {
            throw new IllegalStateException(TRUSTSTORE_PATH + " is set but points to a non-existing file");
        }
        try {
            KeyStore keyStore = KeyStore.getInstance("jks");
            try (InputStream is = Files.newInputStream(path)) {
                keyStore.load(is, keystorePass.toCharArray());
            }
            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, null).build();
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext);
            builder.setHttpClientConfigCallback(
                    new SSLSocketFactoryHttpConfigCallback(sslConnectionSocketFactory));
        } catch (KeyStoreException | NoSuchAlgorithmException | KeyManagementException
                | CertificateException e) {
            throw new RuntimeException(e);
        }
    }

    try (ThreadContext threadContext = new ThreadContext(settings)) {
        Header[] defaultHeaders = new Header[threadContext.getHeaders().size()];
        int i = 0;
        for (Map.Entry<String, String> entry : threadContext.getHeaders().entrySet()) {
            defaultHeaders[i++] = new BasicHeader(entry.getKey(), entry.getValue());
        }
        builder.setDefaultHeaders(defaultHeaders);
    }
    return builder.build();
}

From source file:mobi.jenkinsci.ci.client.JenkinsFormAuthHttpClient.java

public static final String getDomainFromUrl(final URL url) {
    return String.format("%s://%s%s", url.getProtocol(), url.getHost(),
            url.getPort() > 0 ? ":" + url.getPort() : "");
}

From source file:org.fcrepo.localservices.saxon.SaxonServlet.java

/**
 * Return a URL string in which the port is always specified.
 *//*from   ww w .jav  a2  s.com*/
private static String normalizeURL(String urlString) throws MalformedURLException {
    URL url = new URL(urlString);
    if (url.getPort() == -1) {
        return url.getProtocol() + "://" + url.getHost() + ":" + url.getDefaultPort() + url.getFile()
                + (url.getRef() != null ? "#" + url.getRef() : "");
    } else {
        return urlString;
    }
}