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:brooklyn.networking.cloudstack.HttpUtil.java

public static HttpClient createHttpClient(URI uri, Optional<Credentials> credentials) {
    final DefaultHttpClient httpClient = new DefaultHttpClient();

    // TODO if supplier returns null, we may wish to defer initialization until url available?
    if (uri != null && "https".equalsIgnoreCase(uri.getScheme())) {
        try {/* www. ja v  a  2  s .co  m*/
            int port = (uri.getPort() >= 0) ? uri.getPort() : 443;
            SSLSocketFactory socketFactory = new SSLSocketFactory(new TrustAllStrategy(),
                    SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Scheme sch = new Scheme("https", port, socketFactory);
            httpClient.getConnectionManager().getSchemeRegistry().register(sch);
        } catch (Exception e) {
            LOG.warn("Error in HTTP Feed of {}, setting trust for uri {}", uri);
            throw Exceptions.propagate(e);
        }
    }

    // Set credentials
    if (uri != null && credentials.isPresent()) {
        String hostname = uri.getHost();
        int port = uri.getPort();
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(hostname, port), credentials.get());
    }

    return httpClient;
}

From source file:com.jaeksoft.searchlib.util.LinkUtils.java

public final static URL getLink(URL currentURL, String href, UrlFilterItem[] urlFilterList,
        boolean removeFragment) {

    if (href == null)
        return null;
    href = href.trim();//from  ww w .java2  s  . c  o  m
    if (href.length() == 0)
        return null;

    String fragment = null;
    try {
        URI u = URIUtils.resolve(currentURL.toURI(), href);
        href = u.toString();
        href = UrlFilterList.doReplace(u.getHost(), href, urlFilterList);
        URI uri = URI.create(href);
        uri = uri.normalize();

        String p = uri.getPath();
        if (p != null)
            if (p.contains("/./") || p.contains("/../"))
                return null;

        if (!removeFragment)
            fragment = uri.getRawFragment();

        return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(),
                uri.getQuery(), fragment).normalize().toURL();
    } catch (MalformedURLException e) {
        Logging.info(e.getMessage());
        return null;
    } catch (URISyntaxException e) {
        Logging.info(e.getMessage());
        return null;
    } catch (IllegalArgumentException e) {
        Logging.info(e.getMessage());
        return null;
    }
}

From source file:com.google.android.mms.transaction.HttpUtils.java

/**
 * A helper method to send or retrieve data through HTTP protocol.
 *
 * @param token The token to identify the sending progress.
 * @param url The URL used in a GET request. Null when the method is
 *         HTTP_POST_METHOD.//w  ww .  ja  v  a  2s .co m
 * @param pdu The data to be POST. Null when the method is HTTP_GET_METHOD.
 * @param method HTTP_POST_METHOD or HTTP_GET_METHOD.
 * @return A byte array which contains the response data.
 *         If an HTTP error code is returned, an IOException will be thrown.
 * @throws IOException if any error occurred on network interface or
 *         an HTTP error code(&gt;=400) returned from the server.
 */
