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.ibm.watson.apis.conversation_enhanced.utils.HttpSolrClientUtils.java

/**
 * Creates the {@link HttpClient} to use with the Solrj
 *
 * @param url the Solr server url//  w  w  w. ja v  a  2s .c o m
 * @param username the {@link RetrieveAndRank} service username
 * @param password the {@link RetrieveAndRank} service password
 * @return the {@link HttpClient}
 */
private static HttpClient createHttpClient(String url, String username, String password) {
    final URI scopeUri = URI.create(url);
    logger.info(Messages.getString("HttpSolrClientUtils.CREATING_HTTP_CLIENT")); //$NON-NLS-1$
    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(scopeUri.getHost(), scopeUri.getPort()),
            new UsernamePasswordCredentials(username, password));

    final HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(128).setMaxConnPerRoute(32)
            .setDefaultRequestConfig(
                    RequestConfig.copy(RequestConfig.DEFAULT).setRedirectsEnabled(true).build())
            .setDefaultCredentialsProvider(credentialsProvider)
            .addInterceptorFirst(new PreemptiveAuthInterceptor());
    return builder.build();
}

From source file:ch.entwine.weblounge.common.impl.util.TestUtils.java

/**
 * Issues the the given request.//  w w w . j a v  a  2s . c om
 * 
 * @param httpClient
 *          the http client
 * @param request
 *          the request
 * @param params
 *          the request parameters
 * @throws Exception
 *           if the request fails
 */
public static HttpResponse request(HttpClient httpClient, HttpUriRequest request, String[][] params)
        throws Exception {
    if (params != null) {
        if (request instanceof HttpGet) {
            List<NameValuePair> qparams = new ArrayList<NameValuePair>();
            if (params.length > 0) {
                for (String[] param : params) {
                    if (param.length < 2)
                        continue;
                    qparams.add(new BasicNameValuePair(param[0], param[1]));
                }
            }
            URI requestURI = request.getURI();
            URI uri = URIUtils.createURI(requestURI.getScheme(), requestURI.getHost(), requestURI.getPort(),
                    requestURI.getPath(), URLEncodedUtils.format(qparams, "utf-8"), null);
            HeaderIterator headerIterator = request.headerIterator();
            request = new HttpGet(uri);
            while (headerIterator.hasNext()) {
                request.addHeader(headerIterator.nextHeader());
            }
        } else if (request instanceof HttpPost) {
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            for (String[] param : params)
                formparams.add(new BasicNameValuePair(param[0], param[1]));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "utf-8");
            ((HttpPost) request).setEntity(entity);
        } else if (request instanceof HttpPut) {
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            for (String[] param : params)
                formparams.add(new BasicNameValuePair(param[0], param[1]));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "utf-8");
            ((HttpPut) request).setEntity(entity);
        }
    } else {
        if (request instanceof HttpPost || request instanceof HttpPut) {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(new ArrayList<NameValuePair>(), "utf-8");
            ((HttpEntityEnclosingRequestBase) request).setEntity(entity);
        }
    }
    return httpClient.execute(request);
}

From source file:org.fdroid.enigtext.mms.MmsSendHelper.java

private static byte[] makePost(Context context, MmsConnectionParameters parameters, byte[] mms)
        throws ClientProtocolException, IOException {
    AndroidHttpClient client = null;//  w  ww .j  a  va  2  s.  c o  m

    try {
        Log.w("MmsSender", "Sending MMS1 of length: " + (mms != null ? mms.length : "null"));
        client = constructHttpClient(context, parameters);
        URI targetUrl = new URI(parameters.getMmsc());

        if (Util.isEmpty(targetUrl.getHost()))
            throw new IOException("Invalid target host: " + targetUrl.getHost() + " , " + targetUrl);

        HttpHost target = new HttpHost(targetUrl.getHost(), targetUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);
        HttpPost request = new HttpPost(parameters.getMmsc());
        ByteArrayEntity entity = new ByteArrayEntity(mms);

        entity.setContentType("application/vnd.wap.mms-message");

        request.setEntity(entity);
        request.setParams(client.getParams());
        request.addHeader("Accept", "*/*, application/vnd.wap.mms-message, application/vnd.wap.sic");
        request.addHeader("x-wap-profile", "http://www.google.com/oha/rdf/ua-profile-kila.xml");
        HttpResponse response = client.execute(target, request);
        StatusLine status = response.getStatusLine();

        if (status.getStatusCode() != 200)
            throw new IOException("Non-successful HTTP response: " + status.getReasonPhrase());

        return parseResponse(response.getEntity());
    } catch (URISyntaxException use) {
        Log.w("MmsSendHelper", use);
        throw new IOException("Couldn't parse URI.");
    } finally {
        if (client != null)
            client.close();
    }
}

From source file:org.gytheio.messaging.amqp.AmqpNodeBootstrapUtils.java

/**
 * Creates an AMQP endpoint (sender and receiver) from the given arguments
 * /* w  ww  .  j a  v a2 s .  c om*/
 * @param messageConsumer the processor received messages are sent to
 * @param args
 * @return
 */
