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.mirth.connect.connectors.mllp.MllpMessageReceiver.java

protected Socket createClientSocket(URI uri) throws IOException {
    String host = uri.getHost();/*from   w  ww .  ja  v  a 2 s  .c o m*/
    InetAddress inetAddress = InetAddress.getByName(host);
    return new Socket(inetAddress, uri.getPort());
}

From source file:HttpDownloadManager.java

public Download download(URI uri, Listener l) throws IOException {
    if (released)
        throw new IllegalStateException("Can't download() after release()");

    // Get info from the URI
    String scheme = uri.getScheme();
    if (scheme == null || !scheme.equals("http"))
        throw new IllegalArgumentException("Must use 'http:' protocol");
    String hostname = uri.getHost();
    int port = uri.getPort();
    if (port == -1)
        port = 80; // Use default port if none specified
    String path = uri.getRawPath();
    if (path == null || path.length() == 0)
        path = "/";
    String query = uri.getRawQuery();
    if (query != null)
        path += "?" + query;

    // Create a Download object with the pieces of the URL
    Download download = new DownloadImpl(hostname, port, path, l);

    // Add it to the list of pending downloads. This is a synchronized list
    pendingDownloads.add(download);/*from  www  .  j  ava2  s .  com*/

    // And ask the thread to stop blocking in the select() call so that
    // it will notice and process this new pending Download object.
    selector.wakeup();

    // Return the Download so that the caller can monitor it if desired.
    return download;
}

From source file:org.opendatakit.aggregate.externalservice.AbstractExternalService.java

protected HttpResponse sendHttpRequest(String method, String url, HttpEntity entity,
        List<NameValuePair> qparams, CallingContext cc) throws IOException {

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
    HttpConnectionParams.setSoTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);

    // setup client
    HttpClientFactory factory = (HttpClientFactory) cc.getBean(BeanDefs.HTTP_CLIENT_FACTORY);
    HttpClient client = factory.createHttpClient(httpParams);

    // support redirecting to handle http: => https: transition
    HttpClientParams.setRedirecting(httpParams, true);
    // support authenticating
    HttpClientParams.setAuthenticating(httpParams, true);

    // redirect limit is set to some unreasonably high number
    // resets of the socket cause a retry up to MAX_REDIRECTS times,
    // so we should be careful not to set this too high...
    httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 32);
    httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);

    // context holds authentication state machine, so it cannot be
    // shared across independent activities.
    HttpContext localContext = new BasicHttpContext();

    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);

    HttpUriRequest request = null;//  w w w  .  jav  a2  s .com
    if (entity == null && (POST.equals(method) || PATCH.equals(method) || PUT.equals(method))) {
        throw new IllegalStateException("No body supplied for POST, PATCH or PUT request");
    } else if (entity != null && !(POST.equals(method) || PATCH.equals(method) || PUT.equals(method))) {
        throw new IllegalStateException("Body was supplied for GET or DELETE request");
    }

    URI nakedUri;
    try {
        nakedUri = new URI(url);
    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException(e);
    }

    if (qparams == null) {
        qparams = new ArrayList<NameValuePair>();
    }
    URI uri;
    try {
        uri = new URI(nakedUri.getScheme(), nakedUri.getUserInfo(), nakedUri.getHost(), nakedUri.getPort(),
                nakedUri.getPath(), URLEncodedUtils.format(qparams, HtmlConsts.UTF8_ENCODE), null);
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
        throw new IllegalStateException(e1);
    }
    System.out.println(uri.toString());

    if (GET.equals(method)) {
        HttpGet get = new HttpGet(uri);
        request = get;
    } else if (DELETE.equals(method)) {
        HttpDelete delete = new HttpDelete(uri);
        request = delete;
    } else if (PATCH.equals(method)) {
        HttpPatch patch = new HttpPatch(uri);
        patch.setEntity(entity);
        request = patch;
    } else if (POST.equals(method)) {
        HttpPost post = new HttpPost(uri);
        post.setEntity(entity);
        request = post;
    } else if (PUT.equals(method)) {
        HttpPut put = new HttpPut(uri);
        put.setEntity(entity);
        request = put;
    } else {
        throw new IllegalStateException("Unexpected request method");
    }

    HttpResponse resp = client.execute(request);
    return resp;
}

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

public CloseableHttpProvider(ClientCredentials clientCredentials, UserCredentials userCredentials,
        URI accessTokenUri, HttpConfig httpConfig) {
    this.userCredentials = userCredentials;
    this.accessTokenUri = accessTokenUri;
    requestConfig = RequestConfig.custom().setSocketTimeout(httpConfig.getSocketTimeout())
            .setConnectTimeout(httpConfig.getConnectTimeout())
            .setConnectionRequestTimeout(httpConfig.getConnectionRequestTimeout())
            .setStaleConnectionCheckEnabled(httpConfig.isStaleConnectionCheckEnabled()).build();

    // prepare basic auth credentials
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(accessTokenUri.getHost(), accessTokenUri.getPort()),
            new UsernamePasswordCredentials(clientCredentials.getId(), clientCredentials.getSecret()));

    client = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();

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

    // enable basic auth for the request
    final AuthCache authCache = new BasicAuthCache();
    final BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);/*from  w ww .  j a v a 2s.c o m*/

    localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
}

