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.gsma.mobileconnect.utils.RestClient.java

/**
 * Build a HttpClientContext that will preemptively authenticate using Basic Authentication
 *
 * @param username Username for credentials
 * @param password Password for credentials
 * @param uriForRealm uri used to determine the authentication realm
 * @return A HttpClientContext that will preemptively authenticate using Basic Authentication
 */// w w  w . j av  a2 s  . com
public HttpClientContext getHttpClientContext(String username, String password, URI uriForRealm) {
    String host = URIUtils.extractHost(uriForRealm).getHostName();
    int port = uriForRealm.getPort();
    if (port == -1) {
        if (Constants.HTTP_SCHEME.equalsIgnoreCase(uriForRealm.getScheme())) {
            port = Constants.HTTP_PORT;
        } else if (Constants.HTTPS_SCHEME.equalsIgnoreCase(uriForRealm.getScheme())) {
            port = Constants.HTTPS_PORT;
        }
    }

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(host, port),
            new UsernamePasswordCredentials(username, password));

    AuthCache authCache = new BasicAuthCache();
    authCache.put(new HttpHost(host, port, uriForRealm.getScheme()), new BasicScheme());

    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthCache(authCache);

    return context;
}

From source file:org.springframework.ws.transport.http.HttpComponentsMessageSender.java

/**
 * Sets the maximum number of connections per host for the underlying HttpClient. The maximum number of connections
 * per host can be set in a form accepted by the {@code java.util.Properties} class, like as follows:
 * <p/>/*from w w w .j  av a 2 s .  c o m*/
 * <pre>
 * https://www.example.com=1
 * http://www.example.com:8080=7
 * http://www.springframework.org=10
 * </pre>
 * <p/>
 * The host can be specified as a URI (with scheme and port).
 *
 * @param maxConnectionsPerHost a properties object specifying the maximum number of connection
 * @see org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager#setMaxForRoute(org.apache.http.conn.routing.HttpRoute,
 *      int)
 */
public void setMaxConnectionsPerHost(Map<String, String> maxConnectionsPerHost) throws URISyntaxException {
    ClientConnectionManager connectionManager = getHttpClient().getConnectionManager();
    if (!(connectionManager instanceof ThreadSafeClientConnManager)) {
        throw new IllegalArgumentException(
                "maxConnectionsPerHost is not supported on " + connectionManager.getClass().getName() + ". Use "
                        + ThreadSafeClientConnManager.class.getName() + " instead");
    }

    for (Object o : maxConnectionsPerHost.keySet()) {
        String host = (String) o;
        URI uri = new URI(host);
        HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
        int maxHostConnections = Integer.parseInt(maxConnectionsPerHost.get(host));
        ((ThreadSafeClientConnManager) connectionManager).setMaxForRoute(new HttpRoute(httpHost),
                maxHostConnections);
    }
}

From source file:com.esri.geoportal.commons.http.BotsHttpClient.java

private String getProtocolHostPort(URI u) throws MalformedURLException {
    return String.format("%s://%s%s", u.getScheme(), u.getHost(), u.getPort() >= 0 ? ":" + u.getPort() : "");
}

From source file:com.nirima.jenkins.SimpleArtifactCopier.java

private void init() throws URISyntaxException {
    URI targetURI = host.toURI();

    targetHost = new HttpHost(targetURI.getHost(), targetURI.getPort());

    params = new BasicHttpParams();
    params.setParameter(HttpProtocolParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    params.setBooleanParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    params.setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false);
    params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8 * 1024);

    httpexecutor = new HttpRequestExecutor();
    httpproc = new BasicHttpProcessor();
    // Required protocol interceptors
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    // Recommended protocol interceptors
    httpproc.addInterceptor(new RequestConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());

    context = new BasicHttpContext();

    conn = new DefaultHttpClientConnection();

    connStrategy = new DefaultConnectionReuseStrategy();
}

From source file:fr.wseduc.webutils.email.SendInBlueSender.java

public SendInBlueSender(Vertx vertx, Container container, JsonObject config)
        throws InvalidConfigurationException, URISyntaxException {
    super(vertx, container);
    if (config != null && isNotEmpty(config.getString("uri")) && isNotEmpty(config.getString("api-key"))) {
        URI uri = new URI(config.getString("uri"));
        httpClient = vertx.createHttpClient().setHost(uri.getHost()).setPort(uri.getPort()).setMaxPoolSize(16)
                .setSSL("https".equals(uri.getScheme())).setKeepAlive(false);
        apiKey = config.getString("api-key");
        dedicatedIp = config.getString("ip");
        splitRecipients = config.getBoolean("split-recipients", false);
        mapper = new ObjectMapper();
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    } else {// w  w w.  j a va  2 s. c om
        throw new InvalidConfigurationException("missing.parameters");
    }
}

From source file:com.ibm.watson.ta.retail.DemoServlet.java

