Example usage for java.net URL getDefaultPort

List of usage examples for java.net URL getDefaultPort

Introduction

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

Prototype

public int getDefaultPort() 

Source Link

Document

Gets the default port number of the protocol associated with this URL .

Usage

From source file:com.github.mike10004.jenkinsbbhook.WebhookHandler.java

protected CredentialsProvider asCredentialsProvider(URL jenkinsCrumbUrl, AppParams appParams, String username,
        String apiToken) {//from w  w  w  .j  a  va  2  s  .  c o  m
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    String jenkinsHost = jenkinsCrumbUrl.getHost();
    int jenkinsPort = jenkinsCrumbUrl.getPort();
    if (jenkinsPort == -1) {
        jenkinsPort = jenkinsCrumbUrl.getDefaultPort();
    }
    AuthScope scope = new AuthScope(jenkinsHost, jenkinsPort);
    credentialsProvider.setCredentials(scope, new UsernamePasswordCredentials(username, apiToken));
    return credentialsProvider;
}

From source file:org.ut.biolab.medsavant.shared.util.SeekableFTPStream.java

public SeekableFTPStream(URL url, String user, String pwd) {

    if (url == null) {
        throw new IllegalArgumentException("URL may not be null");
    }/*  w w w. java  2s.  c  om*/
    if (!url.getProtocol().toLowerCase().equals("ftp")) {
        throw new IllegalArgumentException("Only ftp:// protocol URLs are valid.");
    }

    source = url.toString();
    username = user;
    password = pwd;
    host = url.getHost();
    int p = url.getPort();
    port = p != -1 ? p : url.getDefaultPort();
    fileName = url.getFile();
    length = 0;
}

From source file:at.spardat.xma.boot.transport.HTTPTransport.java

/**
 * Get the used port of the url. If no port is defined in the url,
 * the default port of the protocol is returned.
 *//*  ww w .ja va  2s.  c  o  m*/
int getPort(URL url) {
    int port = url.getPort();
    if (port == -1) {
        port = url.getDefaultPort();
    }
    return port;
}

From source file:org.geotools.data.wfs.protocol.http.HttpUtil.java

