Example usage for java.net URL getPort

List of usage examples for java.net URL getPort

Introduction

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

Prototype

public int getPort() 

Source Link

Document

Gets the port number of this URL .

Usage

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
 *///from  w  w  w  .  j  a v a 2 s.  com
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: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/*from w ww  .jav a2 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 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  ww  w .j ava2s. co  m*/
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: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();//from  w w w . j  a  v 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:com.microfocus.application.automation.tools.srf.run.RunFromSrfBuilder.java

public static JSONObject getSrfConnectionData(AbstractBuild<?, ?> build, PrintStream logger) {
    try {//w ww.  jav  a2s.c o m
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        String path = build.getProject().getParent().getRootDir().toString();
        path = path.concat(
                "/com.microfocus.application.automation.tools.srf.settings.SrfServerSettingsBuilder.xml");
        File file = new File(path);
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(file);
        // This also shows how you can consult the global configuration of the builder
        JSONObject connectionData = new JSONObject();

        String credentialsId = document.getElementsByTagName("credentialsId").item(0).getTextContent();
        UsernamePasswordCredentials credentials = CredentialsProvider.findCredentialById(credentialsId,
                StandardUsernamePasswordCredentials.class, build, URIRequirementBuilder.create().build());

        String app = credentials.getUsername();
        String tenant = app.substring(1, app.indexOf('_'));
        String secret = credentials.getPassword().getPlainText();
        String server = document.getElementsByTagName("srfServerName").item(0).getTextContent();

        // Normalize SRF server URL string if needed
        if (server.substring(server.length() - 1).equals("/")) {
            server = server.substring(0, server.length() - 1);
        }

        boolean https = true;
        if (!server.startsWith("https://")) {
            if (!server.startsWith("http://")) {
                String tmp = server;
                server = "https://";
                server = server.concat(tmp);
            } else
                https = false;
        }
        URL urlTmp = new URL(server);
        if (urlTmp.getPort() == -1) {
            if (https)
                server = server.concat(":443");
            else
                server = server.concat(":80");
        }
        String srfProxy = "";
        String srfTunnel = "";
        try {
            srfProxy = document.getElementsByTagName("srfProxyName").item(0) != null
                    ? document.getElementsByTagName("srfProxyName").item(0).getTextContent().trim()
                    : null;
            srfTunnel = document.getElementsByTagName("srfTunnelPath").item(0) != null
                    ? document.getElementsByTagName("srfTunnelPath").item(0).getTextContent()
                    : null;
        } catch (Exception e) {
            throw e;
        }
        connectionData.put("app", app);
        connectionData.put("tunnel", srfTunnel);
        connectionData.put("secret", secret);
        connectionData.put("server", server);
        connectionData.put("https", (https) ? "True" : "False");
        connectionData.put("proxy", srfProxy);
        connectionData.put("tenant", tenant);
        return connectionData;
    } catch (ParserConfigurationException e) {
        logger.print(e.getMessage());
        logger.print("\n\r");
    } catch (SAXException | IOException e) {
        logger.print(e.getMessage());
    }
    return null;
}

From source file:com.cloud.utils.SwiftUtil.java

public static URL generateTempUrl(SwiftClientCfg cfg, String container, String object, String tempKey,
        int urlExpirationInterval) {

    int currentTime = (int) (System.currentTimeMillis() / 1000L);
    int expirationSeconds = currentTime + urlExpirationInterval;

    try {//from   www .  j  av  a  2  s  .c o  m

        URL endpoint = new URL(cfg.getEndPoint());
        String method = "GET";
        String path = String.format("/v1/AUTH_%s/%s/%s", cfg.getAccount(), container, object);

        //sign the request
        String hmacBody = String.format("%s\n%d\n%s", method, expirationSeconds, path);
        String signature = calculateRFC2104HMAC(hmacBody, tempKey);
        path += String.format("?temp_url_sig=%s&temp_url_expires=%d", signature, expirationSeconds);

        //generate the temp url
        URL tempUrl = new URL(endpoint.getProtocol(), endpoint.getHost(), endpoint.getPort(), path);

        return tempUrl;

    } catch (Exception e) {
        logger.error(e.getMessage());
        throw new CloudRuntimeException(e.getMessage());
    }

}