public static AmqpDirectEndpoint createEndpoint(MessageConsumer messageConsumer, String brokerUrl,
        String brokerUsername, String brokerPassword, String requestEndpoint, String replyEndpoint) {
    validate(brokerUrl, requestEndpoint, replyEndpoint);

    AmqpDirectEndpoint messageProducer = new AmqpDirectEndpoint();
    ObjectMapper objectMapper = ObjectMapperFactory.createInstance();

    URI broker = null;
    try {
        broker = new URI(brokerUrl);
    } catch (URISyntaxException e) {
        // This would have been caught by validation above
    }

    ((AmqpDirectEndpoint) messageProducer).setHost(broker.getHost());
    Integer brokerPort = broker.getPort();
    if (brokerPort != null) {
        ((AmqpDirectEndpoint) messageProducer).setPort(brokerPort);
    }
    if (brokerUsername != null) {
        ((AmqpDirectEndpoint) messageProducer).setUsername(brokerUsername);
    }
    if (brokerPassword != null) {
        ((AmqpDirectEndpoint) messageProducer).setPassword(brokerPassword);
    }
    ((AmqpDirectEndpoint) messageProducer).setReceiveEndpoint(requestEndpoint);
    ((AmqpDirectEndpoint) messageProducer).setSendEndpoint(replyEndpoint);

    ((AmqpDirectEndpoint) messageProducer).setMessageConsumer(messageConsumer);
    ((AmqpDirectEndpoint) messageProducer).setObjectMapper(objectMapper);

    return messageProducer;
}

From source file:org.switchyard.component.http.endpoint.StandaloneEndpointPublisher.java

/**
 * Method for get request information from a http exchange.
 *
 * @param request HttpExchange//www.ja v  a  2  s . c  o m
 * @param type ContentType
 * @return Request information from a http exchange
 * @throws IOException when the request information could not be read
 */
public static HttpRequestInfo getRequestInfo(HttpExchange request, ContentType type) throws IOException {
    HttpRequestInfo requestInfo = new HttpRequestInfo();

    if (request.getHttpContext().getAuthenticator() instanceof BasicAuthenticator) {
        requestInfo.setAuthType(HttpServletRequest.BASIC_AUTH);
    }
    URI u = request.getRequestURI();
    URI requestURI = null;
    try {
        requestURI = new URI(u.getScheme(), u.getUserInfo(), u.getHost(), u.getPort(), u.getPath(), null, null);
    } catch (URISyntaxException e) {
        // Strange that this could happen when copying from another URI.
        LOGGER.debug(e);
    }
    requestInfo.setCharacterEncoding(type.getCharset());
    requestInfo.setContentType(type.toString());
    requestInfo.setContextPath(request.getHttpContext().getPath());
    requestInfo.setLocalAddr(request.getLocalAddress().getAddress().getHostAddress());
    requestInfo.setLocalName(request.getLocalAddress().getAddress().getHostName());
    requestInfo.setMethod(request.getRequestMethod());
    requestInfo.setProtocol(request.getProtocol());
    requestInfo.setQueryString(u.getQuery());
    requestInfo.setRemoteAddr(request.getRemoteAddress().getAddress().getHostAddress());
    requestInfo.setRemoteHost(request.getRemoteAddress().getAddress().getHostName());
    if (request.getHttpContext().getAuthenticator() instanceof BasicAuthenticator) {
        requestInfo.setRemoteUser(request.getPrincipal().getUsername());
    }
    requestInfo.setContentLength(request.getRequestBody().available());
    // requestInfo.setRequestSessionId(request.getRequestedSessionId());
    if (requestURI != null) {
        requestInfo.setRequestURI(requestURI.toString());
    }
    requestInfo.setScheme(u.getScheme());
    requestInfo.setServerName(u.getHost());
    requestInfo.setRequestPath(u.getPath());

    // Http Query params...
    if (requestInfo.getQueryString() != null) {
        Charset charset = null;
        if (type.getCharset() != null) {
            try {
                charset = Charset.forName(type.getCharset());
            } catch (Exception exception) {
                LOGGER.debug(exception);
            }
        }
        for (NameValuePair nameValuePair : URLEncodedUtils.parse(requestInfo.getQueryString(), charset)) {
            requestInfo.addQueryParam(nameValuePair.getName(), nameValuePair.getValue());
        }
    }

    // Credentials...
    requestInfo.getCredentials().addAll(new HttpExchangeCredentialExtractor().extract(request));

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace(requestInfo);
    }

    return requestInfo;
}

From source file:com.mindquarry.desktop.workspace.SVNProxyHandler.java

public static void applyProxySettings(List<Profile> profiles, String proxyURL, String proxyLogin,
        String proxyPwd) throws Exception {
    removeProxySettings();//from w ww .  j  a va2  s  .  c o  m

    Ini ini = getParser();
    Ini.Section groups = ini.get("groups");

    int number = 0;
    for (Profile profile : profiles) {
        URI uri = new URI(profile.getServerURL());

        String groupID = GROUP_PREFIX + number++;
        groups.put(groupID, uri.getHost());

        uri = new URI(proxyURL);

        Ini.Section section = ini.add(groupID);
        section.put(PROXY_HOST, uri.getHost());
        if (uri.getPort() != -1) {
            section.put(PROXY_PORT, String.valueOf(uri.getPort()));
        }
        if (!proxyLogin.equals("")) {
            section.put(PROXY_USERNAME, proxyLogin);
        }
        if (!proxyPwd.equals("")) {
            section.put(PROXY_PASSWORD, proxyPwd);
        }
    }
    storeConfig(ini);
}

