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:cdr.forms.SwordDepositHandler.java

/**
 * Generates a limited authentication scope for the supplied URL, so that an HTTP client will not send username and
 * passwords to other URLs./*from   w  w w .  j av  a2 s.  c  o m*/
 * 
 * @param queryURL
 *           the URL for the query.
 * @return an authentication scope tuned to the requested URL.
 * @throws IllegalArgumentException
 *            if <code>queryURL</code> is not a well-formed URL.
 */
public static AuthScope getAuthenticationScope(String queryURL) {
    if (queryURL == null) {
        throw new NullPointerException("Cannot derive authentication scope for null URL");
    }
    try {
        URL url = new URL(queryURL);
        // port defaults to 80 unless the scheme is https
        // or the port is explicitly set in the URL.
        int port = 80;
        if (url.getPort() == -1) {
            if ("https".equals(url.getProtocol())) {
                port = 443;
            }
        } else {
            port = url.getPort();
        }
        return new AuthScope(url.getHost(), port);
    } catch (MalformedURLException mue) {
        throw new IllegalArgumentException("supplied URL <" + queryURL + "> is ill-formed:" + mue.getMessage());
    }
}

From source file:com.skcraft.launcher.util.HttpRequest.java

/**
 * URL may contain spaces and other nasties that will cause a failure.
 *
 * @param existing the existing URL to transform
 * @return the new URL, or old one if there was a failure
 *///ww  w.  j a v  a  2 s .  co m
private static URL reformat(URL existing) {
    try {
        URL url = new URL(existing.toString());
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        url = uri.toURL();
        return url;
    } catch (MalformedURLException e) {
        return existing;
    } catch (URISyntaxException e) {
        return existing;
    }
}

From source file:com.evilisn.DAO.CertMapper.java

public static byte[] httpGetBin(URI uri, boolean bActiveCheckUnknownHost) throws Exception

{

    InputStream is = null;//www. j  a  v  a 2  s  .c o  m

    InputStream is_temp = null;

    try {

        if (uri == null)
            return null;

        URL url = uri.toURL();

        if (bActiveCheckUnknownHost) {

            url.getProtocol();

            String host = url.getHost();

            int port = url.getPort();

            if (port == -1)

                port = url.getDefaultPort();

            InetSocketAddress isa = new InetSocketAddress(host, port);

            if (isa.isUnresolved()) {

                //fix JNLP popup error issue

                throw new UnknownHostException("Host Unknown:" + isa.toString());

            }

        }

        HttpURLConnection uc = (HttpURLConnection) url.openConnection();

        uc.setDoInput(true);

        uc.setAllowUserInteraction(false);

        uc.setInstanceFollowRedirects(true);

        setTimeout(uc);

        String contentEncoding = uc.getContentEncoding();

        int len = uc.getContentLength();

        // is = uc.getInputStream();

        if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("gzip") != -1)

        {

            is_temp = uc.getInputStream();

            is = new GZIPInputStream(is_temp);

        }

        else if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("deflate") != -1)

        {

            is_temp = uc.getInputStream();

            is = new InflaterInputStream(is_temp);

        }

        else

        {

            is = uc.getInputStream();

        }

        if (len != -1) {

            int ch = 0, i = 0;

            byte[] res = new byte[len];

            while ((ch = is.read()) != -1) {

                res[i++] = (byte) (ch & 0xff);

            }

            return res;

        } else {

            ArrayList<byte[]> buffer = new ArrayList<byte[]>();

            int buf_len = 1024;

            byte[] res = new byte[buf_len];

            int ch = 0, i = 0;

            while ((ch = is.read()) != -1) {

                res[i++] = (byte) (ch & 0xff);

                if (i == buf_len) {

                    //rotate

                    buffer.add(res);

                    i = 0;

                    res = new byte[buf_len];

                }

            }

            int total_len = buffer.size() * buf_len + i;

            byte[] buf = new byte[total_len];

            for (int j = 0; j < buffer.size(); j++) {

                System.arraycopy(buffer.get(j), 0, buf, j * buf_len, buf_len);

            }

            if (i > 0) {

                System.arraycopy(res, 0, buf, buffer.size() * buf_len, i);

            }

            return buf;

        }

    } catch (Exception e) {

        e.printStackTrace();

        return null;

    } finally {

        closeInputStream(is_temp);

        closeInputStream(is);

    }

}

