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.qwazr.utils.json.client.JsonClientAbstract.java

protected JsonClientAbstract(String url, Integer msTimeOut, Credentials credentials) throws URISyntaxException {
    this.url = url;
    URI u = new URI(url);
    String path = u.getPath();/*from   ww  w  .j ava2 s  .  c  o  m*/
    if (path != null && path.endsWith("/"))
        u = new URI(u.getScheme(), null, u.getHost(), u.getPort(), path.substring(0, path.length() - 1),
                u.getQuery(), u.getFragment());
    this.scheme = u.getScheme() == null ? "http" : u.getScheme();
    this.host = u.getHost();
    this.fragment = u.getFragment();
    this.path = u.getPath();
    this.port = u.getPort() == -1 ? 80 : u.getPort();
    this.timeout = msTimeOut == null ? DEFAULT_TIMEOUT : msTimeOut;
    this.executor = credentials == null ? Executor.newInstance() : Executor.newInstance().auth(credentials);

}

From source file:com.brightcove.zartan.common.helper.MediaAPIHelper.java

/**
 * Executes a file upload write api call against the given URI. This is useful for create_video
 * and add_image/*w  w  w. java  2  s. co  m*/
 * 
 * @param json the json representation of the call you are making
 * @param file the file you are uploading
 * @param uri the api servlet you want to execute against
 * @return json response from api
 * @throws BadEnvironmentException
 * @throws MediaAPIException
 */
public JsonNode executeWrite(JsonNode json, File file, URI uri)
        throws BadEnvironmentException, MediaAPIException {

    mLog.debug("using " + uri.getHost() + " on port " + uri.getPort() + " for api write");

    HttpPost method = new HttpPost(uri);
    MultipartEntity entityIn = new MultipartEntity();
    FileBody fileBody = null;

    if (file != null) {
        fileBody = new FileBody(file);
    }

    try {
        entityIn.addPart("JSON-RPC", new StringBody(json.toString(), Charset.forName("UTF-8")));
    } catch (UnsupportedEncodingException e) {
        throw new BadEnvironmentException("UTF-8 no longer supported");
    }

    if (file != null) {
        entityIn.addPart(file.getName(), fileBody);
    }
    method.setEntity(entityIn);

    return executeCall(method);
}

From source file:com.amazon.s3.http.HttpRequestFactory.java

/** Configures the headers in the specified Apache HTTP request. */
private void configureHeaders(HttpRequestBase httpRequest, Request<?> request, ExecutionContext context,
        ClientConfiguration clientConfiguration) {
    /*/*from  w w  w. j ava2  s .  co  m*/
     * Apache HttpClient omits the port number in the Host header (even if
     * we explicitly specify it) if it's the default port for the protocol
     * in use. To ensure that we use the same Host header in the request and
     * in the calculated string to sign (even if Apache HttpClient changed
     * and started honoring our explicit host with endpoint), we follow this
     * same behavior here and in the QueryString signer.
     */
    URI endpoint = request.getEndpoint();
    String hostHeader = endpoint.getHost();
    if (HttpUtils.isUsingNonDefaultPort(endpoint)) {
        hostHeader += ":" + endpoint.getPort();
    }
    httpRequest.addHeader("Host", hostHeader);

    // Copy over any other headers already in our request
    for (Entry<String, String> entry : request.getHeaders().entrySet()) {
        /*
         * HttpClient4 fills in the Content-Length header and complains if
         * it's already present, so we skip it here. We also skip the Host
         * header to avoid sending it twice, which will interfere with some
         * signing schemes.
         */
        if (entry.getKey().equalsIgnoreCase("Content-Length") || entry.getKey().equalsIgnoreCase("Host"))
            continue;

        httpRequest.addHeader(entry.getKey(), entry.getValue());
    }

    /* Set content type and encoding */
    if (httpRequest.getHeaders("Content-Type") == null || httpRequest.getHeaders("Content-Type").length == 0) {
        httpRequest.addHeader("Content-Type",
                "application/x-www-form-urlencoded; " + "charset=" + DEFAULT_ENCODING.toLowerCase());
    }

    // Override the user agent string specified in the client params if the
    // context requires it
    if (context != null && context.getContextUserAgent() != null) {
        httpRequest.addHeader("User-Agent",
                createUserAgentString(clientConfiguration, context.getContextUserAgent()));
    }
}