public static byte[] httpConnection(Context context, long token, String url, byte[] pdu, int method,
        boolean isProxySet, String proxyHost, int proxyPort) throws IOException {
    if (url == null) {
        throw new IllegalArgumentException("URL must not be null.");
    }

    if (LOCAL_LOGV) {
        Log.v(TAG, "httpConnection: params list");
        Log.v(TAG, "\ttoken\t\t= " + token);
        Log.v(TAG, "\turl\t\t= " + url);
        Log.v(TAG, "\tmethod\t\t= "
                + ((method == HTTP_POST_METHOD) ? "POST" : ((method == HTTP_GET_METHOD) ? "GET" : "UNKNOWN")));
        Log.v(TAG, "\tisProxySet\t= " + isProxySet);
        Log.v(TAG, "\tproxyHost\t= " + proxyHost);
        Log.v(TAG, "\tproxyPort\t= " + proxyPort);
        // TODO Print out binary data more readable.
        //Log.v(TAG, "\tpdu\t\t= " + Arrays.toString(pdu));
    }

    AndroidHttpClient client = null;

    try {
        // Make sure to use a proxy which supports CONNECT.
        URI hostUrl = new URI(url);
        HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);

        client = createHttpClient(context);
        HttpRequest req = null;
        switch (method) {
        case HTTP_POST_METHOD:
            ProgressCallbackEntity entity = new ProgressCallbackEntity(context, token, pdu);
            // Set request content type.
            entity.setContentType("application/vnd.wap.mms-message");

            HttpPost post = new HttpPost(url);
            post.setEntity(entity);
            req = post;
            break;
        case HTTP_GET_METHOD:
            req = new HttpGet(url);
            break;
        default:
            Log.e(TAG, "Unknown HTTP method: " + method + ". Must be one of POST[" + HTTP_POST_METHOD
                    + "] or GET[" + HTTP_GET_METHOD + "].");
            return null;
        }

        // Set route parameters for the request.
        HttpParams params = client.getParams();
        if (isProxySet) {
            ConnRouteParams.setDefaultProxy(params, new HttpHost(proxyHost, proxyPort));
        }
        req.setParams(params);

        // Set necessary HTTP headers for MMS transmission.
        req.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT);
        {
            String xWapProfileTagName = MmsConfig.getUaProfTagName();
            String xWapProfileUrl = MmsConfig.getUaProfUrl();

            if (xWapProfileUrl != null) {
                if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
                    Log.d(LogTag.TRANSACTION, "[HttpUtils] httpConn: xWapProfUrl=" + xWapProfileUrl);
                }
                req.addHeader(xWapProfileTagName, xWapProfileUrl);
            }
        }

        // Extra http parameters. Split by '|' to get a list of value pairs.
        // Separate each pair by the first occurrence of ':' to obtain a name and
        // value. Replace the occurrence of the string returned by
        // MmsConfig.getHttpParamsLine1Key() with the users telephone number inside
        // the value.
        String extraHttpParams = MmsConfig.getHttpParams();

        if (extraHttpParams != null) {
            String line1Number = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE))
                    .getLine1Number();
            String line1Key = MmsConfig.getHttpParamsLine1Key();
            String paramList[] = extraHttpParams.split("\\|");

            for (String paramPair : paramList) {
                String splitPair[] = paramPair.split(":", 2);

                if (splitPair.length == 2) {
                    String name = splitPair[0].trim();
                    String value = splitPair[1].trim();

                    if (line1Key != null) {
                        value = value.replace(line1Key, line1Number);
                    }
                    if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) {
                        req.addHeader(name, value);
                    }
                }
            }
        }
        req.addHeader(HDR_KEY_ACCEPT_LANGUAGE, HDR_VALUE_ACCEPT_LANGUAGE);

        HttpResponse response = client.execute(target, req);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != 200) { // HTTP 200 is success.
            throw new IOException("HTTP error: " + status.getReasonPhrase());
        }

        HttpEntity entity = response.getEntity();
        byte[] body = null;
        if (entity != null) {
            try {
                if (entity.getContentLength() > 0) {
                    body = new byte[(int) entity.getContentLength()];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        dis.readFully(body);
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "Error closing input stream: " + e.getMessage());
                        }
                    }
                }
            } finally {
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        }
        return body;
    } catch (URISyntaxException e) {
        handleHttpConnectionException(e, url);
    } catch (IllegalStateException e) {
        handleHttpConnectionException(e, url);
    } catch (IllegalArgumentException e) {
        handleHttpConnectionException(e, url);
    } catch (SocketException e) {
        handleHttpConnectionException(e, url);
    } catch (Exception e) {
        handleHttpConnectionException(e, url);
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return null;
}

From source file:ws.wamp.jawampa.transport.WampClientChannelFactoryResolver.java

