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:org.apache.pulsar.proxy.server.DirectProxyHandler.java

public DirectProxyHandler(ProxyService service, ProxyConnection proxyConnection, String targetBrokerUrl) {
    this.authentication = service.getClientAuthentication();
    this.inboundChannel = proxyConnection.ctx().channel();
    this.originalPrincipal = proxyConnection.clientAuthRole;
    this.clientAuthData = proxyConnection.clientAuthData;
    this.clientAuthMethod = proxyConnection.clientAuthMethod;
    ProxyConfiguration config = service.getConfiguration();

    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    // Tie the backend connection on the same thread to avoid context switches when passing data between the 2
    // connections
    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.group(inboundChannel.eventLoop()).channel(inboundChannel.getClass()).option(ChannelOption.AUTO_READ,
            false);//from   w w w. j a va  2s.  com
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            if (config.isTlsEnabledWithBroker()) {
                SslContext sslCtx;
                // Set client certificate if available
                AuthenticationDataProvider authData = authentication.getAuthData();
                if (authData.hasDataForTls()) {
                    sslCtx = SecurityUtility.createNettySslContextForClient(
                            config.isTlsAllowInsecureConnection(), config.getBrokerClientTrustCertsFilePath(),
                            (X509Certificate[]) authData.getTlsCertificates(), authData.getTlsPrivateKey());
                } else {
                    sslCtx = SecurityUtility.createNettySslContextForClient(
                            config.isTlsAllowInsecureConnection(), config.getBrokerClientTrustCertsFilePath());
                }
                ch.pipeline().addLast(TLS_HANDLER, sslCtx.newHandler(ch.alloc()));
            }
            ch.pipeline().addLast("frameDecoder",
                    new LengthFieldBasedFrameDecoder(PulsarDecoder.MaxFrameSize, 0, 4, 0, 4));
            ch.pipeline().addLast("proxyOutboundHandler", new ProxyBackendHandler(config));
        }
    });

    URI targetBroker;
    try {
        // targetBrokerUrl is coming in the "hostname:6650" form, so we need to extract host and port
        targetBroker = new URI("pulsar://" + targetBrokerUrl);
    } catch (URISyntaxException e) {
        log.warn("[{}] Failed to parse broker url '{}'", inboundChannel, targetBrokerUrl, e);
        inboundChannel.close();
        return;
    }

    ChannelFuture f = b.connect(targetBroker.getHost(), targetBroker.getPort());
    outboundChannel = f.channel();
    f.addListener(future -> {
        if (!future.isSuccess()) {
            // Close the connection if the connection attempt has failed.
            inboundChannel.close();
            return;
        }
        final ProxyBackendHandler cnx = (ProxyBackendHandler) outboundChannel.pipeline()
                .get("proxyOutboundHandler");
        cnx.setRemoteHostName(targetBroker.getHost());
    });
}

From source file:at.bitfire.davdroid.mirakel.webdav.WebDavResource.java

public WebDavResource(CloseableHttpClient httpClient, URI baseURL, String username, String password,
        boolean preemptive) throws URISyntaxException {
    this(httpClient, baseURL);

    HttpHost host = new HttpHost(baseURL.getHost(), baseURL.getPort(), baseURL.getScheme());
    context.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(username, password));

    if (preemptive) {
        Log.d(TAG, "Using preemptive authentication (not compatible with Digest auth)");
        AuthCache authCache = context.getAuthCache();
        if (authCache == null)
            authCache = new BasicAuthCache();
        authCache.put(host, new BasicScheme());
        context.setAuthCache(authCache);
    }/*w ww  .  ja va 2 s.  co  m*/
}

From source file:com.netscape.cmstools.client.ClientCertImportCLI.java

