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:com.mindquarry.desktop.util.HttpUtilities.java

private static HttpClient createHttpClient(String login, String pwd, String address)
        throws MalformedURLException {
    URL url = new URL(address);

    HttpClient client = new HttpClient();
    client.getParams().setSoTimeout(SOCKET_TIMEOUT);
    client.getParams().setParameter("http.connection.timeout", CONNECTION_TIMEOUT);
    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM),
            new UsernamePasswordCredentials(login, pwd));

    // apply proxy settings if necessary
    if ((store != null) && (store.getBoolean(ProxySettingsPage.PREF_PROXY_ENABLED))) {
        URL proxyUrl = new URL(store.getString(ProxySettingsPage.PREF_PROXY_URL));
        String proxyLogin = store.getString(ProxySettingsPage.PREF_PROXY_LOGIN);
        String proxyPwd = store.getString(ProxySettingsPage.PREF_PROXY_PASSWORD);

        client.getHostConfiguration().setProxy(proxyUrl.getHost(), proxyUrl.getPort());
        client.getState().setProxyCredentials(new AuthScope(proxyUrl.getHost(), proxyUrl.getPort()),
                new UsernamePasswordCredentials(proxyLogin, proxyPwd));
    }//from  w w w  .  ja v a 2  s. c  o  m
    return client;
}

From source file:Models.Geographic.Repository.RepositoryGoogle.java

/**
 * //from  ww  w.j  a  v  a 2s  .  co  m
 * @param latitude
 * @param longitude
 * @return 
 */
public static HashMap reverse(double latitude, double longitude) {
    HashMap a = new HashMap();
    try {
        //URL url=new URL(Configuration.getParameter("geocoding_google_url_send_json") + "latlng=" + String.valueOf(latitude) + "," + String.valueOf(longitude));            
        URL url = new URL(Configuration.getParameter("geocoding_google_url_send_json") + "latlng="
                + String.valueOf(latitude) + "," + String.valueOf(longitude));
        URL file_url = new URL(
                url.getProtocol() + "://" + url.getHost() + signRequest(url.getPath(), url.getQuery()));
        //BufferedReader lector=new BufferedReader(new InputStreamReader(url.openStream()));
        BufferedReader lector = new BufferedReader(new InputStreamReader(file_url.openStream()));
        String textJson = "", tempJs;
        while ((tempJs = lector.readLine()) != null)
            textJson += tempJs;
        if (textJson == null)
            throw new Exception("Don't found item");
        JSONObject google = ((JSONObject) JSONValue.parse(textJson));
        a.put("status", google.get("status").toString());
        if (a.get("status").toString().equals("OK")) {
            JSONArray results = (JSONArray) google.get("results");
            JSONArray address_components = (JSONArray) ((JSONObject) results.get(2)).get("address_components");
            for (int i = 0; i < address_components.size(); i++) {
                JSONObject items = (JSONObject) address_components.get(i);
                //if(((JSONObject)types.get(0)).get("").toString().equals("country"))
                if (items.get("types").toString().contains("country")) {
                    a.put("country", items.get("long_name").toString());
                    a.put("iso", items.get("short_name").toString());
                    break;
                }
            }
        }
    } catch (Exception ex) {
        a = null;
        System.out.println("Error Google Geocoding: " + ex);
    }
    return a;
}

From source file:com.fujitsu.dc.test.utils.Http.java

