Example usage for java.net URI getPort

List of usage examples for java.net URI getPort

Introduction

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

Prototype

public int getPort() 

Source Link

Document

Returns the port number of this URI.

Usage

From source file:com.microsoft.gittf.client.clc.connection.GitTFHTTPClientFactory.java

/**
 * Determines whether the given host should be proxied or not, based on the
 * comma-separated list of wildcards to not proxy (generally taken from the
 * <code>http.nonProxyHosts</code> system property.
 * //w ww  . j  av a  2s . c  om
 * @param host
 *        the host to query (not <code>null</code>)
 * @param nonProxyHosts
 *        the pipe-separated list of hosts (or wildcards) that should not be
 *        proxied, or <code>null</code> if all hosts are proxied
 * @return <code>true</code> if the host should be proxied,
 *         <code>false</code> otherwise
 */
static boolean hostExcludedFromProxyEnvironment(URI serverURI, String nonProxyHosts) {
    if (serverURI == null || serverURI.getHost() == null || nonProxyHosts == null) {
        return false;
    }

    nonProxyHosts = nonProxyHosts.trim();
    if (nonProxyHosts.length() == 0) {
        return false;
    }

    /*
     * The no_proxy setting may be '*' to indicate nothing is proxied.
     * However, this is the only allowable use of a wildcard.
     */
    if ("*".equals(nonProxyHosts)) //$NON-NLS-1$
    {
        return true;
    }

    String serverHost = serverURI.getHost();

    /* Map default ports to the appropriate default. */
    int serverPort = serverURI.getPort();

    if (serverPort == -1) {
        try {
            serverPort = Protocol.getProtocol(serverURI.getScheme().toLowerCase()).getDefaultPort();
        } catch (IllegalStateException e) {
            serverPort = 80;
        }
    }

    for (String nonProxyHost : nonProxyHosts.split(",")) //$NON-NLS-1$
    {
        int nonProxyPort = -1;

        if (nonProxyHost.contains(":")) //$NON-NLS-1$
        {
            String[] nonProxyParts = nonProxyHost.split(":", 2); //$NON-NLS-1$

            nonProxyHost = nonProxyParts[0];

            try {
                nonProxyPort = Integer.parseInt(nonProxyParts[1]);
            } catch (Exception e) {
                log.warn(MessageFormat.format("Could not parse port in non_proxy setting: {0}, ignoring port", //$NON-NLS-1$
                        nonProxyParts[1]));
            }
        }

        /*
         * If the no_proxy entry specifies a port, match it exactly. If it
         * does not, this means to match all ports.
         */
        if (nonProxyPort != -1 && serverPort != nonProxyPort) {
            continue;
        }

        /*
         * Otherwise, the nonProxyHost portion is treated as the trailing
         * DNS entry
         */
        if (LocaleInvariantStringHelpers.caseInsensitiveEndsWith(serverHost, nonProxyHost)) {
            return true;
        }
    }

    return false;
}

From source file:beadsan.AppConfig.java

@ConfigurationProperties("spring.datasource")
@Bean(destroyMethod = "close")
DataSource realDataSource() throws URISyntaxException {
    String url;// ww w .j  a  v  a2  s  .co  m
    String username;
    String password;

    String databaseUrl = System.getenv("DATABASE_URL");
    if (databaseUrl != null) {
        URI dbUri = new URI(databaseUrl);
        url = "jdbc:postgresql://" + dbUri.getHost() + ":" + dbUri.getPort() + dbUri.getPath();
        username = dbUri.getUserInfo().split(":")[0];
        password = dbUri.getUserInfo().split(":")[1];
    } else {
        url = this.properties.getUrl();
        username = this.properties.getUsername();
        password = this.properties.getPassword();
    }

    DataSourceBuilder factory = DataSourceBuilder.create(this.properties.getClassLoader()).url(url)
            .username(username).password(password);
    this.dataSource = factory.build();
    return this.dataSource;
}

From source file:net.bluemix.todo.connector.CloudantServiceInfoCreator.java

@Override
public CloudantServiceInfo createServiceInfo(Map<String, Object> serviceData) {
    Map<String, Object> credentials = (Map<String, Object>) serviceData.get("credentials");
    String id = (String) serviceData.get("name");
    try {//w  w w .  j  a  v  a 2 s.c  o m
        URI uri = new URI((String) credentials.get("url"));
        String scheme = uri.getScheme();
        int port = uri.getPort();
        String host = uri.getHost();
        String path = uri.getPath();
        String query = uri.getQuery();
        String fragment = uri.getFragment();
        String url = new URI(scheme, "", host, port, path, query, fragment).toString();
        String[] userInfo = uri.getUserInfo().split(":");
        return new CloudantServiceInfo(id, userInfo[0], userInfo[1], url);
    } catch (URISyntaxException e) {
        return null;
    }
}