/**
 * Build an executor for the specified url. This disables cookies and sets
 * preemptive authentication (creds are sent without waiting for a 401).
 * //from w  w  w. j  a  v a2s  .c o  m
 * NOTE: This is required to avoid issues with load balancers that use
 * cookies due to Apache Http Client issue:
 * https://issues.apache.org/jira/browse/HTTPCLIENT-1451
 * 
 * @param url
 * @return
 */
private Executor buildExecutor(URI url) {
    return Executor.newInstance().auth(username, password)
            .authPreemptive(new HttpHost(url.getHost(), url.getPort(), url.getScheme()))
            .cookieStore(new CookieStore() {
                // Noop cookie store.
                public void addCookie(Cookie arg0) {
                }

                public void clear() {
                }

                public boolean clearExpired(Date arg0) {
                    return false;
                }

                public List<Cookie> getCookies() {
                    return Collections.emptyList();
                }
            });
}

From source file:org.droidparts.http.CookieJar.java

private List<Cookie> parseCookies(URI uri, List<String> cookieHeaders) {
    ArrayList<Cookie> cookies = new ArrayList<Cookie>();
    int port = (uri.getPort() < 0) ? 80 : uri.getPort();
    boolean secure = "https".equals(uri.getScheme());
    CookieOrigin origin = new CookieOrigin(uri.getHost(), port, uri.getPath(), secure);
    for (String cookieHeader : cookieHeaders) {
        BasicHeader header = new BasicHeader(SM.SET_COOKIE, cookieHeader);
        try {//from ww  w .  java2  s. c  o m
            cookies.addAll(cookieSpec.parse(header, origin));
        } catch (MalformedCookieException e) {
            L.d(e);
        }
    }
    return cookies;
}

From source file:com.navercorp.pinpoint.plugin.httpclient4.interceptor.HttpClientExecuteMethodWithHttpUriRequestInterceptor.java

/**
 * copy//from   w  ww  .  j a va  2s.  co m
 * org.apache.http.client.utils.URIUtils#extractHost(java.net.URI)
 * @param uri
 * @return
 */
private NameIntValuePair<String> extractHost(final URI uri) {
    if (uri == null) {
        return null;
    }
    NameIntValuePair<String> target = null;
    if (uri.isAbsolute()) {
        int port = uri.getPort(); // may be overridden later
        String host = uri.getHost();
        if (host == null) { // normal parse failed; let's do it ourselves
            // authority does not seem to care about the valid character-set
            // for host names
            host = uri.getAuthority();
            if (host != null) {
                // Strip off any leading user credentials
                int at = host.indexOf('@');
                if (at >= 0) {
                    if (host.length() > at + 1) {
                        host = host.substring(at + 1);
                    } else {
                        host = null; // @ on its own
                    }
                }
                // Extract the port suffix, if present
                if (host != null) {
                    int colon = host.indexOf(':');
                    if (colon >= 0) {
                        int pos = colon + 1;
                        int len = 0;
                        for (int i = pos; i < host.length(); i++) {
                            if (Character.isDigit(host.charAt(i))) {
                                len++;
                            } else {
                                break;
                            }
                        }
                        if (len > 0) {
                            try {
                                port = Integer.parseInt(host.substring(pos, pos + len));
                            } catch (NumberFormatException ignore) {
                                // skip
                            }
                        }
                        host = host.substring(0, colon);
                    }
                }
            }
        }
        if (host != null) {
            target = new NameIntValuePair<String>(host, port);
        }
    }
    return target;
}

From source file:com.almende.eve.transport.xmpp.XmppTransport.java

/**
 * Instantiates a new xmpp transport./* w  ww  .ja  va  2  s. c  o  m*/
 * 
 * @param config
 *            the config
 * @param handle
 *            the handle
 * @param service
 *            the service
 */
public XmppTransport(final XmppTransportConfig config, final Handler<Receiver> handle,
        final TransportService service) {
    // TODO: support more parameter structures.
    super(config.getAddress(), handle, service, config);

    final URI address = super.getAddress();
    host = address.getHost();
    port = address.getPort();
    if (port < 0) {
        port = 5222;
    }
    username = address.getUserInfo();
    resource = address.getPath().substring(1);
    if (serviceName == null) {
        serviceName = host;
    }
    password = config.getPassword();
}

From source file:nu.yona.server.sms.PlivoSmsService.java

private HttpClientContext createHttpClientContext() {
    try {/*from   w ww . j  a v  a 2 s. co  m*/
        SmsProperties smsProperties = yonaProperties.getSms();

        URI uri = getPlivoUrl(smsProperties);
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
                new UsernamePasswordCredentials(smsProperties.getPlivoAuthId(),
                        smsProperties.getPlivoAuthToken()));

        HttpClientContext httpClientContext = HttpClientContext.create();
        httpClientContext.setCredentialsProvider(credentialsProvider);
        return httpClientContext;
    } catch (URISyntaxException e) {
        throw SmsException.smsSendingFailed(e);
    }
}