static Socket createSocket(URL url) throws IOException, KeyStoreException, NoSuchAlgorithmException,
        CertificateException, KeyManagementException {
    String host = url.getHost();
    int port = url.getPort();
    String proto = url.getProtocol();
    if (port < 0) {
        if ("https".equals(proto)) {
            port = PORT_HTTPS;/*from   ww  w .ja v a  2 s. c  o  m*/
        }
        if ("http".equals(proto)) {
            port = PORT_HTTP;
        }
    }
    log.debug("sock: " + host + ":" + port);
    log.debug("proto: " + proto);
    // HTTPS?????????????SSLSocket???
    if ("https".equals(proto)) {
        KeyManager[] km = null;
        TrustManager[] tm = { new javax.net.ssl.X509TrustManager() {
            public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                    throws java.security.cert.CertificateException {
                log.debug("Insecure SSLSocket Impl for Testing: NOP at X509TrustManager#checkClientTrusted");
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                    throws java.security.cert.CertificateException {
                log.debug("Insecure SSLSocket Impl for Testing: NOP at X509TrustManager#checkServerTrusted");
            }

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(km, tm, new SecureRandom());
        SocketFactory sf = sslContext.getSocketFactory();
        return (SSLSocket) sf.createSocket(host, port);
    }
    // HTTPS????????
    return new Socket(host, port);
}

From source file:org.cerberus.engine.execution.impl.SeleniumServerService.java

private static void getIPOfNode(TestCaseExecution tCExecution) {
    try {//w ww  .j a v a 2s  . co  m
        Session session = tCExecution.getSession();
        HttpCommandExecutor ce = (HttpCommandExecutor) ((RemoteWebDriver) session.getDriver())
                .getCommandExecutor();
        SessionId sessionId = ((RemoteWebDriver) session.getDriver()).getSessionId();
        String hostName = ce.getAddressOfRemoteServer().getHost();
        int port = ce.getAddressOfRemoteServer().getPort();
        HttpHost host = new HttpHost(hostName, port);
        HttpClient client = HttpClientBuilder.create().build();
        URL sessionURL = new URL("http://" + session.getHost() + ":" + session.getPort()
                + "/grid/api/testsession?session=" + sessionId);
        BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST",
                sessionURL.toExternalForm());
        HttpResponse response = client.execute(host, r);
        if (!response.getStatusLine().toString().contains("403")) {
            InputStream contents = response.getEntity().getContent();
            StringWriter writer = new StringWriter();
            IOUtils.copy(contents, writer, "UTF8");
            JSONObject object = new JSONObject(writer.toString());
            URL myURL = new URL(object.getString("proxyId"));
            if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {
                tCExecution.setIp(myURL.getHost());
                tCExecution.setPort(String.valueOf(myURL.getPort()));
            }
        }

    } catch (IOException ex) {
        LOG.error(ex.toString());
    } catch (JSONException ex) {
        LOG.error(ex.toString());
    }
}

From source file:com.comcast.cmb.common.util.AuthUtil.java

private static String normalizeURL(URL url) {

    String normalizedUrl = url.getHost().toLowerCase();

    // account for apache http client omitting standard ports

    if (url.getPort() > 0 && url.getPort() != 80 && url.getPort() != 443) {
        normalizedUrl += ":" + url.getPort();
    }/*from  ww  w .  j a  va2 s  .  c om*/

    return normalizedUrl;
}

From source file:URLUtils.java

/**
 * Checks that the protocol://host:port part of two URLs are equal.
 * /*from  ww w. ja v  a2  s .c  om*/
 * @param u1,
 *          the first URL to check
 * @param u2,
 *          the second URL to check
 * @return a boolean, true if the protocol://host:port part of the URL are
 *         equals, false otherwise
 */
public static boolean equalsProtocolHostPort(URL u1, URL u2) {
    if ((u1 == null) || (u2 == null)) {
        return false;
    }
    // check that the protocol are the same (as it impacts the
    // default port check
    if (!u1.getProtocol().equalsIgnoreCase(u2.getProtocol())) {
        return false;
    }
    // check that both hostnames are equal
    if (!u1.getHost().equalsIgnoreCase(u2.getHost())) {
        return false;
    }
    int u1p = u1.getPort();
    int u2p = u2.getPort();
    // if port is ok, it's good!
    if (u1p == u2p) {
        return true;
    } else if ((u1p > 0) && (u2p > 0)) {
        return false;
    }
    // otherwise, the painful comparison of -1 and such
    if (url_defport != null) {
        if (u1p == -1) {
            try {
                int u1dp;
                u1dp = ((Integer) url_defport.invoke(u1, (Object[]) null)).intValue();
                return (u2p == u1dp);
            } catch (InvocationTargetException ex) {
            } catch (IllegalAccessException iex) {
            }
        } else {
            try {
                int u2dp;
                u2dp = ((Integer) url_defport.invoke(u2, (Object[]) null)).intValue();
                return (u1p == u2dp);
            } catch (InvocationTargetException ex) {
            } catch (IllegalAccessException iex) {
            }
        }
    }
    // no JDK 1.4 this is becoming painful...
    if (u1p == -1) {
        String s = u1.getProtocol();
        int u1dp = 0;
        if (s.equalsIgnoreCase("http")) {
            u1dp = 80;
        } else if (s.equalsIgnoreCase("https")) {
            u1dp = 443;
        } // FIXME do others?
        return (u2p == u1dp);
    } else {
        String s = u2.getProtocol();
        int u2dp = 0;
        if (s.equalsIgnoreCase("http")) {
            u2dp = 80;
        } else if (s.equalsIgnoreCase("https")) {
            u2dp = 443;
        } // FIXME do others?
        return (u1p == u2dp);
    }
}

From source file:eu.trentorise.smartcampus.network.RemoteConnector.java

private static String normalizeURL(String uriString) throws RemoteException {
    try {//from  ww  w .  ja v a2  s  .c  om
        URL url = new URL(uriString);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        uriString = uri.toURL().toString();
    } catch (Exception e) {
        throw new RemoteException(e.getMessage());
    }
    return uriString;
}

From source file:com.dtolabs.client.utils.BaseFormAuthenticator.java

/**
 * Check the http state cookies to see if we have the proper session id cookie
 *
 * @param reqUrl   URL being requested//from  w  w w .  j a v a 2 s .  co m
 * @param state    HTTP state object
 * @param basePath base path of requests
 *
 * @return true if a cookie matching the basePath, server host and port, and request protocol and appropriate
 *         session cookie name is found
 */
public static boolean hasSessionCookie(final URL reqUrl, final HttpState state, final String basePath) {

    final CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    final Cookie[] initcookies = cookiespec.match(reqUrl.getHost(),
            reqUrl.getPort() > 0 ? reqUrl.getPort() : 80, basePath.endsWith("/") ? basePath : basePath + "/",
            HTTP_SECURE_PROTOCOL.equalsIgnoreCase(reqUrl.getProtocol()), state.getCookies());
    boolean hasSession = false;
    if (initcookies.length == 0) {
        hasSession = false;
    } else {
        for (final Cookie cookie : initcookies) {
            if (JAVA_SESSION_COOKIE_NAME.equals(cookie.getName())
                    || JAVA_SESSION_COOKIE_PATTERN.matcher(cookie.getName()).matches()) {
                logger.debug("Saw session cookie: " + cookie.getName());
                hasSession = true;
                break;
            }
        }
    }
    return hasSession;
}

From source file:app.web.Application2ITCase.java

public static URL toLocationPath(String location) {
    try {/*ww  w  . j av  a2s. co  m*/
        URL fullUrl = new URL(location);
        // We just throw the query string if any
        return new URL(fullUrl.getProtocol(), fullUrl.getHost(), fullUrl.getPort(), fullUrl.getPath());
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}

From source file:brooklyn.entity.rebind.persister.jclouds.BlobStoreExpiryTest.java

public static HttpToolResponse requestTokenWithExplicitLifetime(URL url, String user, String key,
        Duration expiration) throws URISyntaxException {
    HttpClient client = HttpTool.httpClientBuilder().build();
    HttpToolResponse response = HttpTool.httpGet(client, url.toURI(),
            MutableMap.<String, String>of().add(AuthHeaders.AUTH_USER, user).add(AuthHeaders.AUTH_KEY, key)
                    .add("Host", url.getHost()).add("X-Auth-New-Token", "" + true)
                    .add("X-Auth-Token-Lifetime", "" + expiration.toSeconds()));
    //        curl -v https://ams01.objectstorage.softlayer.net/auth/v1.0/v1.0 -H "X-Auth-User: IBMOS12345-2:username" -H "X-Auth-Key: <API KEY>" -H "Host: ams01.objectstorage.softlayer.net" -H "X-Auth-New-Token: true" -H "X-Auth-Token-Lifetime: 15"
    log.info("Requested token with explicit lifetime: " + expiration + " at " + url + "\n" + response + "\n"
            + response.getHeaderLists());
    return response;
}