From source file:org.bedework.synch.cnctrs.orgSyncV2.OrgSyncV2ConnectorInstance.java

@Override
public URI getUri() throws SynchException {
    try {/*w  ww . j  a  v a2  s.com*/
        //Get yesterdays date
        final LocalDate yesterday = LocalDate.now().minus(1, ChronoUnit.DAYS);
        final String yesterdayStr = yesterday.format(DateTimeFormatter.ISO_LOCAL_DATE);

        final URI infoUri = new URI(info.getUri());
        return new URIBuilder().setScheme(infoUri.getScheme()).setHost(infoUri.getHost())
                .setPort(infoUri.getPort()).setPath(infoUri.getPath())
                .setParameter("key", cnctr.getSyncher().decrypt(info.getPassword()))
                .setParameter("start_date", yesterdayStr).build();
    } catch (final SynchException se) {
        throw se;
    } catch (final Throwable t) {
        throw new SynchException(t);
    }
}

From source file:io.wcm.maven.plugins.contentpackage.AbstractContentPackageMojo.java

/**
 * Set up http client with credentials//from   w ww  .  j  a va2  s  .co  m
 * @return Http client
 * @throws MojoExecutionException Mojo execution exception
 */
protected final CloseableHttpClient getHttpClient() throws MojoExecutionException {
    try {
        URI crxUri = new URI(getCrxPackageManagerUrl());

        final AuthScope authScope = new AuthScope(crxUri.getHost(), crxUri.getPort());
        final Credentials credentials = new UsernamePasswordCredentials(this.userId, this.password);
        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(authScope, credentials);

        HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
                .addInterceptorFirst(new HttpRequestInterceptor() {
                    @Override
                    public void process(HttpRequest request, HttpContext context)
                            throws HttpException, IOException {
                        // enable preemptive authentication
                        AuthState authState = (AuthState) context
                                .getAttribute(HttpClientContext.TARGET_AUTH_STATE);
                        authState.update(new BasicScheme(), credentials);
                    }
                });

        if (this.relaxedSSLCheck) {
            SSLContext sslContext = new SSLContextBuilder()
                    .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    new NoopHostnameVerifier());
            httpClientBuilder.setSSLSocketFactory(sslsf);
        }

        return httpClientBuilder.build();
    } catch (URISyntaxException ex) {
        throw new MojoExecutionException("Invalid url: " + getCrxPackageManagerUrl(), ex);
    } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException ex) {
        throw new MojoExecutionException("Could not set relaxedSSLCheck", ex);
    }
}

From source file:net.bluemix.connectors.core.info.IBMObjectStorageServiceInfo.java

public IBMObjectStorageServiceInfo(final String id, final String url) throws URISyntaxException {
    super(id);// w  w  w. java  2 s  .  c om
    final String modUrl = url.replaceFirst(IBMObjectStorageServiceInfo.SCHEME, "https");
    final URI uri = new URI(modUrl);
    this.authUrl = uri.getScheme() + "://" + uri.getHost();
    if (uri.getPort() > 0) {
        this.authUrl = authUrl + ":" + uri.getPort();
    }
    if (uri.getUserInfo() != null) {
        final String[] credentials = uri.getUserInfo().split(":");
        this.userId = credentials[0];
        this.password = credentials[1];
    }
    if (uri.getPath() != null) {
        //the path includes the '/' after the host
        final String[] path = uri.getPath().split("/");
        if (path.length == 3) {
            this.project = path[1];
            this.domainName = path[2];
        }
    }

}

From source file:com.alibaba.napoli.gecko.service.impl.DefaultRemotingClient.java