public static WampClientChannelFactory getFactory(final URI uri, final SslContext sslCtx)
        throws ApplicationError {
    String scheme = uri.getScheme();
    scheme = scheme != null ? scheme : "";

    if (scheme.equalsIgnoreCase("ws") || scheme.equalsIgnoreCase("wss")) {

        // Check the host and port field for validity
        if (uri.getHost() == null || uri.getPort() == 0) {
            throw new ApplicationError(ApplicationError.INVALID_URI);
        }//from   w  w w  . j  av  a2  s.com

        // Return a factory that creates a channel for websocket connections            
        return new WampClientChannelFactory() {
            @Override
            public ChannelFuture createChannel(final ChannelHandler handler, final EventLoopGroup eventLoop,
                    final ObjectMapper objectMapper) throws Exception {
                // Initialize SSL when required
                final boolean needSsl = uri.getScheme().equalsIgnoreCase("wss");
                final SslContext sslCtx0;
                if (needSsl && sslCtx == null) {
                    // Create a default SslContext when we got none provided through the constructor
                    try {
                        sslCtx0 = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
                    } catch (SSLException e) {
                        throw e;
                    }
                } else if (needSsl) {
                    sslCtx0 = sslCtx;
                } else {
                    sslCtx0 = null;
                }

                // Use well-known ports if not explicitly specified
                final int port;
                if (uri.getPort() == -1) {
                    if (needSsl)
                        port = 443;
                    else
                        port = 80;
                } else
                    port = uri.getPort();

                final WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri,
                        WebSocketVersion.V13, WampHandlerConfiguration.WAMP_WEBSOCKET_PROTOCOLS, false,
                        new DefaultHttpHeaders());

                Bootstrap b = new Bootstrap();
                b.group(eventLoop).channel(NioSocketChannel.class)
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel ch) {
                                ChannelPipeline p = ch.pipeline();
                                if (sslCtx0 != null) {
                                    p.addLast(sslCtx0.newHandler(ch.alloc(), uri.getHost(), port));
                                }
                                p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192),
                                        new WebSocketClientProtocolHandler(handshaker, false),
                                        new WebSocketFrameAggregator(
                                                WampHandlerConfiguration.MAX_WEBSOCKET_FRAME_SIZE),
                                        new WampClientWebsocketHandler(handshaker, objectMapper), handler);
                            }
                        });

                return b.connect(uri.getHost(), port);
            }
        };
    }

    throw new ApplicationError(ApplicationError.INVALID_URI);
}

From source file:com.collective.celos.Util.java

public static String augmentHdfsPath(String hdfsPrefix, String path) throws URISyntaxException {

    if (hdfsPrefix.isEmpty() || hdfsPrefix.equals("/")) {
        return path;
    }// www  . j  a va  2s  .  c  o m

    for (String ch : conversions.keySet()) {
        path = path.replace(ch.toString(), conversions.get(ch).toString());
    }
    URI oldUri = URI.create(path);

    String host = oldUri.getHost();
    if (oldUri.getRawSchemeSpecificPart().startsWith("///") && host == null) {
        host = "";
    }

    URI newUri = new URI(oldUri.getScheme(), oldUri.getUserInfo(), host, oldUri.getPort(),
            hdfsPrefix + oldUri.getPath(), oldUri.getQuery(), oldUri.getFragment());
    path = newUri.toString();
    for (String ch : backConversions.keySet()) {
        path = path.replace(ch.toString(), backConversions.get(ch).toString());
    }
    return path;
}

From source file:org.springframework.xd.dirt.integration.bus.rabbit.RabbitBusCleaner.java

@VisibleForTesting
static RestTemplate buildRestTemplate(String adminUri, String user, String password) {
    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(user, password));
    HttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    // Set up pre-emptive basic Auth because the rabbit plugin doesn't currently support challenge/response for PUT
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local; from the apache docs...
    // auth cache
    BasicScheme basicAuth = new BasicScheme();
    URI uri;/* w  ww. j  a v  a  2  s.com*/
    try {
        uri = new URI(adminUri);
    } catch (URISyntaxException e) {
        throw new RabbitAdminException("Invalid URI", e);
    }
    authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), basicAuth);
    // Add AuthCache to the execution context
    final HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient) {

        @Override
        protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
            return localContext;
        }

    });
    restTemplate.setMessageConverters(
            Collections.<HttpMessageConverter<?>>singletonList(new MappingJackson2HttpMessageConverter()));
    return restTemplate;
}

From source file:com.aliyun.oss.integrationtests.TestUtils.java

