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.facebook.presto.jdbc.PrestoConnection.java

PrestoConnection(URI uri, String user, QueryExecutor queryExecutor) throws SQLException {
    this.uri = checkNotNull(uri, "uri is null");
    this.address = HostAndPort.fromParts(uri.getHost(), uri.getPort());
    this.user = checkNotNull(user, "user is null");
    this.queryExecutor = checkNotNull(queryExecutor, "queryExecutor is null");
    catalog.set("default");
    schema.set("default");
    timeZoneId.set(TimeZone.getDefault().getID());
    locale.set(Locale.getDefault());

    if (!isNullOrEmpty(uri.getPath())) {
        setCatalogAndSchema();//from   w ww  . j a  v  a  2s  .  co  m
    }
}

From source file:com.geoxp.oss.client.OSSClient.java

private static void changeACL(boolean remove, String ossURL, String sshKeyFingerprint, String secretname,
        List<String> keyfpr) throws OSSException {

    SSHAgentClient agent = null;//from  ww  w .  ja v  a  2 s  .  c om

    HttpClient httpclient = null;

    try {
        agent = new SSHAgentClient();

        List<SSHKey> sshkeys = agent.requestIdentities();

        //
        // If no SSH Key fingerprint was provided, try all SSH keys available in the agent
        //

        List<String> fingerprints = new ArrayList<String>();

        if (null == sshKeyFingerprint) {
            for (SSHKey key : sshkeys) {
                fingerprints.add(key.fingerprint);
            }
        } else {
            fingerprints.add(sshKeyFingerprint.toLowerCase().replaceAll("[^0-9a-f]", ""));
        }

        int idx = 0;

        for (String fingerprint : fingerprints) {
            idx++;

            //
            // Ask the SSH agent for the SSH key blob
            //

            byte[] keyblob = null;

            for (SSHKey key : sshkeys) {
                if (key.fingerprint.equals(fingerprint)) {
                    keyblob = key.blob;
                    break;
                }
            }

            //
            // Throw an exception if this condition is encountered as it can only happen if
            // there was a provided fingerprint which is not in the agent.
            //

            if (null == keyblob) {
                throw new OSSException("SSH Key " + sshKeyFingerprint + " was not found by your SSH agent.");
            }

            //
            // Retrieve OSS RSA key
            //

            RSAPublicKey pubkey = getOSSRSA(ossURL);

            //
            // Build the token
            //
            // <TS> <<SECRET_NAME><FINGERPRINT1>....<FINGERPRINTN>> <SSH Signing Key Blob> <SSH Signature Blob>
            //

            ByteArrayOutputStream token = new ByteArrayOutputStream();

            byte[] tsdata = nowBytes();

            token.write(CryptoHelper.encodeNetworkString(tsdata));

            ByteArrayOutputStream subtoken = new ByteArrayOutputStream();

            subtoken.write(CryptoHelper.encodeNetworkString(secretname.getBytes("UTF-8")));

            for (String fpr : keyfpr) {
                subtoken.write(CryptoHelper
                        .encodeNetworkString(fpr.toLowerCase().replaceAll("[^a-f0-9]", "").getBytes("UTF-8")));
            }

            token.write(CryptoHelper.encodeNetworkString(subtoken.toByteArray()));
            token.write(CryptoHelper.encodeNetworkString(keyblob));

            byte[] sigblob = agent.sign(keyblob, token.toByteArray());

            token.write(CryptoHelper.encodeNetworkString(sigblob));

            //
            // Encrypt the token with a random AES256 key
            //

            byte[] aeskey = new byte[32];
            CryptoHelper.getSecureRandom().nextBytes(aeskey);

            byte[] wrappedtoken = CryptoHelper.wrapAES(aeskey, token.toByteArray());

            //
            // Encrypt the random key with OSS' RSA key
            //

            byte[] sealedaeskey = CryptoHelper.encryptRSA(pubkey, aeskey);

            //
            // Create the token
            //

            token.reset();

            token.write(CryptoHelper.encodeNetworkString(wrappedtoken));
            token.write(CryptoHelper.encodeNetworkString(sealedaeskey));

            //
            // Base64 encode the encryptedtoken
            //

            String b64token = new String(Base64.encode(token.toByteArray()), "UTF-8");

            //
            // Send request to OSS
            //

            URIBuilder builder = new URIBuilder(ossURL + (remove ? GuiceServletModule.SERVLET_PATH_REMOVE_ACL
                    : GuiceServletModule.SERVLET_PATH_ADD_ACL));

            builder.addParameter("token", b64token);

            URI uri = builder.build();

            String qs = uri.getRawQuery();

            HttpPost post = new HttpPost(
                    uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + uri.getPath());

            post.setHeader("Content-Type", "application/x-www-form-urlencoded");

            post.setEntity(new StringEntity(qs));

            httpclient = newHttpClient();

            HttpResponse response = httpclient.execute(post);
            HttpEntity resEntity = response.getEntity();
            String content = EntityUtils.toString(resEntity, "UTF-8");

            post.reset();

            if (HttpServletResponse.SC_OK != response.getStatusLine().getStatusCode()) {
                // Only throw an exception if this is the last SSH key we could try
                if (idx == fingerprints.size()) {
                    throw new OSSException("None of the provided keys (" + idx
                            + ") could be used to modify ACL. Latest error message was: "
                            + response.getStatusLine().getReasonPhrase());
                } else {
                    continue;
                }
            }

            return;
        }
    } catch (OSSException osse) {
        throw osse;
    } catch (Exception e) {
        throw new OSSException(e);
    } finally {
        if (null != httpclient) {
            httpclient.getConnectionManager().shutdown();
        }
        if (null != agent) {
            agent.close();
        }
    }
}