private InetSocketAddress getSocketAddrFromGroup(String group) throws NotifyRemotingException {
    if (group == null) {
        throw new IllegalArgumentException("Null group");
    }//from   www. j  a v a 2  s . co m
    group = group.trim();
    if (!group.startsWith(this.config.getWireFormatType().getScheme())) {
        throw new NotifyRemotingException(
                "?Group?" + this.config.getWireFormatType().getScheme() + "");
    }
    try {
        final URI uri = new URI(group);
        return new InetSocketAddress(uri.getHost(), uri.getPort());
    } catch (final Exception e) {
        throw new NotifyRemotingException("uri???,url=" + group, e);
    }
}

From source file:com.github.lpezet.antiope.dao.DefaultHttpRequestFactory.java

/** Configures the headers in the specified Apache HTTP request. */
private void configureHeaders(HttpRequestBase pHttpRequest, Request<?> pRequest, ExecutionContext pContext,
        APIConfiguration pConfiguration) {
    /*//from  w  w w.  j  a v  a 2  s .co m
     * Apache HttpClient omits the port number in the Host header (even if
     * we explicitly specify it) if it's the default port for the protocol
     * in use. To ensure that we use the same Host header in the request and
     * in the calculated string to sign (even if Apache HttpClient changed
     * and started honoring our explicit host with endpoint), we follow this
     * same behavior here and in the QueryString signer.
     */
    URI endpoint = pRequest.getEndpoint();
    String hostHeader = endpoint.getHost();
    if (HttpUtils.isUsingNonDefaultPort(endpoint)) {
        hostHeader += COLON + endpoint.getPort();
    }
    pHttpRequest.addHeader(HOST, hostHeader);

    // Copy over any other headers already in our request
    for (Entry<String, String> entry : pRequest.getHeaders().entrySet()) {
        /*
         * HttpClient4 fills in the Content-Length header and complains if
         * it's already present, so we skip it here. We also skip the Host
         * header to avoid sending it twice, which will interfere with some
         * signing schemes.
         */
        if (entry.getKey().equalsIgnoreCase(CONTENT_LENGTH) || entry.getKey().equalsIgnoreCase(HOST))
            continue;

        pHttpRequest.addHeader(entry.getKey(), entry.getValue());
    }

    /* Set content type and encoding */
    if (pHttpRequest.getHeaders(CONTENT_TYPE) == null || pHttpRequest.getHeaders(CONTENT_TYPE).length == 0) {
        pHttpRequest.addHeader(CONTENT_TYPE,
                "application/x-www-form-urlencoded; " + "charset=" + DEFAULT_ENCODING.toLowerCase());
    }

    // Override the user agent string specified in the client params if the
    // context requires it
    if (pContext != null && pContext.getContextUserAgent() != null) {
        pHttpRequest.addHeader(USER_AGENT,
                createUserAgentString(pConfiguration, pContext.getContextUserAgent()));
    }
}

From source file:org.sonar.updatecenter.server.HttpDownloader.java

File downloadFile(URI fileURI, File toFile, String login, String password) {
    LOG.info("Download " + fileURI + " in " + toFile);
    DefaultHttpClient client = new DefaultHttpClient();
    try {/*from  w ww . ja v  a2 s . c o  m*/
        if (StringUtils.isNotBlank(login)) {
            client.getCredentialsProvider().setCredentials(new AuthScope(fileURI.getHost(), fileURI.getPort()),
                    new UsernamePasswordCredentials(login, password));
        }
        HttpGet httpget = new HttpGet(fileURI);
        byte[] data = client.execute(httpget, new ByteResponseHandler());
        if (data != null) {
            FileUtils.writeByteArrayToFile(toFile, data);
        }

    } catch (Exception e) {
        LOG.error("Fail to download " + fileURI + " to " + toFile, e);
        FileUtils.deleteQuietly(toFile);

    } finally {
        client.getConnectionManager().shutdown();
    }
    return toFile;
}

From source file:com.fortify.bugtracker.common.tgt.processor.AbstractTargetProcessorUpdateIssues.java

protected boolean compareTargetURIWithDeepLinkURI(URI targetURI, URI deepLinkURI) {
    return targetURI.getHost().equals(deepLinkURI.getHost()) && targetURI.getPort() == deepLinkURI.getPort();
}