public static String composeLocation(String endpoint, String bucketName, String key) {
    try {/*  w w w  .  j ava 2s . com*/
        URI baseUri = URI.create(endpoint);
        URI resultUri = new URI(baseUri.getScheme(), null, bucketName + "." + baseUri.getHost(),
                baseUri.getPort(), String.format("/%s", HttpUtil.urlEncode(key, DEFAULT_CHARSET_NAME)), null,
                null);
        return URLDecoder.decode(resultUri.toString(), DEFAULT_CHARSET_NAME);
    } catch (Exception e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    }
}

From source file:com.ibm.watson.developer_cloud.professor_languo.ingestion.RankerCreationUtil.java

/**
 * //w ww  .  ja va  2 s .  c om
 * @param uri
 * @param username
 * @param password
 * @return
 */
public static HttpClient createHttpClient(String uri, String username, String password) {
    final URI scopeUri = URI.create(uri);

    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());
    builder.setDefaultCredentialsProvider(credentialsProvider);

    return builder.build();
}

From source file:com.code4bones.utils.HttpUtils.java

/**
 * A helper method to send or retrieve data through HTTP protocol.
 *
 * @param token The token to identify the sending progress.
 * @param url The URL used in a GET request. Null when the method is
 *         HTTP_POST_METHOD.//from  w  w w.  j  av a 2 s .  com
 * @param pdu The data to be POST. Null when the method is HTTP_GET_METHOD.
 * @param method HTTP_POST_METHOD or HTTP_GET_METHOD.
 * @return A byte array which contains the response data.
 *         If an HTTP error code is returned, an IOException will be thrown.
 * @throws IOException if any error occurred on network interface or
 *         an HTTP error code(&gt;=400) returned from the server.
 */