From source file:com.cloud.storage.template.HttpTemplateDownloader.java

private Pair<String, Integer> validateUrl(String url) throws IllegalArgumentException {
    try {//www.  j  a v a  2s  .c  om
        URI uri = new URI(url);
        if (!uri.getScheme().equalsIgnoreCase("http") && !uri.getScheme().equalsIgnoreCase("https")) {
            throw new IllegalArgumentException("Unsupported scheme for url");
        }
        int port = uri.getPort();
        if (!(port == 80 || port == 443 || port == -1)) {
            throw new IllegalArgumentException("Only ports 80 and 443 are allowed");
        }

        if (port == -1 && uri.getScheme().equalsIgnoreCase("https")) {
            port = 443;
        } else if (port == -1 && uri.getScheme().equalsIgnoreCase("http")) {
            port = 80;
        }

        String host = uri.getHost();
        try {
            InetAddress hostAddr = InetAddress.getByName(host);
            if (hostAddr.isAnyLocalAddress() || hostAddr.isLinkLocalAddress() || hostAddr.isLoopbackAddress()
                    || hostAddr.isMulticastAddress()) {
                throw new IllegalArgumentException("Illegal host specified in url");
            }
            if (hostAddr instanceof Inet6Address) {
                throw new IllegalArgumentException(
                        "IPV6 addresses not supported (" + hostAddr.getHostAddress() + ")");
            }
            return new Pair<String, Integer>(host, port);
        } catch (UnknownHostException uhe) {
            throw new IllegalArgumentException("Unable to resolve " + host);
        }
    } catch (IllegalArgumentException iae) {
        s_logger.warn("Failed uri validation check: " + iae.getMessage());
        throw iae;
    } catch (URISyntaxException use) {
        s_logger.warn("Failed uri syntax check: " + use.getMessage());
        throw new IllegalArgumentException(use.getMessage());
    }
}

From source file:com.machinepublishers.jbrowserdriver.CookieStore.java

/**
 * {@inheritDoc}//from   w w  w  .  jav a 2 s.  com
 */
@Override
public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException {
    if (isJavascript(uri.getScheme())) {
        for (Map.Entry<String, List<String>> entry : responseHeaders.entrySet()) {
            for (String value : entry.getValue()) {
                try {
                    List<Cookie> cookies = spec.parse(new BasicHeader(entry.getKey(), value),
                            new CookieOrigin(uri.getHost(), canonicalPort(uri.getScheme(), uri.getPort()),
                                    canonicalPath(uri.getPath()), isSecure(uri.getScheme())));
                    for (Cookie cookie : cookies) {
                        synchronized (store) {
                            store.addCookie(cookie);
                        }
                    }
                } catch (MalformedCookieException e) {
                    LogsServer.instance().warn(
                            "Malformed cookie for cookie named " + entry.getKey() + ". " + e.getMessage());
                }
            }
        }
    }
}

From source file:org.vietspider.net.client.impl.AbstractHttpClient.java

private HttpHost determineTarget(HttpUriRequest request) {
    // A null target may be acceptable if there is a default target.
    // Otherwise, the null target is detected in the director.
    HttpHost target = null;/*  w ww . j  a  v a  2s. c  o m*/

    URI requestURI = request.getURI();
    if (requestURI.isAbsolute()) {
        target = new HttpHost(requestURI.getHost(), requestURI.getPort(), requestURI.getScheme());
    }
    return target;
}

From source file:org.obiba.opal.rest.client.magma.OpalJavaClient.java