From source file:com.hpe.application.automation.tools.srf.run.RunFromSrfBuilder.java

public static JSONObject getSrfConnectionData(AbstractBuild<?, ?> build, PrintStream logger) {
    try {//w w w  .  java  2  s  . c o m
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        String path = build.getProject().getParent().getRootDir().toString();
        path = path.concat("/com.hpe.application.automation.tools.settings.SrfServerSettingsBuilder.xml");
        File file = new File(path);
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(file);
        // This also shows how you can consult the global configuration of the builder
        JSONObject connectionData = new JSONObject();

        String app = document.getElementsByTagName("srfAppName").item(0).getTextContent();
        String tenant = app.substring(1, app.indexOf('_'));
        String secret = document.getElementsByTagName("srfSecretName").item(0).getTextContent();
        String server = document.getElementsByTagName("srfServerName").item(0).getTextContent();
        boolean https = true;
        if (!server.startsWith("https://")) {
            if (!server.startsWith("http://")) {
                String tmp = server;
                server = "https://";
                server = server.concat(tmp);
            } else
                https = false;
        }
        URL urlTmp = new URL(server);
        if (urlTmp.getPort() == -1) {
            if (https)
                server = server.concat(":443");
            else
                server = server.concat(":80");
        }
        String srfProxy = "";
        String srfTunnel = "";
        try {
            srfProxy = document.getElementsByTagName("srfProxyName").item(0).getTextContent().trim();
            srfTunnel = document.getElementsByTagName("srfTunnelPath").item(0).getTextContent();
        } catch (Exception e) {
            throw e;
        }
        connectionData.put("app", app);
        connectionData.put("tunnel", srfTunnel);
        connectionData.put("secret", secret);
        connectionData.put("server", server);
        connectionData.put("https", (https) ? "True" : "False");
        connectionData.put("proxy", srfProxy);
        connectionData.put("tenant", tenant);
        return connectionData;
    } catch (ParserConfigurationException e) {
        logger.print(e.getMessage());
        logger.print("\n\r");
    } catch (SAXException | IOException e) {
        logger.print(e.getMessage());
    }
    return null;
}

From source file:com.adguard.commons.web.UrlUtils.java

/**
 * Extracts port from URI//  ww  w . j a v  a2 s .  com
 *
 * @param url URL to get port from
 * @return port value.
 */
public static int getPort(URL url) {
    int port = url.getPort();

    if (port >= 0) {
        return port;
    } else if ("http".equals(url.getProtocol())) {
        return 80;
    } else if ("https".equals(url.getProtocol())) {
        return 443;
    } else if ("ftp".equals(url.getProtocol())) {
        return 21;
    }

    return port;
}

From source file:com.hp.mercury.ci.jenkins.plugins.OOBuildStep.java

public static URI URI(String urlString) {

    try {//from w  w w . j a v a  2 s  .  c o m
        final URL url = new URL(urlString);

        return new URI(url.getProtocol(), null, url.getHost(), url.getPort(), url.getPath(), url.getQuery(),
                null);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:lucee.commons.net.http.httpclient4.HTTPEngineImpl.java

private static HTTPResponse _invoke(URL url, HttpUriRequest request, String username, String password,
        long timeout, boolean redirect, String charset, String useragent, ProxyData proxy,
        lucee.commons.net.http.Header[] headers, Map<String, String> formfields) throws IOException {

    HttpClientBuilder builder = HttpClients.custom();

    // redirect//from w  w  w .  j  a v a2 s.  com
    if (redirect)
        builder.setRedirectStrategy(new DefaultRedirectStrategy());
    else
        builder.disableRedirectHandling();

    HttpHost hh = new HttpHost(url.getHost(), url.getPort());
    setHeader(request, headers);
    if (CollectionUtil.isEmpty(formfields))
        setContentType(request, charset);
    setFormFields(request, formfields, charset);
    setUserAgent(request, useragent);
    if (timeout > 0)
        builder.setConnectionTimeToLive(timeout, TimeUnit.MILLISECONDS);
    HttpContext context = setCredentials(builder, hh, username, password, false);
    setProxy(builder, request, proxy);
    CloseableHttpClient client = builder.build();
    if (context == null)
        context = new BasicHttpContext();
    return new HTTPResponse4Impl(url, context, request, client.execute(request, context));
}