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.baidubce.util.HttpUtils.java

/**
 * Returns true if the specified URI is using a non-standard port (i.e. any port other than 80 for HTTP URIs or any
 * port other than 443 for HTTPS URIs).// w  ww. ja v a2s.c  om
 *
 * @param uri the URI
 * @return True if the specified URI is using a non-standard port, otherwise false.
 */
public static boolean isUsingNonDefaultPort(URI uri) {
    String scheme = uri.getScheme().toLowerCase();
    int port = uri.getPort();
    if (port <= 0) {
        return false;
    }
    if (scheme.equals(Protocol.HTTP.toString())) {
        return port != Protocol.HTTP.getDefaultPort();
    }
    if (scheme.equals(Protocol.HTTPS.toString())) {
        return port != Protocol.HTTPS.getDefaultPort();
    }
    return false;
}

From source file:com.github.wolf480pl.mias4j.util.AbstractTransformingClassLoader.java

public static URL guessCodeSourceURL(String resourcePath, URL resourceURL) {
    // FIXME: Find a better way to do this
    @SuppressWarnings("restriction")
    String escaped = sun.net.www.ParseUtil.encodePath(resourcePath, false);
    String path = resourceURL.getPath();
    if (!path.endsWith(escaped)) {
        // Umm... whadda we do now? Maybe let's fallback to full resource URL.
        LOG.warn("Resource URL path \"" + path + "\" doesn't end with escaped resource path \"" + escaped
                + "\" for resource \"" + resourcePath + "\"");
        return resourceURL;
    }/*from   www  .j a  v a  2s.c o  m*/
    path = path.substring(0, path.length() - escaped.length());
    if (path.endsWith("!/")) { // JAR
        path = path.substring(0, path.length() - 2);
    }
    try {
        URI uri = resourceURL.toURI();
        return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), path, uri.getQuery(),
                uri.getFragment()).toURL();
    } catch (MalformedURLException | URISyntaxException e) {
        // Umm... whadda we do now? Maybe let's fallback to full resource URL.
        LOG.warn("Couldn't assemble CodeSource URL with modified path", e);
        return resourceURL;
    }
}

From source file:password.pwm.http.client.PwmHttpClient.java

public static HttpClient getHttpClient(final Configuration configuration,
        final PwmHttpClientConfiguration pwmHttpClientConfiguration) throws PwmUnrecoverableException {
    final DefaultHttpClient httpClient;
    try {//from  w  w  w.ja  v a  2s.c om
        if (Boolean.parseBoolean(configuration.readAppProperty(AppProperty.SECURITY_HTTP_PROMISCUOUS_ENABLE))) {
            httpClient = new DefaultHttpClient(makeConnectionManager(new X509Utils.PromiscuousTrustManager()));
        } else if (pwmHttpClientConfiguration != null && pwmHttpClientConfiguration.getCertificates() != null) {
            final TrustManager trustManager = new X509Utils.CertMatchingTrustManager(configuration,
                    pwmHttpClientConfiguration.getCertificates());
            httpClient = new DefaultHttpClient(makeConnectionManager(trustManager));
        } else {
            httpClient = new DefaultHttpClient();
        }
    } catch (Exception e) {
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_UNKNOWN,
                "unexpected error creating promiscuous https client: " + e.getMessage()));
    }
    final String strValue = configuration.readSettingAsString(PwmSetting.HTTP_PROXY_URL);
    if (strValue != null && strValue.length() > 0) {
        final URI proxyURI = URI.create(strValue);

        final String host = proxyURI.getHost();
        final int port = proxyURI.getPort();
        final HttpHost proxy = new HttpHost(host, port);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        final String username = proxyURI.getUserInfo();
        if (username != null && username.length() > 0) {
            final String password = (username.contains(":")) ? username.split(":")[1] : "";
            final UsernamePasswordCredentials passwordCredentials = new UsernamePasswordCredentials(username,
                    password);
            httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, port), passwordCredentials);
        }
    }
    final String userAgent = PwmConstants.PWM_APP_NAME + " " + PwmConstants.SERVLET_VERSION;
    httpClient.getParams().setParameter(HttpProtocolParams.USER_AGENT, userAgent);
    return httpClient;
}

From source file:com.magnet.tools.tests.RestStepDefs.java

/**
 * @return get a test http client that trusts all certs
 *//* w w  w .  ja v a 2s.  c  o m*/
private static CloseableHttpClient getTestHttpClient(URI uri) {
    String scheme = uri.getScheme();
    int port = uri.getPort();
    if (scheme.toLowerCase().equals("https")) {
        try {
            SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }, new AllowAllHostnameVerifier());

            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("https", port, sf));
            ClientConnectionManager ccm = new ThreadSafeClientConnManager(registry);
            return new DefaultHttpClient(ccm);
        } catch (Exception e) {
            e.printStackTrace();
            return new DefaultHttpClient();
        }
    } else {
        return new DefaultHttpClient();
    }
}