From source file:com.google.cloud.hadoop.util.HttpTransportFactory.java

/**
 * Create an {@link HttpTransport} based on an type class and an optional HTTP proxy.
 *
 * @param type The type of HttpTransport to use.
 * @param proxyAddress The HTTP proxy to use with the transport. Of the form hostname:port. If
 * empty no proxy will be used./*from w w w .j  a  v a2s  .co  m*/
 * @return The resulting HttpTransport.
 * @throws IllegalArgumentException If the proxy address is invalid.
 * @throws IOException If there is an issue connecting to Google's Certification server.
 */
public static HttpTransport createHttpTransport(HttpTransportType type, @Nullable String proxyAddress)
        throws IOException {
    try {
        URI proxyUri = parseProxyAddress(proxyAddress);
        switch (type) {
        case APACHE:
            HttpHost proxyHost = null;
            if (proxyUri != null) {
                proxyHost = new HttpHost(proxyUri.getHost(), proxyUri.getPort());
            }
            return createApacheHttpTransport(proxyHost);
        case JAVA_NET:
            Proxy proxy = null;
            if (proxyUri != null) {
                proxy = new Proxy(Proxy.Type.HTTP,
                        new InetSocketAddress(proxyUri.getHost(), proxyUri.getPort()));
            }
            return createNetHttpTransport(proxy);
        default:
            throw new IllegalArgumentException(String.format("Invalid HttpTransport type '%s'", type.name()));
        }
    } catch (GeneralSecurityException e) {
        throw new IOException(e);
    }
}

From source file:com.ibm.jaggr.core.impl.deps.DepUtils.java

/**
 * Removes URIs containing duplicate and non-orthogonal paths so that the
 * collection contains only unique and non-overlapping paths.
 *
 * @param uris collection of URIs// w w  w  . j  a v a 2  s .  c  om
 *
 * @return a new collection with redundant paths removed
 */
static public Collection<URI> removeRedundantPaths(Collection<URI> uris) {
    List<URI> result = new ArrayList<URI>();
    for (URI uri : uris) {
        String path = uri.getPath();
        if (!path.endsWith("/")) { //$NON-NLS-1$
            path += "/"; //$NON-NLS-1$
        }
        boolean addIt = true;
        for (int i = 0; i < result.size(); i++) {
            URI testUri = result.get(i);
            if (!StringUtils.equals(testUri.getScheme(), uri.getScheme())
                    || !StringUtils.equals(testUri.getHost(), uri.getHost())
                    || testUri.getPort() != uri.getPort()) {
                continue;
            }
            String test = testUri.getPath();
            if (!test.endsWith("/")) { //$NON-NLS-1$
                test += "/"; //$NON-NLS-1$
            }
            if (path.equals(test) || path.startsWith(test)) {
                addIt = false;
                break;
            } else if (test.startsWith(path)) {
                result.remove(i);
            }
        }
        if (addIt)
            result.add(uri);
    }
    // Now copy the trimmed list back to the original
    return result;
}

From source file:org.jboss.as.test.integration.domain.AbstractSSLMasterSlaveTestCase.java

private static CloseableHttpClient createHttpClient(URI mgmtURI) {
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(SLAVE_HOST_USERNAME,
            SLAVE_HOST_PASSWORD);/* www .  j a  v  a  2 s . c o m*/
    AuthScope authScope = new AuthScope(mgmtURI.getHost(), mgmtURI.getPort());
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(authScope, credentials);
    return HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
}

From source file:eu.stratosphere.nephele.net.NetUtils.java

/**
 * Util method to build socket addr from either:
 * <host>/*from  w w w  .  j a  v  a 2  s. c  o m*/
 * <host>:<post>
 * <fs>://<host>:<port>/<path>
 */
public static InetSocketAddress createSocketAddr(String target, int defaultPort) {
    int colonIndex = target.indexOf(':');
    if (colonIndex < 0 && defaultPort == -1) {
        throw new RuntimeException("Not a host:port pair: " + target);
    }
    String hostname = "";
    int port = -1;
    if (!target.contains("/")) {
        if (colonIndex == -1) {
            hostname = target;
        } else {
            // must be the old style <host>:<port>
            hostname = target.substring(0, colonIndex);
            port = Integer.parseInt(target.substring(colonIndex + 1));
        }
    } else {
        // a new uri
        try {
            URI addr = new URI(target);
            hostname = addr.getHost();
            port = addr.getPort();
        } catch (URISyntaxException use) {
            LOG.fatal(use);
        }
    }

    if (port == -1) {
        port = defaultPort;
    }

    if (getStaticResolution(hostname) != null) {
        hostname = getStaticResolution(hostname);
    }
    return new InetSocketAddress(hostname, port);
}