public void execute(String[] args) throws Exception {
    // Always check for "--help" prior to parsing
    if (Arrays.asList(args).contains("--help")) {
        printHelp();/*from w w  w  .  jav a 2 s  .  c om*/
        return;
    }

    CommandLine cmd = parser.parse(options, args);

    String[] cmdArgs = cmd.getArgs();

    if (cmdArgs.length > 1) {
        throw new Exception("Too many arguments specified.");
    }

    MainCLI mainCLI = (MainCLI) parent.getParent();

    String nickname = null;

    // Get nickname from command argument if specified.
    if (cmdArgs.length > 0) {
        nickname = cmdArgs[0];
    }

    // Otherwise, get nickname from authentication option -n.
    // This code is used to provide backward compatibility.
    // TODO: deprecate/remove this code in 10.3.
    if (nickname == null) {
        nickname = mainCLI.config.getCertNickname();
    }

    // nickname is not required to import PKCS #12 file

    String certPath = cmd.getOptionValue("cert");
    String caCertPath = cmd.getOptionValue("ca-cert");
    String pkcs7Path = cmd.getOptionValue("pkcs7");
    String pkcs12Path = cmd.getOptionValue("pkcs12");
    String pkcs12Password = cmd.getOptionValue("pkcs12-password");
    String pkcs12PasswordPath = cmd.getOptionValue("pkcs12-password-file");
    boolean importFromCAServer = cmd.hasOption("ca-server");
    String serialNumber = cmd.getOptionValue("serial");
    String trustAttributes = cmd.getOptionValue("trust");

    File nssdbPasswordFile = null;

    if (mainCLI.config.getNSSPassword() != null) {

        // store NSS database password in a temporary file

        nssdbPasswordFile = File.createTempFile("pki-client-cert-import-", ".nssdb-pwd");
        nssdbPasswordFile.deleteOnExit();

        try (PrintWriter out = new PrintWriter(new FileWriter(nssdbPasswordFile))) {
            out.print(mainCLI.config.getNSSPassword());
        }
    }

    // load the certificate
    if (certPath != null) {

        if (verbose)
            System.out.println("Importing certificate from " + certPath + ".");

        if (trustAttributes == null)
            trustAttributes = "u,u,u";

        importCert(mainCLI.certDatabase, nssdbPasswordFile, certPath, nickname, trustAttributes);

    } else if (caCertPath != null) {

        if (verbose)
            System.out.println("Importing CA certificate from " + caCertPath + ".");

        // initialize JSS
        mainCLI.init();

        if (trustAttributes == null)
            trustAttributes = "CT,C,C";

        importCACert(mainCLI.certDatabase, nssdbPasswordFile, caCertPath, nickname, trustAttributes);

    } else if (pkcs7Path != null) {

        if (verbose)
            System.out.println("Importing certificates from " + pkcs7Path + ".");

        // initialize JSS
        mainCLI.init();

        importPKCS7(pkcs7Path, nickname, trustAttributes);

    } else if (pkcs12Path != null) {

        if (verbose)
            System.out.println("Importing certificates from " + pkcs12Path + ".");

        if (pkcs12Password != null && pkcs12PasswordPath != null) {
            throw new Exception("PKCS #12 password and password file are mutually exclusive");

        } else if (pkcs12Password != null) {
            // store password into a temporary file
            File pkcs12PasswordFile = File.createTempFile("pki-client-cert-import-", ".pkcs12-pwd");
            pkcs12PasswordFile.deleteOnExit();

            try (PrintWriter out = new PrintWriter(new FileWriter(pkcs12PasswordFile))) {
                out.print(pkcs12Password);
            }

            pkcs12PasswordPath = pkcs12PasswordFile.getAbsolutePath();

        } else if (pkcs12PasswordPath != null) {
            // nothing to do

        } else {
            throw new Exception("Missing PKCS #12 password");
        }

        // import certificates and private key into PKCS #12 file
        importPKCS12(mainCLI.certDatabase, nssdbPasswordFile, pkcs12Path, pkcs12PasswordPath);

    } else if (importFromCAServer) {

        // late initialization
        mainCLI.init();

        PKIClient client = getClient();
        URI serverURI = mainCLI.config.getServerURL().toURI();

        String caServerURI = serverURI.getScheme() + "://" + serverURI.getHost() + ":" + serverURI.getPort()
                + "/ca";

        if (verbose)
            System.out.println("Importing CA certificate from " + caServerURI + ".");
        byte[] bytes = client.downloadCACertChain(caServerURI);

        File certFile = File.createTempFile("pki-client-cert-import-", ".crt");
        certFile.deleteOnExit();

        try (FileOutputStream out = new FileOutputStream(certFile)) {
            out.write(bytes);
        }

        if (trustAttributes == null)
            trustAttributes = "CT,C,C";

        importCert(mainCLI.certDatabase, nssdbPasswordFile, certFile.getAbsolutePath(), nickname,
                trustAttributes);

    } else if (serialNumber != null) {

        // connect to CA anonymously
        ClientConfig config = new ClientConfig(mainCLI.config);
        config.setNSSDatabase(null);
        config.setNSSPassword(null);
        config.setCertNickname(null);

        URL serverURL = config.getServerURL();
        if (verbose)
            System.out.println("Importing certificate " + serialNumber + " from " + serverURL + ".");

        PKIClient client = new PKIClient(config, null);
        CAClient caClient = new CAClient(client);
        CACertClient certClient = new CACertClient(caClient);

        CertData certData = certClient.getCert(new CertId(serialNumber));

        File certFile = File.createTempFile("pki-client-cert-import-", ".crt");
        certFile.deleteOnExit();

        String encoded = certData.getEncoded();
        try (PrintWriter out = new PrintWriter(new FileWriter(certFile))) {
            out.write(encoded);
        }

        if (trustAttributes == null)
            trustAttributes = "u,u,u";

        importCert(mainCLI.certDatabase, nssdbPasswordFile, certFile.getAbsolutePath(), nickname,
                trustAttributes);

    } else {
        throw new Exception("Missing certificate to import");
    }
}