From source file:net.adamcin.recap.replication.RecapReplicationUtil.java

/**
 * Builds a RecapAddress from related properties of the provided AgentConfig
 * @param config/*from w w w  . java 2s.c om*/
 * @return
 * @throws com.day.cq.replication.ReplicationException
 */
public static RecapAddress getAgentAddress(AgentConfig config) throws ReplicationException {

    final String uri = config.getTransportURI();

    if (!uri.startsWith(TRANSPORT_URI_SCHEME_PREFIX)) {
        throw new ReplicationException("uri must start with " + TRANSPORT_URI_SCHEME_PREFIX);
    }

    final String user = config.getTransportUser();
    final String pass = config.getTransportPassword();

    try {

        final URI parsed = new URI(uri.substring(TRANSPORT_URI_SCHEME_PREFIX.length()));
        final boolean https = "https".equals(parsed.getScheme());
        final String host = parsed.getHost();
        final int port = parsed.getPort() < 0 ? (https ? 443 : 80) : parsed.getPort();
        final String prefix = StringUtils.isEmpty(parsed.getPath()) ? null : parsed.getPath();

        return new DefaultRecapAddress() {
            @Override
            public boolean isHttps() {
                return https;
            }

            @Override
            public String getHostname() {
                return host;
            }

            @Override
            public Integer getPort() {
                return port;
            }

            @Override
            public String getUsername() {
                return user;
            }

            @Override
            public String getPassword() {
                return pass;
            }

            @Override
            public String getServletPath() {
                return prefix;
            }
        };
    } catch (URISyntaxException e) {
        throw new ReplicationException(e);
    }
}

From source file:com.ibm.watson.developer_cloud.retrieve_and_rank.RetrieveAndRankSolrJExample.java

private static HttpClient createHttpClient(String uri, String username, String password) {
    final URI scopeUri = URI.create(uri);

    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(scopeUri.getHost(), scopeUri.getPort()),
            new UsernamePasswordCredentials(username, password));

    final HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(128).setMaxConnPerRoute(32)
            .setDefaultRequestConfig(/*from www . j ava2 s. c o m*/
                    RequestConfig.copy(RequestConfig.DEFAULT).setRedirectsEnabled(true).build())
            .setDefaultCredentialsProvider(credentialsProvider)
            .addInterceptorFirst(new PreemptiveAuthInterceptor());
    return builder.build();
}

From source file:org.apache.camel.component.http4.HttpComponent.java

private static int getPort(URI uri) {
    int port = uri.getPort();
    if (port < 0) {
        if ("http4".equals(uri.getScheme()) || "http".equals(uri.getScheme())) {
            port = 80;/* www.j  a  v  a2 s  .  c o  m*/
        } else if ("https4".equals(uri.getScheme()) || "https".equals(uri.getScheme())) {
            port = 443;
        } else {
            throw new IllegalArgumentException("Unknown scheme, cannot determine port number for uri: " + uri);
        }
    }
    return port;
}

From source file:io.lavagna.config.DataSourceConfig.java

/**
 * for supporting heroku style url:// w  w w .  ja va  2 s .c om
 *
 * <pre>
 * [database type]://[username]:[password]@[host]:[port]/[database name]
 * </pre>
 *
 * @param dataSource
 * @param env
 * @throws URISyntaxException
 */
private static void urlWithCredentials(HikariDataSource dataSource, Environment env) throws URISyntaxException {
    URI dbUri = new URI(env.getRequiredProperty("datasource.url"));
    dataSource.setUsername(dbUri.getUserInfo().split(":")[0]);
    dataSource.setPassword(dbUri.getUserInfo().split(":")[1]);
    dataSource.setJdbcUrl(
            String.format("%s://%s:%s%s", scheme(dbUri), dbUri.getHost(), dbUri.getPort(), dbUri.getPath()));
}

From source file:com.baidubce.util.HttpUtils.java

/**
 * Returns a host header according to the specified URI. The host header is generated with the same logic used by
 * apache http client, that is, append the port to hostname only if it is not the default port.
 *
 * @param uri the URI//from   w  ww .j a  va 2  s.co  m
 * @return a host header according to the specified URI.
 */
public static String generateHostHeader(URI uri) {
    String host = uri.getHost();
    if (isUsingNonDefaultPort(uri)) {
        host += ":" + uri.getPort();
    }
    return host;
}

From source file:nl.knaw.dans.easy.sword2examples.Common.java

public static CloseableHttpClient createHttpClient(URI uri, String uid, String pw) {
    BasicCredentialsProvider credsProv = new BasicCredentialsProvider();
    credsProv.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
            new UsernamePasswordCredentials(uid, pw));
    return HttpClients.custom().setDefaultCredentialsProvider(credsProv).build();
}