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.springframework.cloud.dataflow.shell.command.support.HttpClientUtils.java

/**
 * Ensures that the passed-in {@link RestTemplate} is using the Apache HTTP Client. If the optional {@code username} AND
 * {@code password} are not empty, then a {@link BasicCredentialsProvider} will be added to the {@link CloseableHttpClient}.
 *
 * Furthermore, you can set the underlying {@link SSLContext} of the {@link HttpClient} allowing you to accept self-signed
 * certificates./*from   ww w .  j a  v a 2  s .  co m*/
 *
 * @param restTemplate Must not be null
 * @param username Can be null
 * @param password Can be null
 * @param skipSslValidation Use with caution! If true certificate warnings will be ignored.
 */
public static void prepareRestTemplate(RestTemplate restTemplate, URI host, String username, String password,
        boolean skipSslValidation) {

    Assert.notNull(restTemplate, "The provided RestTemplate must not be null.");

    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
        final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }

    if (skipSslValidation) {
        httpClientBuilder.setSSLContext(HttpClientUtils.buildCertificateIgnoringSslContext());
        httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }

    final CloseableHttpClient httpClient = httpClientBuilder.build();
    final HttpHost targetHost = new HttpHost(host.getHost(), host.getPort(), host.getScheme());

    final HttpComponentsClientHttpRequestFactory requestFactory = new PreemptiveBasicAuthHttpComponentsClientHttpRequestFactory(
            httpClient, targetHost);
    restTemplate.setRequestFactory(requestFactory);
}

From source file:com.ctriposs.r2.message.rest.QueryTunnelUtil.java

/**
 * @param request   a RestRequest object to be encoded as a tunneled POST
 * @param threshold the size of the query params above which the request will be encoded
 *
 * @return an encoded RestRequest/*  w ww. ja v a  2 s  .com*/
 */
public static RestRequest encode(final RestRequest request, int threshold)
        throws URISyntaxException, MessagingException, IOException {
    URI uri = request.getURI();

    // Check to see if we should tunnel this request by testing the length of the query
    // if the query is NULL, we won't bother to encode.
    // 0 length is a special case that could occur with a url like http://www.foo.com?
    // which we don't want to encode, because we'll lose the "?" in the process
    // Otherwise only encode queries whose length is greater than or equal to the
    // threshold value.

    String query = uri.getRawQuery();

    if (query == null || query.length() == 0 || query.length() < threshold) {
        return request;
    }

    RestRequestBuilder requestBuilder = new RestRequestBuilder(request);

    // reconstruct URI without query
    uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), null,
            uri.getFragment());

    // If there's no existing body, just pass the request as x-www-form-urlencoded
    ByteString entity = request.getEntity();
    if (entity == null || entity.length() == 0) {
        requestBuilder.setHeader(HEADER_CONTENT_TYPE, FORM_URL_ENCODED);
        requestBuilder.setEntity(ByteString.copyString(query, Data.UTF_8_CHARSET));
    } else {
        // If we have a body, we must preserve it, so use multipart/mixed encoding

        MimeMultipart multi = createMultiPartEntity(entity, request.getHeader(HEADER_CONTENT_TYPE), query);
        requestBuilder.setHeader(HEADER_CONTENT_TYPE, multi.getContentType());
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        multi.writeTo(os);
        requestBuilder.setEntity(ByteString.copy(os.toByteArray()));
    }

    // Set the base uri, supply the original method in the override header, and change method to POST
    requestBuilder.setURI(uri);
    requestBuilder.setHeader(HEADER_METHOD_OVERRIDE, requestBuilder.getMethod());
    requestBuilder.setMethod(RestMethod.POST);

    return requestBuilder.build();
}

From source file:net.ripe.rpki.validator.util.UriToFileMapper.java

private String getHostPortAsString(URI uri) {
    String host = uri.getHost();//from   w ww  .j a v  a  2  s  . c o  m
    int port = uri.getPort();
    return port == -1 ? host : (host + ":" + port);
}

From source file:TestFuseDFS.java

/**
 * Run a fuse-dfs process to mount the given DFS
 *///  ww w  .j  av  a2s.c o  m