From source file:org.zalando.stups.tokens.CloseableTokenVerifier.java

public CloseableTokenVerifier(URI tokenInfoUri, HttpConfig httpConfig, MetricsListener metricsListener) {
    this.tokenInfoUri = tokenInfoUri;
    this.metricsListener = metricsListener;

    requestConfig = RequestConfig.custom().setSocketTimeout(httpConfig.getSocketTimeout())
            .setConnectTimeout(httpConfig.getConnectTimeout())
            .setConnectionRequestTimeout(httpConfig.getConnectionRequestTimeout())
            .setStaleConnectionCheckEnabled(httpConfig.isStaleConnectionCheckEnabled()).build();

    client = HttpClients.custom().setUserAgent(new UserAgent().get()).useSystemProperties().build();

    host = new HttpHost(tokenInfoUri.getHost(), tokenInfoUri.getPort(), tokenInfoUri.getScheme());
}

From source file:org.lightcouch.CouchDbClient.java

public String getDBUserObject(String username, String password) {
    HttpResponse response = null;//from ww w.j  a  v a 2s.  c o  m
    String responseString = null;

    try {
        URI uri = getDBUri();
        URI furi = URI.create(uri.getScheme() + "://" + username + ":" + password + "@" + uri.getHost() + ":"
                + uri.getPort());
        HttpGet get = new HttpGet(builder(furi).path("/_users/org.couchdb.user:" + username).build());
        //         HttpEntity body = new ByteArrayEntity(string.getBytes("UTF-8"));
        //
        //         post.setEntity(body);
        get.setHeader("Content-Type", "application/json");

        response = executeRequest(get);
        HttpEntity entity = response.getEntity();
        responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        close(response);
    }
    return responseString;
}

From source file:com.gopivotal.manager.redis.RedisStore.java

/**
 * Sets the connection URI/*from  w ww.ja va 2s .  c  o  m*/
 *
 * @param uri the connection URI
 */
public void setUri(final String uri) {
    this.lockTemplate.withWriteLock(new LockTemplate.LockedOperation<Void>() {

        @Override
        public Void invoke() {
            URI richUri = URI.create(uri);
            setHost(richUri.getHost());
            setPort(richUri.getPort());
            setPassword(parsePassword(richUri));
            setDatabase(parseDatabase(richUri));
            return null;
        }

    });
}