From source file:com.microsoft.tfs.client.clc.CLCHTTPClientFactory.java

/**
 * Determines whether the given host should be proxied or not, based on the
 * comma-separated list of wildcards to not proxy (generally taken from the
 * <code>http.nonProxyHosts</code> system property.
 *
 * @param host//from w w  w. ja  v  a  2 s  .c om
 *        the host to query (not <code>null</code>)
 * @param nonProxyHosts
 *        the pipe-separated list of hosts (or wildcards) that should not be
 *        proxied, or <code>null</code> if all hosts are proxied
 * @return <code>true</code> if the host should be proxied,
 *         <code>false</code> otherwise
 */
static boolean hostExcludedFromProxyEnvironment(final URI serverURI, String nonProxyHosts) {
    if (serverURI == null || serverURI.getHost() == null || nonProxyHosts == null) {
        return false;
    }

    nonProxyHosts = nonProxyHosts.trim();
    if (nonProxyHosts.length() == 0) {
        return false;
    }

    /*
     * The no_proxy setting may be '*' to indicate nothing is proxied.
     * However, this is the only allowable use of a wildcard.
     */
    if ("*".equals(nonProxyHosts)) //$NON-NLS-1$
    {
        return true;
    }

    final String serverHost = serverURI.getHost();

    /* Map default ports to the appropriate default. */
    int serverPort = serverURI.getPort();

    if (serverPort == -1) {
        try {
            serverPort = Protocol.getProtocol(serverURI.getScheme().toLowerCase()).getDefaultPort();
        } catch (final IllegalStateException e) {
            serverPort = 80;
        }
    }

    for (String nonProxyHost : nonProxyHosts.split(",")) //$NON-NLS-1$
    {
        int nonProxyPort = -1;

        if (nonProxyHost.contains(":")) //$NON-NLS-1$
        {
            final String[] nonProxyParts = nonProxyHost.split(":", 2); //$NON-NLS-1$

            nonProxyHost = nonProxyParts[0];

            try {
                nonProxyPort = Integer.parseInt(nonProxyParts[1]);
            } catch (final Exception e) {
                log.warn(MessageFormat.format("Could not parse port in non_proxy setting: {0}, ignoring port", //$NON-NLS-1$
                        nonProxyParts[1]));
            }
        }

        /*
         * If the no_proxy entry specifies a port, match it exactly. If it
         * does not, this means to match all ports.
         */
        if (nonProxyPort != -1 && serverPort != nonProxyPort) {
            continue;
        }

        /*
         * Otherwise, the nonProxyHost portion is treated as the trailing
         * DNS entry
         */
        if (LocaleInvariantStringHelpers.caseInsensitiveEndsWith(serverHost, nonProxyHost)) {
            return true;
        }
    }

    return false;
}

From source file:org.dasein.security.joyent.AuthClientFactory.java

@Override
public @Nonnull HttpClient getClient(String endpoint) throws CloudException, InternalException {

    if (endpoint == null) {
        throw new CloudException("No cloud endpoint was defined");
    }/*from  w  w w .  ja v  a2 s .c  o  m*/

    boolean ssl = endpoint.startsWith("https");
    int targetPort;
    URI uri;

    try {
        uri = new URI(endpoint);
        targetPort = uri.getPort();
        if (targetPort < 1) {
            targetPort = (ssl ? 443 : 80);
        }
    } catch (URISyntaxException e) {
        throw new CloudException(e);
    }
    HttpHost targetHost = new HttpHost(uri.getHost(), targetPort, uri.getScheme());

    DefaultHttpClient client = (DefaultHttpClient) super.getClient(endpoint);

    try {
        String userName = new String(getProviderContext().getAccessPublic(), "utf-8");
        String password = new String(getProviderContext().getAccessPrivate(), "utf-8");

        client.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(userName, password));
    } catch (UnsupportedEncodingException e) {
        throw new InternalException(e);
    }
    return client;
}

From source file:com.buaa.cfs.utils.NetUtils.java

/**
 * Create an InetSocketAddress from the given target string and default port. If the string cannot be parsed
 * correctly, the <code>configName</code> parameter is used as part of the exception message, allowing the user to
 * better diagnose the misconfiguration.
 *
 * @param target      a string of either "host" or "host:port"
 * @param defaultPort the default port if <code>target</code> does not include a port number
 * @param configName  the name of the configuration from which <code>target</code> was loaded. This is used in the
 *                    exception message in the case that parsing fails.
 *///ww  w . j av a 2s . c  o  m