public UriBuilder newUri(URI root) {
    String rootPath = root.getPath();
    if (!rootPath.endsWith("/")) {
        try {//from   www .j  a va 2 s  .  c om
            return new UriBuilder(new URI(root.getScheme(), root.getHost() + ":" + root.getPort(),
                    rootPath + "/", root.getQuery(), root.getFragment()));
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }
    return new UriBuilder(root);
}

From source file:edu.harvard.iq.dvn.api.datadeposit.UrlManager.java

void processUrl(String url) throws SwordError {
    logger.fine("URL was: " + url);
    this.originalUrl = url;
    URI javaNetUri;
    try {//from  w w  w . ja  va 2 s.  c  om
        javaNetUri = new URI(url);
    } catch (URISyntaxException ex) {
        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Invalid URL syntax: " + url);
    }
    if (!"https".equals(javaNetUri.getScheme())) {
        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST,
                "https is required but protocol was " + javaNetUri.getScheme());
    }
    this.port = javaNetUri.getPort();
    String[] urlPartsArray = javaNetUri.getPath().split("/");
    List<String> urlParts = Arrays.asList(urlPartsArray);
    String dataDepositApiBasePath;
    try {
        List<String> dataDepositApiBasePathParts;
        //             1 2   3   4            5  6       7          8         9
        // for example: /dvn/api/data-deposit/v1/swordv2/collection/dataverse/sword
        dataDepositApiBasePathParts = urlParts.subList(0, 6);
        dataDepositApiBasePath = StringUtils.join(dataDepositApiBasePathParts, "/");
    } catch (IndexOutOfBoundsException ex) {
        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Error processing URL: " + url);
    }
    if (!dataDepositApiBasePath.equals(swordConfiguration.getBaseUrlPath())) {
        throw new SwordError(
                dataDepositApiBasePath + " found but " + swordConfiguration.getBaseUrlPath() + " expected");
    }
    try {
        this.servlet = urlParts.get(6);
    } catch (ArrayIndexOutOfBoundsException ex) {
        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST,
                "Unable to determine servlet path from URL: " + url);
    }
    if (!servlet.equals("service-document")) {
        List<String> targetTypeAndIdentifier;
        try {
            //               6          7         8
            // for example: /collection/dataverse/sword
            targetTypeAndIdentifier = urlParts.subList(7, urlParts.size());
        } catch (IndexOutOfBoundsException ex) {
            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST,
                    "No target components specified in URL: " + url);
        }
        this.targetType = targetTypeAndIdentifier.get(0);
        if (targetType != null) {
            if (targetType.equals("dataverse")) {
                String dvAlias;
                try {
                    dvAlias = targetTypeAndIdentifier.get(1);
                } catch (IndexOutOfBoundsException ex) {
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST,
                            "No dataverse alias provided in URL: " + url);
                }
                this.targetIdentifier = dvAlias;
            } else if (targetType.equals("study")) {
                String globalId;
                try {
                    List<String> globalIdParts = targetTypeAndIdentifier.subList(1,
                            targetTypeAndIdentifier.size());
                    globalId = StringUtils.join(globalIdParts, "/");
                } catch (IndexOutOfBoundsException ex) {
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST,
                            "Invalid study global id provided in URL: " + url);
                }
                this.targetIdentifier = globalId;
            } else if (targetType.equals("file")) {
                String fileIdString;
                try {
                    // a user might reasonably pass in a filename as well [.get(2)] since
                    // we expose it in the statement of a study but we ignore it here
                    fileIdString = targetTypeAndIdentifier.get(1);
                } catch (IndexOutOfBoundsException ex) {
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "No file id provided in URL: " + url);
                }
                this.targetIdentifier = fileIdString;
            } else {
                throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "unsupported target type: " + targetType);
            }
        } else {
            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST,
                    "Unable to determine target type from URL: " + url);
        }
        logger.fine("target type: " + targetType);
        logger.fine("target identifier: " + targetIdentifier);
    }
}

From source file:com.okta.sdk.framework.ApiClient.java

/**
 * Constructor for the ApiClient.//w  w w .j a  va  2 s. c om
 *
 * Bootstraps an HTTPClient to make various requests to the Okta API.
 *
 * @param config {@link ApiClientConfiguration}
 */
public ApiClient(ApiClientConfiguration config) {
    Proxy proxy = ProxySelector.getDefault().select(URI.create(config.getBaseUrl())).iterator().next();
    HttpRoutePlanner routePlanner;
    if (Proxy.Type.HTTP.equals(proxy.type())) {
        URI proxyUri = URI.create(proxy.type() + "://" + proxy.address());
        HttpHost proxyHost = new HttpHost(proxyUri.getHost(), proxyUri.getPort(), proxyUri.getScheme());
        routePlanner = new DefaultProxyRoutePlanner(proxyHost);
    } else {
        routePlanner = new DefaultRoutePlanner(null);
    }
    StandardHttpRequestRetryHandler requestRetryHandler = new StandardHttpRequestRetryHandler(RETRY_COUNT,
            true);
    HttpClient client = HttpClientBuilder.create().setRetryHandler(requestRetryHandler)
            .setUserAgent("OktaSDKJava_v" + Utils.getSdkVersion()).disableCookieManagement()
            .setRoutePlanner(routePlanner).build();

    this.httpClient = client;
    this.baseUrl = config.getBaseUrl();
    this.apiVersion = config.getApiVersion();
    this.configuration = config;
    this.token = config.getApiToken();

    initMarshaller();
}