From source file:com.spotify.helios.client.DefaultRequestDispatcher.java

/**
 * Sets up a connection, retrying on connect failure.
 *//*from   ww w  . ja  va2  s.  c  o m*/
private HttpURLConnection connect(final URI uri, final String method, final byte[] entity,
        final Map<String, List<String>> headers)
        throws URISyntaxException, IOException, TimeoutException, InterruptedException, HeliosException {
    final long deadline = currentTimeMillis() + RETRY_TIMEOUT_MILLIS;
    final int offset = ThreadLocalRandom.current().nextInt();

    while (currentTimeMillis() < deadline) {
        final List<URI> endpoints = endpointSupplier.get();
        if (endpoints.isEmpty()) {
            throw new RuntimeException("failed to resolve master");
        }
        log.debug("endpoint uris are {}", endpoints);

        // Resolve hostname into IPs so client will round-robin and retry for multiple A records.
        // Keep a mapping of IPs to hostnames for TLS verification.
        final List<URI> ipEndpoints = Lists.newArrayList();
        final Map<URI, URI> ipToHostnameUris = Maps.newHashMap();

        for (final URI hnUri : endpoints) {
            try {
                final InetAddress[] ips = InetAddress.getAllByName(hnUri.getHost());
                for (final InetAddress ip : ips) {
                    final URI ipUri = new URI(hnUri.getScheme(), hnUri.getUserInfo(), ip.getHostAddress(),
                            hnUri.getPort(), hnUri.getPath(), hnUri.getQuery(), hnUri.getFragment());
                    ipEndpoints.add(ipUri);
                    ipToHostnameUris.put(ipUri, hnUri);
                }
            } catch (UnknownHostException e) {
                log.warn("Unable to resolve hostname {} into IP address: {}", hnUri.getHost(), e);
            }
        }

        for (int i = 0; i < ipEndpoints.size() && currentTimeMillis() < deadline; i++) {
            final URI ipEndpoint = ipEndpoints.get(positive(offset + i) % ipEndpoints.size());
            final String fullpath = ipEndpoint.getPath() + uri.getPath();

            final String scheme = ipEndpoint.getScheme();
            final String host = ipEndpoint.getHost();
            final int port = ipEndpoint.getPort();
            if (!VALID_PROTOCOLS.contains(scheme) || host == null || port == -1) {
                throw new HeliosException(String.format(
                        "Master endpoints must be of the form \"%s://heliosmaster.domain.net:<port>\"",
                        VALID_PROTOCOLS_STR));
            }

            final URI realUri = new URI(scheme, host + ":" + port, fullpath, uri.getQuery(), null);

            AgentProxy agentProxy = null;
            Deque<Identity> identities = Queues.newArrayDeque();
            try {
                if (scheme.equals("https")) {
                    agentProxy = AgentProxies.newInstance();
                    for (final Identity identity : agentProxy.list()) {
                        if (identity.getPublicKey().getAlgorithm().equals("RSA")) {
                            // only RSA keys will work with our TLS implementation
                            identities.offerLast(identity);
                        }
                    }
                }
            } catch (Exception e) {
                log.warn("Couldn't get identities from ssh-agent", e);
            }

            try {
                do {
                    final Identity identity = identities.poll();

                    try {
                        log.debug("connecting to {}", realUri);

                        final HttpURLConnection connection = connect0(realUri, method, entity, headers,
                                ipToHostnameUris.get(ipEndpoint).getHost(), agentProxy, identity);

                        final int responseCode = connection.getResponseCode();
                        if (((responseCode == HTTP_FORBIDDEN) || (responseCode == HTTP_UNAUTHORIZED))
                                && !identities.isEmpty()) {
                            // there was some sort of security error. if we have any more SSH identities to try,
                            // retry with the next available identity
                            log.debug("retrying with next SSH identity since {} failed", identity.getComment());
                            continue;
                        }

                        return connection;
                    } catch (ConnectException | SocketTimeoutException | UnknownHostException e) {
                        // UnknownHostException happens if we can't resolve hostname into IP address.
                        // UnknownHostException's getMessage method returns just the hostname which is a
                        // useless message, so log the exception class name to provide more info.
                        log.debug(e.toString());
                        // Connecting failed, sleep a bit to avoid hammering and then try another endpoint
                        Thread.sleep(200);
                    }
                } while (false);
            } finally {
                if (agentProxy != null) {
                    agentProxy.close();
                }
            }
        }
        log.warn("Failed to connect, retrying in 5 seconds.");
        Thread.sleep(5000);
    }
    throw new TimeoutException("Timed out connecting to master");
}

