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:ca.sqlpower.enterprise.ServerInfoProvider.java

private static void init(URL url, String username, String password, CookieStore cookieStore)
        throws IOException {

    if (version.containsKey(generateServerKey(url, username, password)))
        return;/*from  w  w  w .  j  a  v a2  s .  c om*/

    try {
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 2000);
        DefaultHttpClient httpClient = new DefaultHttpClient(params);
        httpClient.setCookieStore(cookieStore);
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        HttpUriRequest request = new HttpOptions(url.toURI());
        String responseBody = httpClient.execute(request, new BasicResponseHandler());

        // Decode the message
        String serverVersion;
        Boolean licensedServer;
        final String watermarkMessage;
        try {
            JSONObject jsonObject = new JSONObject(responseBody);
            serverVersion = jsonObject.getString(ServerProperties.SERVER_VERSION.toString());
            licensedServer = jsonObject.getBoolean(ServerProperties.SERVER_LICENSED.toString());
            watermarkMessage = jsonObject.getString(ServerProperties.SERVER_WATERMARK_MESSAGE.toString());
        } catch (JSONException e) {
            throw new IOException(e.getMessage());
        }

        // Save found values
        version.put(generateServerKey(url, username, password), new Version(serverVersion));
        licenses.put(generateServerKey(url, username, password), licensedServer);
        watermarkMessages.put(generateServerKey(url, username, password), watermarkMessage);

        // Notify the user if the server is not licensed.
        if (!licensedServer || (watermarkMessage != null && watermarkMessage.trim().length() > 0)) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    HyperlinkListener hyperlinkListener = new HyperlinkListener() {
                        @Override
                        public void hyperlinkUpdate(HyperlinkEvent e) {
                            try {
                                if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                                    if (e.getURL() != null) {
                                        BrowserUtil.launch(e.getURL().toString());
                                    }
                                }
                            } catch (IOException ex) {
                                throw new RuntimeException(ex);
                            }
                        }
                    };
                    HTMLUserPrompter htmlPrompter = new HTMLUserPrompter(UserPromptOptions.OK,
                            UserPromptResponse.OK, null, watermarkMessage, hyperlinkListener, "OK");
                    htmlPrompter.promptUser("");
                }
            });
        }

    } catch (URISyntaxException e) {
        throw new IOException(e.getLocalizedMessage());
    }
}

From source file:org.apache.metron.dataloads.taxii.TaxiiHandler.java

private static HttpClient buildClient(URL proxy, String username, String password) throws Exception {
    HttpClient client = new HttpClient(); // Start with a default TAXII HTTP client.

    // Create an Apache HttpClientBuilder to be customized by the command line arguments.
    HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties();

    // Proxy// www. j  ava 2 s  .  c o  m
    if (proxy != null) {
        HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort(), proxy.getProtocol());
        builder.setProxy(proxyHost);
    }

    // Basic authentication. User & Password
    if (username != null ^ password != null) {
        throw new Exception("'username' and 'password' arguments are required to appear together.");
    }

    // from:  http://stackoverflow.com/questions/19517538/ignoring-ssl-certificate-in-apache-httpclient-4-3
    SSLContextBuilder ssbldr = new SSLContextBuilder();
    ssbldr.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ssbldr.build(),
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", new PlainConnectionSocketFactory()).register("https", sslsf).build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
    cm.setMaxTotal(20);//max connection

    System.setProperty("jsse.enableSNIExtension", "false"); //""
    CloseableHttpClient httpClient = builder.setSSLSocketFactory(sslsf).setConnectionManager(cm).build();

    client.setHttpclient(httpClient);
    return client;
}

From source file:UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified port.
 * @param u the URL on which to base the returned URL
 * @param newPort the new port to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified port
 * @throws MalformedURLException if there is a problem creating the new URL
 *//*  w w w. j a v  a 2  s  .c  o  m*/
public static URL getUrlWithNewPort(final URL u, final int newPort) throws MalformedURLException {
    return createNewUrl(u.getProtocol(), u.getHost(), newPort, u.getPath(), u.getRef(), u.getQuery());
}

From source file:com.netscape.cmstools.cli.MainCLI.java

public static CAClient createCAClient(PKIClient client) throws Exception {

    ClientConfig config = client.getConfig();
    CAClient caClient = new CAClient(client);

    while (!caClient.exists()) {
        System.err.println("Error: CA subsystem not available");

        URL serverURI = config.getServerURL();
        String uri = serverURI.getProtocol() + "://" + serverURI.getHost() + ":" + serverURI.getPort();

        System.out.print("CA server URL [" + uri + "]: ");
        System.out.flush();//w ww.j av a 2  s.c om

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String line = reader.readLine().trim();
        if (!line.equals("")) {
            uri = line;
        }

        config = new ClientConfig(client.getConfig());
        config.setServerURL(uri);

        client = new PKIClient(config);
        caClient = new CAClient(client);
    }

    return caClient;
}