public static String createUri(final URL baseUrl, final Map<String, String> queryStringKvp) {
    final String query = baseUrl.getQuery();
    Map<String, String> finalKvpMap = new HashMap<String, String>(queryStringKvp);
    if (query != null && query.length() > 0) {
        Map<String, String> userParams = new CaseInsensitiveMap(queryStringKvp);
        String[] rawUrlKvpSet = query.split("&");
        for (String rawUrlKvp : rawUrlKvpSet) {
            int eqIdx = rawUrlKvp.indexOf('=');
            String key, value;//ww  w . j  a v  a  2 s .  com
            if (eqIdx > 0) {
                key = rawUrlKvp.substring(0, eqIdx);
                value = rawUrlKvp.substring(eqIdx + 1);
            } else {
                key = rawUrlKvp;
                value = null;
            }
            try {
                value = URLDecoder.decode(value, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
            if (userParams.containsKey(key)) {
                LOGGER.fine("user supplied value for query string argument " + key
                        + " overrides the one in the base url");
            } else {
                finalKvpMap.put(key, value);
            }
        }
    }

    String protocol = baseUrl.getProtocol();
    String host = baseUrl.getHost();
    int port = baseUrl.getPort();
    String path = baseUrl.getPath();

    StringBuilder sb = new StringBuilder();
    sb.append(protocol).append("://").append(host);
    if (port != -1 && port != baseUrl.getDefaultPort()) {
        sb.append(':');
        sb.append(port);
    }
    if (!"".equals(path) && !path.startsWith("/")) {
        sb.append('/');
    }
    sb.append(path).append('?');

    String key, value;
    try {
        Entry<String, String> kvp;
        for (Iterator<Map.Entry<String, String>> it = finalKvpMap.entrySet().iterator(); it.hasNext();) {
            kvp = it.next();
            key = kvp.getKey();
            value = kvp.getValue();
            if (value == null) {
                value = "";
            } else {
                value = URLEncoder.encode(value, "UTF-8");
            }
            sb.append(key);
            sb.append('=');
            sb.append(value);
            if (it.hasNext()) {
                sb.append('&');
            }
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }

    final String finalUrlString = sb.toString();
    return finalUrlString;
}

From source file:com.amazon.speech.speechlet.authentication.SpeechletRequestSignatureVerifier.java

/**
 * Verifies the signing certificate chain URL and returns a {@code URL} object.
 *
 * @param signingCertificateChainUrl/*from  w  w w  .  j  ava 2  s.co m*/
 *            the external form of the URL
 * @return the URL
 * @throws CertificateException
 *             if the URL is malformed or contains an invalid hostname, an unsupported protocol,
 *             or an invalid port (if specified)
 */
static URL getAndVerifySigningCertificateChainUrl(final String signingCertificateChainUrl)
        throws CertificateException {
    try {
        URL url = new URI(signingCertificateChainUrl).normalize().toURL();
        // Validate the hostname
        if (!VALID_SIGNING_CERT_CHAIN_URL_HOST_NAME.equalsIgnoreCase(url.getHost())) {
            throw new CertificateException(String.format(
                    "SigningCertificateChainUrl [%s] does not contain the required hostname" + " of [%s]",
                    signingCertificateChainUrl, VALID_SIGNING_CERT_CHAIN_URL_HOST_NAME));
        }

        // Validate the path prefix
        String path = url.getPath();
        if (!path.startsWith(VALID_SIGNING_CERT_CHAING_URL_PATH_PREFIX)) {
            throw new CertificateException(String.format(
                    "SigningCertificateChainUrl path [%s] is invalid. Expecting path to " + "start with [%s]",
                    signingCertificateChainUrl, VALID_SIGNING_CERT_CHAING_URL_PATH_PREFIX));
        }

        // Validate the protocol
        String urlProtocol = url.getProtocol();
        if (!VALID_SIGNING_CERT_CHAIN_PROTOCOL.equalsIgnoreCase(urlProtocol)) {
            throw new CertificateException(
                    String.format("SigningCertificateChainUrl [%s] contains an unsupported protocol [%s]",
                            signingCertificateChainUrl, urlProtocol));
        }

        // Validate the port uses the default of 443 for HTTPS if explicitly defined in the URL
        int urlPort = url.getPort();
        if ((urlPort != UNSPECIFIED_SIGNING_CERT_CHAIN_URL_PORT_VALUE) && (urlPort != url.getDefaultPort())) {
            throw new CertificateException(
                    String.format("SigningCertificateChainUrl [%s] contains an invalid port [%d]",
                            signingCertificateChainUrl, urlPort));
        }

        return url;
    } catch (IllegalArgumentException | MalformedURLException | URISyntaxException ex) {
        throw new CertificateException(
                String.format("SigningCertificateChainUrl [%s] is malformed", signingCertificateChainUrl), ex);
    }
}

From source file:org.apache.nutch.net.urlnormalizer.basic.BasicURLNormalizer.java

public String normalize(String urlString, String scope) throws MalformedURLException {
    if ("".equals(urlString)) // permit empty
        return urlString;

    urlString = urlString.trim(); // remove extra spaces

    URL url = new URL(urlString);

    String protocol = url.getProtocol();
    String host = url.getHost();/*  ww  w.  j a  v  a 2  s  . co m*/
    int port = url.getPort();
    String file = url.getFile();

    boolean changed = false;

    if (!urlString.startsWith(protocol)) // protocol was lowercased
        changed = true;

    if ("http".equals(protocol) || "ftp".equals(protocol)) {

        if (host != null) {
            String newHost = host.toLowerCase(); // lowercase host
            if (!host.equals(newHost)) {
                host = newHost;
                changed = true;
            }
        }

        if (port == url.getDefaultPort()) { // uses default port
            port = -1; // so don't specify it
            changed = true;
        }

        if (file == null || "".equals(file)) { // add a slash
            file = "/";
            changed = true;
        }

        if (url.getRef() != null) { // remove the ref
            changed = true;
        }

        // check for unnecessary use of "/../"
        String file2 = substituteUnnecessaryRelativePaths(file);

        if (!file.equals(file2)) {
            changed = true;
            file = file2;
        }

    }

    if (changed)
        urlString = new URL(protocol, host, port, file).toString();

    return urlString;
}

From source file:com.iflytek.spider.net.BasicURLNormalizer.java

public String normalize(String urlString) throws MalformedURLException {
    if ("".equals(urlString)) // permit empty
        return urlString;

    urlString = urlString.trim(); // remove extra spaces

    URL url = new URL(urlString);

    String protocol = url.getProtocol();
    String host = url.getHost();//from w w w .ja  v  a 2s  . c  o  m
    int port = url.getPort();
    String file = url.getFile();

    boolean changed = false;

    if (!urlString.startsWith(protocol)) // protocol was lowercased
        changed = true;

    if ("http".equals(protocol) || "ftp".equals(protocol)) {

        if (host != null) {
            String newHost = host.toLowerCase(); // lowercase host
            if (!host.equals(newHost)) {
                host = newHost;
                changed = true;
            }
        }

        if (port == url.getDefaultPort()) { // uses default port
            port = -1; // so don't specify it
            changed = true;
        }

        if (file == null || "".equals(file)) { // add a slash
            file = "/";
            changed = true;
        }

        if (url.getRef() != null) { // remove the ref
            changed = true;
        }

        // check for unnecessary use of "/../"
        String file2 = substituteUnnecessaryRelativePaths(file);

        if (!file.equals(file2)) {
            changed = true;
            file = file2;
        }

    }

    if (changed)
        urlString = new URL(protocol, host, port, file).toString();

    return urlString;
}

From source file:jp.go.nict.langrid.servicesupervisor.invocationprocessor.executor.ServiceInvoker.java

/**
 * /*w  w w.  ja v  a2s  . co  m*/
 * 
 */
public static int invoke(URL url, String userName, String password, Map<String, String> headers,
        InputStream input, HttpServletResponse output, OutputStream errorOut, int connectionTimeout,
        int soTimeout) throws IOException, SocketTimeoutException {
    HttpClient client = HttpClientUtil.createHttpClientWithHostConfig(url);
    SimpleHttpConnectionManager manager = new SimpleHttpConnectionManager(true);
    manager.getParams().setConnectionTimeout(connectionTimeout);
    manager.getParams().setSoTimeout(soTimeout);
    manager.getParams().setMaxConnectionsPerHost(client.getHostConfiguration(), 2);
    client.setHttpConnectionManager(manager);
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(0, false));

    PostMethod method = new PostMethod(url.getFile());
    method.setRequestEntity(new InputStreamRequestEntity(input));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        method.addRequestHeader(e.getKey(), e.getValue());
    }
    if (!headers.containsKey("Content-Type"))
        method.addRequestHeader("Content-Type", "text/xml; charset=utf-8");
    if (!headers.containsKey("Accept"))
        method.addRequestHeader("Accept", "application/soap+xml, application/dime, multipart/related, text/*");
    if (!headers.containsKey("SOAPAction"))
        method.addRequestHeader("SOAPAction", "\"\"");
    if (!headers.containsKey("User-Agent"))
        method.addRequestHeader("User-Agent", "Langrid Service Invoker/1.0");
    if (userName != null) {
        int port = url.getPort();
        if (port == -1) {
            port = url.getDefaultPort();
            if (port == -1) {
                port = 80;
            }
        }
        if (password == null) {
            password = "";
        }
        client.getState().setCredentials(new AuthScope(url.getHost(), port, null),
                new UsernamePasswordCredentials(userName, password));
        client.getParams().setAuthenticationPreemptive(true);
        method.setDoAuthentication(true);
    }

    try {
        int status;
        try {
            status = client.executeMethod(method);
        } catch (SocketTimeoutException e) {
            status = HttpServletResponse.SC_REQUEST_TIMEOUT;
        }
        output.setStatus(status);
        if (status == 200) {
            for (Header h : method.getResponseHeaders()) {
                String name = h.getName();
                if (name.startsWith("X-Langrid") || (!throughHeaders.contains(name.toLowerCase())))
                    continue;
                String value = h.getValue();
                output.addHeader(name, value);
            }
            OutputStream os = output.getOutputStream();
            StreamUtil.transfer(method.getResponseBodyAsStream(), os);
            os.flush();
        } else if (status == HttpServletResponse.SC_REQUEST_TIMEOUT) {
        } else {
            StreamUtil.transfer(method.getResponseBodyAsStream(), errorOut);
        }
        return status;
    } finally {
        manager.shutdown();
    }
}

From source file:saintybalboa.nutch.net.AdvancedURLNormalizer.java

public String normalize(String urlString, String scope) throws MalformedURLException {
    if ("".equals(urlString)) // permit empty
        return urlString;

    urlString = urlString.trim(); // remove extra spaces
    String ourlString = urlString;
    URL url = new URL(urlString);

    String protocol = url.getProtocol();
    String host = url.getHost().toLowerCase();
    int port = url.getPort();
    String path = url.getPath().toLowerCase();
    String queryStr = url.getQuery();

    boolean changed = false;

    if (!urlString.startsWith(protocol)) // protocol was lowercased
        changed = true;/* w  w  w  .j  a va  2 s  .c  o m*/

    if ("http".equals(protocol) || "https".equals(protocol) || "ftp".equals(protocol)) {

        if (host != null) {
            String newHost = host.toLowerCase(); // lowercase host
            if (!host.equals(newHost)) {
                host = newHost;
                changed = true;
            }
        }

        if (port == url.getDefaultPort()) { // uses default port
            port = -1; // so don't specify it
            changed = true;
        }

        if (url.getRef() != null) { // remove the ref
            changed = true;
        }

        if (queryStr != null) {
            if (!queryStr.isEmpty() && queryStr != "?") {

                changed = true;

                //convert query param names values to lowercase. Dependent on arguments
                queryStr = formatQueryString(queryStr);
            }
        }

    }

    urlString = (queryStr != null && queryStr != "")
            ? new URL(protocol, host, port, path).toString() + "?" + queryStr
            : new URL(protocol, host, port, path).toString();

    //the url should be the same as the url passed in
    if (ourlString.length() > urlString.length())
        urlString = urlString + ourlString.substring(urlString.length(), ourlString.length());

    return urlString;
}

From source file:org.eclipse.smila.connectivity.framework.crawler.web.net.BasicUrlNormalizer.java

/**
 * {@inheritDoc}// ww  w . j  a  v  a  2s  .  c  om
 */
public String normalize(String urlString) throws MalformedURLException {
    if ("".equals(urlString)) {
        return urlString;
    }

    // remove extra spaces
    urlString = urlString.trim();

    final URL url = new URL(urlString);

    final String protocol = url.getProtocol();
    String host = url.getHost();
    int port = url.getPort();
    String file = url.getFile();

    boolean changed = false;

    if (!urlString.startsWith(protocol)) {
        changed = true;
    }

    if ("http".equals(protocol) || "ftp".equals(protocol)) {

        if (host != null) {
            final String newHost = host.toLowerCase(); // lower case host
            if (!host.equals(newHost)) {
                host = newHost;
                changed = true;
            }
        }

        if (port == url.getDefaultPort()) { // uses default port
            port = -1; // so don't specify it
            changed = true;
        }

        if (file == null || "".equals(file)) { // add a slash
            file = "/";
            changed = true;
        }

        if (url.getRef() != null) { // remove the reference
            changed = true;
        }

        // check for unnecessary use of "/../"
        final String file2 = substituteUnnecessaryRelativePaths(file);

        if (!file.equals(file2)) {
            changed = true;
            file = file2;
        }

    }

    if (changed) {
        urlString = new URL(protocol, host, port, file).toString();
    }

    return urlString;
}