From source file:org.glassfish.jersey.apache.connector.ApacheConnector.java

/**
 * Create the new Apache HTTP Client connector.
 *
 * @param client JAX-RS client instance for which the connector is being created.
 * @param config client configuration./*w w  w.  j a v a  2 s.co  m*/
 */
ApacheConnector(final Client client, final Configuration config) {
    final Object connectionManager = config.getProperties().get(ApacheClientProperties.CONNECTION_MANAGER);
    if (connectionManager != null) {
        if (!(connectionManager instanceof HttpClientConnectionManager)) {
            LOGGER.log(Level.WARNING,
                    LocalizationMessages.IGNORING_VALUE_OF_PROPERTY(ApacheClientProperties.CONNECTION_MANAGER,
                            connectionManager.getClass().getName(),
                            HttpClientConnectionManager.class.getName()));
        }
    }

    Object reqConfig = config.getProperties().get(ApacheClientProperties.REQUEST_CONFIG);
    if (reqConfig != null) {
        if (!(reqConfig instanceof RequestConfig)) {
            LOGGER.log(Level.WARNING,
                    LocalizationMessages.IGNORING_VALUE_OF_PROPERTY(ApacheClientProperties.REQUEST_CONFIG,
                            reqConfig.getClass().getName(), RequestConfig.class.getName()));
            reqConfig = null;
        }
    }

    final SSLContext sslContext = client.getSslContext();
    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();

    clientBuilder.setConnectionManager(getConnectionManager(client, config, sslContext));
    clientBuilder.setConnectionManagerShared(PropertiesHelper.getValue(config.getProperties(),
            ApacheClientProperties.CONNECTION_MANAGER_SHARED, false, null));
    clientBuilder.setSslcontext(sslContext);

    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

    final Object credentialsProvider = config.getProperty(ApacheClientProperties.CREDENTIALS_PROVIDER);
    if (credentialsProvider != null && (credentialsProvider instanceof CredentialsProvider)) {
        clientBuilder.setDefaultCredentialsProvider((CredentialsProvider) credentialsProvider);
    }

    final Object retryHandler = config.getProperties().get(ApacheClientProperties.RETRY_HANDLER);
    if (retryHandler != null && (retryHandler instanceof HttpRequestRetryHandler)) {
        clientBuilder.setRetryHandler((HttpRequestRetryHandler) retryHandler);
    }

    final Object proxyUri;
    proxyUri = config.getProperty(ClientProperties.PROXY_URI);
    if (proxyUri != null) {
        final URI u = getProxyUri(proxyUri);
        final HttpHost proxy = new HttpHost(u.getHost(), u.getPort(), u.getScheme());
        final String userName;
        userName = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_USERNAME,
                String.class);
        if (userName != null) {
            final String password;
            password = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_PASSWORD,
                    String.class);

            if (password != null) {
                final CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(u.getHost(), u.getPort()),
                        new UsernamePasswordCredentials(userName, password));
                clientBuilder.setDefaultCredentialsProvider(credsProvider);
            }
        }
        clientBuilder.setProxy(proxy);
    }

    final Boolean preemptiveBasicAuthProperty = (Boolean) config.getProperties()
            .get(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION);
    this.preemptiveBasicAuth = (preemptiveBasicAuthProperty != null) ? preemptiveBasicAuthProperty : false;

    final boolean ignoreCookies = PropertiesHelper.isProperty(config.getProperties(),
            ApacheClientProperties.DISABLE_COOKIES);

    if (reqConfig != null) {
        final RequestConfig.Builder reqConfigBuilder = RequestConfig.copy((RequestConfig) reqConfig);
        if (ignoreCookies) {
            reqConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
        }
        requestConfig = reqConfigBuilder.build();
    } else {
        if (ignoreCookies) {
            requestConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
        }
        requestConfig = requestConfigBuilder.build();
    }

    if (requestConfig.getCookieSpec() == null
            || !requestConfig.getCookieSpec().equals(CookieSpecs.IGNORE_COOKIES)) {
        this.cookieStore = new BasicCookieStore();
        clientBuilder.setDefaultCookieStore(cookieStore);
    } else {
        this.cookieStore = null;
    }
    clientBuilder.setDefaultRequestConfig(requestConfig);
    this.client = clientBuilder.build();
}

From source file:ch.cyberduck.core.cloudfront.CloudFrontDistributionConfiguration.java