From source file:io.cloudslang.content.amazon.utils.InputsUtil.java

public static String getEndpointFromUrl(String input) throws MalformedURLException {
    URL url = new URL(input);
    String endpoint = url.getHost();
    if (url.getPort() > START_INDEX) {
        endpoint += COLON + url.getPort();
    }/* w w w .java 2s. co  m*/
    return endpoint;
}

From source file:com.digitalpebble.storm.crawler.protocol.http.HttpRobotRulesParser.java

/**
 * Compose unique key to store and access robot rules in cache for given URL
 *//*w w  w . ja v a2  s.c  o m*/
protected static String getCacheKey(URL url) {
    String protocol = url.getProtocol().toLowerCase(Locale.ROOT); // normalize
                                                                  // to
                                                                  // lower
                                                                  // case
    String host = url.getHost().toLowerCase(Locale.ROOT); // normalize to
                                                          // lower case
    int port = url.getPort();
    if (port == -1) {
        port = url.getDefaultPort();
    }
    /*
     * Robot rules apply only to host, protocol, and port where robots.txt
     * is hosted (cf. NUTCH-1752). Consequently
     */
    String cacheKey = protocol + ":" + host + ":" + port;
    return cacheKey;
}

From source file:com.zimbra.cs.servlet.util.AuthUtil.java

public static String getRedirectURL(HttpServletRequest req, Server server, boolean isAdminRequest,
        boolean relative) throws ServiceException, MalformedURLException {
    String redirectUrl;//from w  ww.ja va2  s  . co  m
    if (isAdminRequest) {
        redirectUrl = getAdminURL(server, relative);
    } else {
        redirectUrl = getMailURL(server, relative);
    }
    if (!relative) {
        URL url = new URL(redirectUrl);

        // replace host of the URL to the host the request was sent to
        String reqHost = req.getServerName();
        String host = url.getHost();

        if (!reqHost.equalsIgnoreCase(host)) {
            URL destUrl = new URL(url.getProtocol(), reqHost, url.getPort(), url.getFile());
            redirectUrl = destUrl.toString();
        }
    }
    return redirectUrl;
}

From source file:sit.web.client.HttpHelper.java

public static void apacheDownload(String downloadUrl, File targetFile) throws IOException {

    URL url = new URL(downloadUrl);

    HttpClient httpclient;//  ww w . j av a 2 s .c o  m
    if (isHTTPS(downloadUrl)) {
        httpclient = HTTPTrustHelper.getNewHttpClient(Charset.defaultCharset(),
                (url.getPort() != -1) ? url.getPort() : url.getDefaultPort());
    } else {
        httpclient = new DefaultHttpClient();
    }

    HttpGet request = new HttpGet(downloadUrl);
    HttpResponse response = httpclient.execute(request);

    InputStream is = response.getEntity().getContent();
    FileOutputStream writer = new FileOutputStream(targetFile);

    try {
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = 0;
        while ((bytesRead = is.read(buffer, 0, buffer.length)) >= 0) {
            writer.write(buffer, 0, bytesRead);
        }
    } finally {
        writer.close();
        is.close();
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:URLUtils.java

/**
 * Checks that the protocol://host:port part of two URLs are equal.
 * /*w w w .j  a v a  2  s.  co m*/
 * @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: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 w  w  w . ja va2s  .  c o m*/

    return normalizedUrl;
}

From source file:com.vmware.vchs.publicapi.samples.HttpUtils.java

/**
 * This method will parse the passed in String which is presumably a complete URL and return the
 * base URL e.g. https://vchs.vmware.api/ from the component parts of the passed in URL.
 * /*w w w . j  av  a  2s . c o m*/
 * @param vDCUrl
 *            the VDC Href to parse
 * @return the base url of the vCloud
 */
public static String getHostname(String completeUrl) {
    URL baseUrl = null;

    try {
        // First create a URL object
        baseUrl = new URL(completeUrl);
        // Now use the URL implementation to provide the component parts, leaving out
        // some parts so that we can build just the base URL without the path and query string
        return new URL(baseUrl.getProtocol(), baseUrl.getHost(), baseUrl.getPort(), "").toString();
    } catch (MalformedURLException e) {
        throw new RuntimeException("Invalid URL: " + completeUrl);
    }
}