private static Process establishMount(URI uri) throws IOException {
    Runtime r = Runtime.getRuntime();
    String cp = System.getProperty("java.class.path");

    String buildTestDir = System.getProperty("build.test");
    String fuseCmd = buildTestDir + "/../fuse_dfs";
    String libHdfs = buildTestDir + "/../../../c++/lib";

    String arch = System.getProperty("os.arch");
    String jvm = System.getProperty("java.home") + "/lib/" + arch + "/server";
    String lp = System.getProperty("LD_LIBRARY_PATH") + ":" + libHdfs + ":" + jvm;
    LOG.debug("LD_LIBRARY_PATH=" + lp);

    String nameNode = "dfs://" + uri.getHost() + ":" + String.valueOf(uri.getPort());

    // NB: We're mounting via an unprivileged user, therefore
    // user_allow_other needs to be set in /etc/fuse.conf, which also
    // needs to be world readable.
    String mountCmd[] = { fuseCmd, nameNode, mountPoint,
            // "-odebug",              // Don't daemonize
            "-obig_writes", // Allow >4kb writes
            "-oentry_timeout=0.1", // Don't cache dents long
            "-oattribute_timeout=0.1", // Don't cache attributes long
            "-ononempty", // Don't complain about junk in mount point
            "-f", // Don't background the process
            "-ordbuffer=32768", // Read buffer size in kb
            "rw" };

    String[] env = { "CLASSPATH=" + cp, "LD_LIBRARY_PATH=" + lp, "PATH=/usr/bin:/bin" };

    execWaitRet("fusermount -u " + mountPoint);
    execAssertSucceeds("rm -rf " + mountPoint);
    execAssertSucceeds("mkdir -p " + mountPoint);

    // Mount the mini cluster
    String cmdStr = "";
    for (String c : mountCmd) {
        cmdStr += (" " + c);
    }
    LOG.info("now mounting with:" + cmdStr);
    Process fuseProcess = r.exec(mountCmd, env);
    RedirectToStdoutThread stdoutThread = new RedirectToStdoutThread(fuseProcess.getInputStream());
    RedirectToStdoutThread stderrThread = new RedirectToStdoutThread(fuseProcess.getErrorStream());
    stdoutThread.start();
    stderrThread.start();
    // Wait for fusermount to start up, so that we know we're operating on the
    // FUSE FS when we run the tests.
    try {
        Thread.sleep(50000);
    } catch (InterruptedException e) {
    }
    return fuseProcess;
}

From source file:fedora.server.utilities.ServerUtility.java

/**
 * Tell whether the given URL appears to be referring to somewhere within
 * the Fedora webapp.//w  ww.  j  av a  2s .  co m
 */
public static boolean isURLFedoraServer(String url) {

    // scheme must be http or https
    URI uri = URI.create(url);
    String scheme = uri.getScheme();
    if (!scheme.equals("http") && !scheme.equals("https")) {
        return false;
    }

    // host must be configured hostname or localhost
    String fHost = CONFIG.getParameter(FEDORA_SERVER_HOST).getValue();
    String host = uri.getHost();
    if (!host.equals(fHost) && !host.equals("localhost")) {
        return false;
    }

    // path must begin with configured webapp context
    String path = uri.getPath();
    String fedoraContext = CONFIG.getParameter(FEDORA_SERVER_CONTEXT).getValue();
    if (!path.startsWith("/" + fedoraContext + "/")) {
        return false;
    }

    // port specification must match http or https port as appropriate
    String httpPort = CONFIG.getParameter(FEDORA_SERVER_PORT).getValue();
    String httpsPort = CONFIG.getParameter(FEDORA_REDIRECT_PORT).getValue();
    if (uri.getPort() == -1) {
        // unspecified, so fedoraPort must be 80 (http), or 443 (https)
        if (scheme.equals("http")) {
            return httpPort.equals("80");
        } else {
            return httpsPort.equals("443");
        }
    } else {
        // specified, so must match appropriate http or https port
        String port = "" + uri.getPort();
        if (scheme.equals("http")) {
            return port.equals(httpPort);
        } else {
            return port.equals(httpsPort);
        }
    }

}

From source file:org.apache.servicecomb.it.ITBootListener.java