From source file:UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified reference.
 * @param u the URL on which to base the returned URL
 * @param newRef the new reference to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified reference
 * @throws MalformedURLException if there is a problem creating the new URL
 *//*from  w w w . j av  a  2  s  .  c  o m*/
public static URL getUrlWithNewRef(final URL u, final String newRef) throws MalformedURLException {
    return createNewUrl(u.getProtocol(), u.getHost(), u.getPort(), u.getPath(), newRef, u.getQuery());
}

From source file:UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified protocol.
 * @param u the URL on which to base the returned URL
 * @param newProtocol the new protocol to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified protocol
 * @throws MalformedURLException if there is a problem creating the new URL
 *//*from  w  w w  .  j  a  va  2 s  .  c om*/
public static URL getUrlWithNewProtocol(final URL u, final String newProtocol) throws MalformedURLException {
    return createNewUrl(newProtocol, u.getHost(), u.getPort(), u.getPath(), u.getRef(), u.getQuery());
}

From source file:UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified path.
 * @param u the URL on which to base the returned URL
 * @param newPath the new path to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified path
 * @throws MalformedURLException if there is a problem creating the new URL
 *///w  w  w  .ja v a 2s.  c  o  m
public static URL getUrlWithNewPath(final URL u, final String newPath) throws MalformedURLException {
    return createNewUrl(u.getProtocol(), u.getHost(), u.getPort(), newPath, u.getRef(), u.getQuery());
}

From source file:UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified query string.
 * @param u the URL on which to base the returned URL
 * @param newQuery the new query string to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified query string
 * @throws MalformedURLException if there is a problem creating the new URL
 *///from  w ww. ja v  a  2s  . c om
public static URL getUrlWithNewQuery(final URL u, final String newQuery) throws MalformedURLException {
    return createNewUrl(u.getProtocol(), u.getHost(), u.getPort(), u.getPath(), u.getRef(), newQuery);
}

From source file:au.gov.aims.atlasmapperserver.servlet.Proxy.java

private static boolean addProxyAllowedHost(Set<String> allowedHosts, String urlStr) {
    URL url = null;
    try {//from w ww.j  av  a2  s. co m
        url = Utils.toURL(urlStr);
    } catch (Exception ex) {
        return false;
    }
    // It should not be null if it succeed, but better not taking chance.
    if (url == null) {
        return false;
    }

    String host = url.getHost();
    if (Utils.isNotBlank(host)) {
        allowedHosts.add(host.trim());
    }

    return true;
}

From source file:com.ms.commons.test.classloader.util.AntxconfigUtil.java

@SuppressWarnings("unchecked")
private static void autoconf(File tmp, String autoconfigPath, String autoconfigFile, PrintStream out)
        throws Exception {
    Enumeration<URL> urls = AntxconfigUtil.class.getClassLoader().getResources(autoconfigFile);
    for (; urls.hasMoreElements();) {
        URL url = urls.nextElement();
        // copy xml
        File autoconfFile = new File(tmp, autoconfigFile);
        writeUrlToFile(url, autoconfFile);
        // copy vm
        SAXBuilder b = new SAXBuilder();
        Document document = b.build(autoconfFile);
        List<Element> elements = XPath.selectNodes(document, GEN_PATH);
        for (Element element : elements) {
            String path = url.getPath();
            String vm = element.getAttributeValue("template");
            String vmPath = StringUtils.substringBeforeLast(path, "/") + "/" + vm;
            URL vmUrl = new URL(url.getProtocol(), url.getHost(), vmPath);
            File vmFile = new File(tmp, autoconfigPath + "/" + vm);
            writeUrlToFile(vmUrl, vmFile);
        }//  w  w w  .j a  va2  s.  co  m
        // call antxconfig
        String args = "";
        if (new File(DEFAULT_ANTX_FILE).isFile()) {
            args = " -u " + DEFAULT_ANTX_FILE;
        }

        Process p = Runtime.getRuntime().exec(ANTXCONFIG_CMD + args, null, tmp);
        BufferedInputStream in = new BufferedInputStream(p.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String s;
        while ((s = br.readLine()) != null) {
            out.println(new String(s.getBytes(), ENDODING));
        }
        FileUtils.deleteDirectory(new File(tmp, autoconfigPath));
    }
}