public static byte[] httpConnection(Context context, long token, String url, byte[] pdu, int method,
        boolean isProxySet, String proxyHost, int proxyPort) throws IOException {
    if (url == null) {
        throw new IllegalArgumentException("URL must not be null.");
    }

    NetLog.v("httpConnection: params list");
    NetLog.v("\ttoken\t\t= " + token);
    NetLog.v("\turl\t\t= " + url);
    NetLog.v("\tmethod\t\t= "
            + ((method == HTTP_POST_METHOD) ? "POST" : ((method == HTTP_GET_METHOD) ? "GET" : "UNKNOWN")));
    NetLog.v("\tisProxySet\t= " + isProxySet);
    NetLog.v("\tproxyHost\t= " + proxyHost);
    NetLog.v("\tproxyPort\t= " + proxyPort);
    //Log.v(TAG, "\tpdu\t\t= " + Arrays.toString(pdu));

    AndroidHttpClient client = null;

    try {
        // Make sure to use a proxy which supports CONNECT.
        URI hostUrl = new URI(url);
        HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);

        client = createHttpClient(context);
        HttpRequest req = null;
        switch (method) {
        case HTTP_POST_METHOD:
            ProgressCallbackEntity entity = new ProgressCallbackEntity(context, token, pdu);
            // Set request content type.
            entity.setContentType("application/vnd.wap.mms-message");

            HttpPost post = new HttpPost(url);
            post.setEntity(entity);
            req = post;
            break;
        case HTTP_GET_METHOD:
            req = new HttpGet(url);
            break;
        default:
            Log.e(TAG, "Unknown HTTP method: " + method + ". Must be one of POST[" + HTTP_POST_METHOD
                    + "] or GET[" + HTTP_GET_METHOD + "].");
            return null;
        }

        // Set route parameters for the request.
        HttpParams params = client.getParams();
        if (isProxySet) {
            ConnRouteParams.setDefaultProxy(params, new HttpHost(proxyHost, proxyPort));
        }
        req.setParams(params);

        // Set necessary HTTP headers for MMS transmission.
        req.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT);
        {
            //TODO: MmsConfig.getUaProfTagName();
            String xWapProfileTagName = "x-wap-profile";//MmsConfig.getUaProfTagName();
            String xWapProfileUrl = "mms.beeline.ru"; //MmsConfig.getUaProfUrl();

            if (xWapProfileUrl != null) {
                NetLog.v("[HttpUtils] httpConn: xWapProfUrl=" + xWapProfileUrl);
            }
            req.addHeader(xWapProfileTagName, xWapProfileUrl);
        }

        // Extra http parameters. Split by '|' to get a list of value pairs.
        // Separate each pair by the first occurrence of ':' to obtain a name and
        // value. Replace the occurrence of the string returned by
        // MmsConfig.getHttpParamsLine1Key() with the users telephone number inside
        // the value.
        //TODO: MmsConfig.getHttpParams();
        String extraHttpParams = null; //MmsConfig.getHttpParams();

        if (extraHttpParams != null) {
            String line1Number = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE))
                    .getLine1Number();
            String line1Key = "key"; //MmsConfig.getHttpParamsLine1Key();
            String paramList[] = extraHttpParams.split("\\|");

            for (String paramPair : paramList) {
                String splitPair[] = paramPair.split(":", 2);

                if (splitPair.length == 2) {
                    String name = splitPair[0].trim();
                    String value = splitPair[1].trim();

                    if (line1Key != null) {
                        value = value.replace(line1Key, line1Number);
                    }
                    if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) {
                        req.addHeader(name, value);
                    }
                }
            }
        }
        req.addHeader(HDR_KEY_ACCEPT_LANGUAGE, HDR_VALUE_ACCEPT_LANGUAGE);

        HttpResponse response = client.execute(target, req);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != 200) { // HTTP 200 is success.
            throw new IOException("HTTP error: " + status.getReasonPhrase());
        }

        HttpEntity entity = response.getEntity();
        byte[] body = null;
        if (entity != null) {
            try {
                if (entity.getContentLength() > 0) {
                    body = new byte[(int) entity.getContentLength()];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        dis.readFully(body);
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "Error closing input stream: " + e.getMessage());
                        }
                    }
                }
                if (entity.isChunked()) {
                    Log.v(TAG, "httpConnection: transfer encoding is chunked");
                    //TODO: MmsConfig.getMaxMessageSize();
                    int bytesTobeRead = 4096; //MmsConfig.getMaxMessageSize();
                    byte[] tempBody = new byte[bytesTobeRead];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        int bytesRead = 0;
                        int offset = 0;
                        boolean readError = false;
                        do {
                            try {
                                bytesRead = dis.read(tempBody, offset, bytesTobeRead);
                            } catch (IOException e) {
                                readError = true;
                                Log.e(TAG, "httpConnection: error reading input stream" + e.getMessage());
                                break;
                            }
                            if (bytesRead > 0) {
                                bytesTobeRead -= bytesRead;
                                offset += bytesRead;
                            }
                        } while (bytesRead >= 0 && bytesTobeRead > 0);
                        if (bytesRead == -1 && offset > 0 && !readError) {
                            // offset is same as total number of bytes read
                            // bytesRead will be -1 if the data was read till the eof
                            body = new byte[offset];
                            System.arraycopy(tempBody, 0, body, 0, offset);
                            Log.v(TAG, "httpConnection: Chunked response length [" + Integer.toString(offset)
                                    + "]");
                        } else {
                            Log.e(TAG, "httpConnection: Response entity too large or empty");
                        }
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "Error closing input stream: " + e.getMessage());
                        }
                    }
                }
            } finally {
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        }
        return body;
    } catch (URISyntaxException e) {
        handleHttpConnectionException(e, url);
    } catch (IllegalStateException e) {
        handleHttpConnectionException(e, url);
    } catch (IllegalArgumentException e) {
        handleHttpConnectionException(e, url);
    } catch (SocketException e) {
        handleHttpConnectionException(e, url);
    } catch (Exception e) {
        handleHttpConnectionException(e, url);
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return null;
}

From source file:org.apache.jena.jdbc.remote.RemoteEndpointDriver.java

/**
 * Get the URI with irrelevant components (Fragment and Querystring)
 * stripped off/*from ww  w .  j a  v  a 2 s.  c  o m*/
 * 
 * @param input
 *            URI
 * @return URI with irrelevant components stripped off or null if stripping
 *         is impossible
 */
private static String stripIrrelevantComponents(String input) {
    try {
        URI orig = new URI(input);
        return new URI(orig.getScheme(), orig.getUserInfo(), orig.getHost(), orig.getPort(), orig.getPath(),
                null, null).toString();
    } catch (URISyntaxException e) {
        return null;
    }
}