protected void selectPort(String cfgKey) {
    String endpoint = DynamicPropertyFactory.getInstance().getStringProperty(cfgKey, null).get();
    if (endpoint == null) {
        return;//from  w  w w.  j av a 2s  .c o m
    }

    URI uri = URI.create("http://" + endpoint);
    if (uri.getPort() == 0) {
        int port = getRandomPort();
        try {
            ConcurrentCompositeConfiguration config = (ConcurrentCompositeConfiguration) DynamicPropertyFactory
                    .getBackingConfigurationSource();
            endpoint = new URIBuilder("http://" + endpoint).setPort(port).build().toString().substring(7);
            config.getConfiguration(0).setProperty(cfgKey, endpoint);
            LOGGER.info("change {} to {}.", cfgKey, endpoint);
        } catch (URISyntaxException e) {
            throw new IllegalStateException("Failed to build endpoint.", e);
        }
    }
}

From source file:com.orange.ngsi.ProtocolRegistry.java

private String getHost(String url) throws URISyntaxException {
    URI uri = new URI(url);
    return uri.getHost() + ":" + uri.getPort();
}

From source file:Main.java

/**
 * Parse the URI and use the details to connect to the IMAP(S) server and login.
 *
 * @param uri the URI to use, e.g. imaps://user:pass@imap.mail.yahoo.com/folder
 * or imaps://user:pass@imap.googlemail.com/folder
 * @param defaultTimeout initial timeout (in milliseconds)
 * @param listener for tracing protocol IO (may be null)
 * @return the IMAP client - connected and logged in
 * @throws IOException if any problems occur
 *//*ww  w .j a  v  a2  s  .  c om*/
static IMAPClient imapLogin(URI uri, int defaultTimeout, ProtocolCommandListener listener) throws IOException {
    final String userInfo = uri.getUserInfo();
    if (userInfo == null) {
        throw new IllegalArgumentException("Missing userInfo details");
    }

    String[] userpass = userInfo.split(":");
    if (userpass.length != 2) {
        throw new IllegalArgumentException("Invalid userInfo details: '" + userpass + "'");
    }

    String username = userpass[0];
    String password = userpass[1]; // TODO enable reading this secretly

    final IMAPClient imap;

    final String scheme = uri.getScheme();
    if ("imaps".equalsIgnoreCase(scheme)) {
        System.out.println("Using secure protocol");
        imap = new IMAPSClient(true); // implicit
    } else if ("imap".equalsIgnoreCase(scheme)) {
        imap = new IMAPClient();
    } else {
        throw new IllegalArgumentException("Invalid protocol: " + scheme);
    }
    final int port = uri.getPort();
    if (port != -1) {
        imap.setDefaultPort(port);
    }

    imap.setDefaultTimeout(defaultTimeout);

    if (listener != null) {
        imap.addProtocolCommandListener(listener);
    }

    final String server = uri.getHost();
    System.out.println("Connecting to server " + server + " on " + imap.getDefaultPort());

    try {
        imap.connect(server);
        System.out.println("Successfully connected");
    } catch (IOException e) {
        throw new RuntimeException("Could not connect to server.", e);
    }

    if (!imap.login(username, password)) {
        imap.disconnect();
        throw new RuntimeException("Could not login to server. Check login details.");
    }

    return imap;
}

From source file:com.orange.cloud.servicebroker.filter.securitygroups.domain.Destination.java

private boolean noPort(URI uri) {
    return uri.getPort() == -1;
}

From source file:org.jets3t.service.utils.SignatureUtils.java

/**
 * Replace the hostname of the given URI endpoint to match the given region.
 *
 * @param uri//from ww  w  . j ava 2 s .  c o m
 * @param region
 *
 * @return
 * URI with hostname that may or may not have been changed to be appropriate
 * for the given region. For example, the hostname "s3.amazonaws.com" is
 * unchanged for the "us-east-1" region but for the "eu-central-1" region
 * becomes "s3-eu-central-1.amazonaws.com".
 */
public static URI awsV4CorrectHostnameForRegion(URI uri, String region) {
    String[] hostSplit = uri.getHost().split("\\.");
    if (region.equals("us-east-1")) {
        hostSplit[hostSplit.length - 3] = "s3";
    } else {
        hostSplit[hostSplit.length - 3] = "s3-" + region;
    }
    String newHost = ServiceUtils.join(hostSplit, ".");
    try {
        String rawPathAndQuery = uri.getRawPath();
        if (uri.getRawQuery() != null) {
            rawPathAndQuery += "?" + uri.getRawQuery();
        }
        return new URL(uri.getScheme(), newHost, uri.getPort(), rawPathAndQuery).toURI();
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}