From source file:de.thingweb.thing.Thing.java

public String resolveActionUri(String name, int index) {

    URI uri = getUri(index);

    Action a = getAction(name);/*from   www.  j  a  v a 2  s  .  c om*/

    if (a != null) {
        try {
            String path = uri.getPath();
            if (path.endsWith("/")) {
                path = path + a.getHrefs().get(index);
            } else {
                path = path + "/" + a.getHrefs().get(index);
            }
            uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), path,
                    uri.getQuery(), uri.getFragment());
        } catch (URISyntaxException e) {
            throw new RuntimeException("TD with malformed hrefs");
        }
    } else {
        throw new RuntimeException("No such Property");
    }

    return uri.toString();
}

From source file:com.jayway.restassured.internal.http.AuthConfig.java

/**
 * Sets a certificate to be used for SSL authentication. See {@link Class#getResource(String)} for how to get a URL from a resource
 * on the classpath.//from  w w w. j  a v  a2  s .c o m
 *
 * @param certURL              URL to a JKS keystore where the certificate is stored.
 * @param password             password to decrypt the keystore
 * @param certType             The certificate type
 * @param port                 The SSL port
 * @param trustStore           The trust store
 * @param x509HostnameVerifier The X509HostnameVerifier to use
 * @param sslSocketFactory     The SSLSocketFactory to use
 */
public void certificate(String certURL, String password, String certType, int port, KeyStore trustStore,
        X509HostnameVerifier x509HostnameVerifier, SSLSocketFactory sslSocketFactory) {
    KeystoreSpecImpl keystoreSpec = new KeystoreSpecImpl();
    URI uri = ((URIBuilder) builder.getUri()).toURI();
    if (uri == null)
        throw new IllegalStateException("a default URI must be set");
    keystoreSpec.setKeyStoreType(certType);
    keystoreSpec.setPassword(password);
    keystoreSpec.setPath(certURL);
    keystoreSpec.setTrustStore(trustStore);
    keystoreSpec.setPort(port);
    keystoreSpec.setX509HostnameVerifier(x509HostnameVerifier);
    keystoreSpec.setFactory(sslSocketFactory);
    int portSpecifiedInUri = uri.getPort();
    keystoreSpec.apply(builder, portSpecifiedInUri == UNDEFINED_PORT ? DEFAULT_HTTPS_PORT : portSpecifiedInUri);
}

From source file:org.apache.abdera2.common.protocol.Session.java

public void usePreemptiveAuthentication(String target, String realm) throws URISyntaxException {
    AuthCache cache = (AuthCache) localContext.getAttribute(ClientContext.AUTH_CACHE);
    if (cache == null) {
        String host = AuthScope.ANY_HOST;
        int port = AuthScope.ANY_PORT;
        if (target != null) {
            URI uri = new URI(target);
            host = uri.getHost();/*from ww w .ja  va2  s  .  com*/
            port = uri.getPort();
        }
        BasicScheme basicAuth = new BasicScheme();
        HttpHost targetHost = new HttpHost(host, port, basicAuth.getSchemeName());
        cache = new BasicAuthCache();
        cache.put(targetHost, basicAuth);
        localContext.setAttribute(ClientContext.AUTH_CACHE, cache);
    }
}