public static InetSocketAddress createSocketAddr(String target, int defaultPort, String configName) {
    String helpText = "";
    if (configName != null) {
        helpText = " (configuration property '" + configName + "')";
    }
    if (target == null) {
        throw new IllegalArgumentException("Target address cannot be null." + helpText);
    }
    target = target.trim();
    boolean hasScheme = target.contains("://");
    URI uri = null;
    try {
        uri = hasScheme ? URI.create(target) : URI.create("dummyscheme://" + target);
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException(
                "Does not contain a valid host:port authority: " + target + helpText);
    }

    String host = uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
        port = defaultPort;
    }
    String path = uri.getPath();

    if ((host == null) || (port < 0) || (!hasScheme && path != null && !path.isEmpty())) {
        throw new IllegalArgumentException(
                "Does not contain a valid host:port authority: " + target + helpText);
    }
    return createSocketAddrForHost(host, port);
}

From source file:com.cognifide.actions.msg.push.active.PushClientRunnable.java

public PushClientRunnable(Set<PushReceiver> receivers, String serverUrl, String username, String password)
        throws URISyntaxException {
    this.receivers = receivers;
    this.serverUrl = serverUrl;

    final HttpConnectionManager connManager = new MultiThreadedHttpConnectionManager();
    client = new HttpClient(connManager);
    client.getParams().setAuthenticationPreemptive(true);
    final Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
    final URI serverUri = new URI(serverUrl);
    final int port = serverUri.getPort() == -1 ? 80 : serverUri.getPort();
    client.getState().setCredentials(new AuthScope(serverUri.getHost(), port, AuthScope.ANY_REALM),
            defaultcreds);//from  w w  w.j  a v  a 2 s .co  m
}

From source file:org.mulgara.scon.Connection.java

/**
 * Encodes a URI if it looks like it needs it.
 * @param u The URI to encode, if needed.
 * @return a minimally encoded URI./* w  ww  .j  a v  a2 s  .  co m*/
 */
private static final String enc(URI u) {
    try {
        // if there is no query, then just return the unencoded URI
        String query = u.getRawQuery();
        if (query == null)
            return u.toString();
        // encode the query, and add it to the end of the URI
        String encQuery = encode(query);
        String encU = new URI(u.getScheme(), u.getUserInfo(), u.getHost(), u.getPort(), u.getPath(), encQuery,
                u.getFragment()).toString();
        // if the partial encoding works, then return it
        if (decode(encU).equals(u.toString()))
            return encU;
        // nothing else worked, so encode it fully
        return encode(u.toString());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Unable to encode a URI", e);
    }
}

From source file:de.betterform.connector.xmlrpc.XMLRPCURIResolver.java

/**
 * Parses the URI into three elements./*w  w  w  .j  av  a  2s  .  co m*/
 * The xmlrpc URL, the function and the params
 *
 * @return a Vector
 */
private Vector parseURI(URI uri) {
    String host = uri.getHost();
    int port = uri.getPort();
    String path = uri.getPath();
    String query = uri.getQuery();

    /* Split the path up into basePath and function */
    int finalSlash = path.lastIndexOf('/');
    String basePath = "";
    if (finalSlash > 0) {
        basePath = path.substring(1, finalSlash);
    }
    String function = path.substring(finalSlash + 1, path.length());

    String rpcURL = "http://" + host + ":" + port + "/" + basePath;

    log.debug("New URL  = " + rpcURL);
    log.debug("Function = " + function);

    Hashtable paramHash = new Hashtable();

    if (query != null) {
        String[] params = query.split("&");

        for (int i = 0; i < params.length; i++) {
            log.debug("params[" + i + "] = " + params[i]);
            String[] keyval = params[i].split("=");
            log.debug("\t" + keyval[0] + " -> " + keyval[1]);
            paramHash.put(keyval[0], keyval[1]);
        }
    }

    Vector ret = new Vector();
    ret.add(rpcURL);
    ret.add(function);
    ret.add(paramHash);
    return ret;
}

From source file:com.orange.spring.cloud.connector.s3.heroku.S3ServiceInfoCreator.java

public S3ServiceInfo createServiceInfo(S3DetectableService s3DetectableService) {
    Map<String, String> env = environment.getEnv();
    String accessKeyId = env.get(s3DetectableService.getAccessKeyIdEnvKey());
    String secretAccessKey = env.get(s3DetectableService.getSecretAccessKeyEnvKey());
    String bucketName = env.get(s3DetectableService.getBucketNameEnvKey());
    String finalUrl = this.getFinalUrl(s3DetectableService, bucketName);
    URI finalUri = URI.create(finalUrl);
    return new S3ServiceInfo(bucketName, finalUri.getScheme(), finalUri.getHost(), finalUri.getPort(),
            accessKeyId, secretAccessKey, finalUri.getPath());
}