protected com.amazonaws.services.cloudfront.model.Distribution createCustomDistribution(final Path container,
        final Distribution distribution) throws BackgroundException {
    final AmazonCloudFront client = client(container);
    int httpPort = 80;
    int httpsPort = 443;
    final URI origin = this.getOrigin(container, distribution.getMethod());
    if (origin.getPort() != -1) {
        if (origin.getScheme().equals(Scheme.http.name())) {
            httpPort = origin.getPort();
        }// w  w  w. j  a  v  a  2s  .co m
        if (origin.getScheme().equals(Scheme.https.name())) {
            httpsPort = origin.getPort();
        }
    }
    final String originId = String.format("%s-%s", preferences.getProperty("application.name"),
            new AlphanumericRandomStringService().random());
    final DistributionConfig config = new DistributionConfig(new AlphanumericRandomStringService().random(),
            distribution.isEnabled())
                    .withComment(originId)
                    .withOrigins(new Origins().withQuantity(1)
                            .withItems(new Origin().withId(originId).withDomainName(origin.getHost())
                                    .withCustomOriginConfig(new CustomOriginConfig().withHTTPPort(httpPort)
                                            .withHTTPSPort(httpsPort)
                                            .withOriginSslProtocols(new OriginSslProtocols().withQuantity(2)
                                                    .withItems("TLSv1.1", "TLSv1.2"))
                                            .withOriginProtocolPolicy(
                                                    this.getPolicy(distribution.getMethod())))))
                    .withPriceClass(PriceClass.PriceClass_All)
                    .withDefaultCacheBehavior(new DefaultCacheBehavior().withTargetOriginId(originId)
                            .withForwardedValues(new ForwardedValues().withQueryString(true)
                                    .withCookies(new CookiePreference().withForward(ItemSelection.All)))
                            .withViewerProtocolPolicy(ViewerProtocolPolicy.AllowAll).withMinTTL(0L)
                            .withTrustedSigners(new TrustedSigners().withEnabled(false).withQuantity(0)))
                    .withDefaultRootObject(distribution.getIndexDocument()).withAliases(new Aliases()
                            .withItems(distribution.getCNAMEs()).withQuantity(distribution.getCNAMEs().length));
    if (distribution.isLogging()) {
        // Make bucket name fully qualified
        final String loggingTarget = ServiceUtils.generateS3HostnameForBucket(
                distribution.getLoggingContainer(), false, new S3Protocol().getDefaultHostname());
        if (log.isDebugEnabled()) {
            log.debug(String.format("Set logging target for %s to %s", distribution, loggingTarget));
        }
        config.setLogging(new LoggingConfig().withEnabled(distribution.isLogging()).withIncludeCookies(true)
                .withBucket(loggingTarget).withPrefix(preferences.getProperty("cloudfront.logging.prefix")));
    }
    return client.createDistribution(new CreateDistributionRequest(config)).getDistribution();
}

From source file:com.cloudera.hoop.client.fs.HoopFileSystem.java

/**
 * Called after a new FileSystem instance is constructed.
 *
 * @param name a uri whose authority section names the host, port, etc. for this FileSystem
 * @param conf the configuration/*from ww  w .jav a2s.  c om*/
 */
@Override
public void initialize(URI name, Configuration conf) throws IOException {
    UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
    doAs = ugi.getUserName();
    super.initialize(name, conf);
    try {
        uri = new URI(name.getScheme() + "://" + name.getHost() + ":" + name.getPort());
    } catch (URISyntaxException ex) {
        throw new IOException(ex);
    }
}

From source file:com.mirth.connect.connectors.tcp.TcpMessageReceiver.java

protected ServerSocket createSocket(URI uri) throws IOException {
    String host = uri.getHost();//w  w w.j a v a2  s .  c  o  m
    int backlog = connector.getBacklog();
    if (host == null || host.length() == 0) {
        host = "localhost";
    }
    InetAddress inetAddress = InetAddress.getByName(host);
    if (inetAddress.equals(InetAddress.getLocalHost()) || inetAddress.isLoopbackAddress()
            || host.trim().equals("localhost")) {
        return new ServerSocket(uri.getPort(), backlog);
    } else {
        return new ServerSocket(uri.getPort(), backlog, inetAddress);
    }
}

From source file:edu.stanford.junction.provider.irc.Junction.java

public Junction(URI uri, ActivityScript script, final JunctionActor actor) {
    this.setActor(actor);

    mNickname = makeIRCName(actor.getActorID());

    // User & name are not important for 
    // our needs. 
    String user = "jxuser";
    String name = "jxuser";

    mFullNick = new FullNick(mNickname + "!" + user + "@127.0.0.1");

    mAcceptedInvitation = uri;//from   ww w.j a  va 2 s  .  c  o m
    mActivityScript = script;
    mSession = "jxsession-" + makeIRCName(uri.getPath().substring(1));
    String host = uri.getHost();
    int port = uri.getPort();

    mClientState = new ClientState();
    mConnection = new IRCConnection(mClientState);

    mConnection.addStateObserver(new JXStateObserver());
    mConnection.addCommandObserver(new JXCommandObserver());

    AutoJoin autoJoin = new AutoJoin(mConnection, "#" + mSession);
    AutoRegister autoReg = new AutoRegister(mConnection, mNickname, user, name);
    AutoReconnect autoRecon = new AutoReconnect(mConnection);
    AutoResponder autoRes = new AutoResponder(mConnection);

    autoRecon.go(host, port);
}