Example usage for java.net URL getPort

List of usage examples for java.net URL getPort

Introduction

In this page you can find the example usage for java.net URL getPort.

Prototype

public int getPort() 

Source Link

Document

Gets the port number of this URL .

Usage

From source file:it.geosolutions.geoserver.rest.HTTPUtils.java

private static void setAuth(HttpClient client, String url, String username, String pw)
        throws MalformedURLException {
    URL u = new URL(url);
    if (username != null && pw != null) {
        Credentials defaultcreds = new UsernamePasswordCredentials(username, pw);
        client.getState().setCredentials(new AuthScope(u.getHost(), u.getPort()), defaultcreds);
        client.getParams().setAuthenticationPreemptive(true); // GS2 by
                                                              // default
                                                              // always
                                                              // requires
                                                              // authentication
    } else {/*from w  w w . j  av a2s.  co m*/
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Not setting credentials to access to " + url);
        }
    }
}

From source file:sce.RESTAppMetricJob.java

public static URL convertToURLEscapingIllegalCharacters(String string) {
    try {/*from  w ww .  j  av a2s. c  o m*/
        String decodedURL = URLDecoder.decode(string, "UTF-8");
        URL url = new URL(decodedURL);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        return uri.toURL();
    } catch (MalformedURLException | URISyntaxException | UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:io.fabric8.apiman.ApimanStarter.java

private static URL waitForDependency(URL url, String path, String serviceName, String key, String value,
        String username, String password) throws InterruptedException {
    boolean isFoundRunningService = false;
    ObjectMapper mapper = new ObjectMapper();
    int counter = 0;
    URL endpoint = null;//w ww .jav a  2  s.  c  om
    while (!isFoundRunningService) {
        endpoint = resolveServiceEndpoint(url.getProtocol(), url.getHost(), String.valueOf(url.getPort()));
        if (endpoint != null) {
            String isLive = null;
            try {
                URL statusURL = new URL(endpoint.toExternalForm() + path);
                HttpURLConnection urlConnection = (HttpURLConnection) statusURL.openConnection();
                urlConnection.setConnectTimeout(500);
                if (urlConnection instanceof HttpsURLConnection) {
                    try {
                        KeyStoreUtil.Info tPathInfo = new KeyStoreUtil().new Info(ApimanStarter.TRUSTSTORE_PATH,
                                ApimanStarter.TRUSTSTORE_PASSWORD_PATH);
                        TrustManager[] tms = KeyStoreUtil.getTrustManagers(tPathInfo);
                        KeyStoreUtil.Info kPathInfo = new KeyStoreUtil().new Info(
                                ApimanStarter.CLIENT_KEYSTORE_PATH,
                                ApimanStarter.CLIENT_KEYSTORE_PASSWORD_PATH);
                        KeyManager[] kms = KeyStoreUtil.getKeyManagers(kPathInfo);
                        final SSLContext sc = SSLContext.getInstance("TLS");
                        sc.init(kms, tms, new java.security.SecureRandom());
                        final SSLSocketFactory socketFactory = sc.getSocketFactory();
                        HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
                        HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
                        httpsConnection.setHostnameVerifier(new DefaultHostnameVerifier());
                        httpsConnection.setSSLSocketFactory(socketFactory);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        throw e;
                    }
                }
                if (Utils.isNotNullOrEmpty(username)) {
                    String encoded = Base64.getEncoder()
                            .encodeToString((username + ":" + password).getBytes("UTF-8"));
                    urlConnection.setRequestProperty("Authorization", "Basic " + encoded);
                    log.info(username + ":" + "*****");
                }
                isLive = IOUtils.toString(urlConnection.getInputStream());
                Map<String, Object> esResponse = mapper.readValue(isLive,
                        new TypeReference<Map<String, Object>>() {
                        });
                if (esResponse.containsKey(key) && value.equals(String.valueOf(esResponse.get(key)))) {
                    isFoundRunningService = true;
                } else {
                    if (counter % 10 == 0)
                        log.info(endpoint.toExternalForm() + " not yet up. " + isLive);
                }
            } catch (Exception e) {
                if (counter % 10 == 0)
                    log.info(endpoint.toExternalForm() + " not yet up. " + e.getMessage());
            }
        } else {
            if (counter % 10 == 0)
                log.info("Could not find " + serviceName + " in namespace, waiting..");
        }
        counter++;
        Thread.sleep(1000l);
    }
    return endpoint;
}

From source file:com.liferay.ide.server.remote.RemoteLogStream.java

protected static InputStream openInputStream(IServerManagerConnection remote, URL url) throws IOException {
    String username = remote.getUsername();
    String password = remote.getPassword();

    String authString = username + ":" + password; //$NON-NLS-1$
    byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
    String authStringEnc = new String(authEncBytes);
    final IProxyService proxyService = LiferayCore.getProxyService();
    URLConnection conn = null;/*  w w w.  j  av  a 2  s.c  o m*/

    try {
        URI uri = new URI("HTTP://" + url.getHost() + ":" + url.getPort()); //$NON-NLS-1$ //$NON-NLS-2$
        IProxyData[] proxyDataForHost = proxyService.select(uri);

        for (IProxyData data : proxyDataForHost) {
            if (data.getHost() != null) {
                System.setProperty("http.proxyHost", data.getHost()); //$NON-NLS-1$
                System.setProperty("http.proxyPort", String.valueOf(data.getPort())); //$NON-NLS-1$

                break;
            }
        }

        uri = new URI("SOCKS://" + url.getHost() + ":" + url.getPort()); //$NON-NLS-1$ //$NON-NLS-2$
        proxyDataForHost = proxyService.select(uri);

        for (IProxyData data : proxyDataForHost) {
            if (data.getHost() != null) {
                System.setProperty("socksProxyHost", data.getHost()); //$NON-NLS-1$
                System.setProperty("socksProxyPort", String.valueOf(data.getPort())); //$NON-NLS-1$

                break;
            }
        }
    } catch (URISyntaxException e) {
        LiferayServerCore.logError("Could not read proxy data", e); //$NON-NLS-1$
    }

    conn = url.openConnection();
    conn.setRequestProperty("Authorization", "Basic " + authStringEnc); //$NON-NLS-1$ //$NON-NLS-2$
    Authenticator.setDefault(null);
    conn.setAllowUserInteraction(false);

    return conn.getInputStream();
}

From source file:com.eviware.soapui.support.Tools.java

public static String getEndpointFromUrl(URL baseUrl) {
    StringBuilder result = new StringBuilder();
    result.append(baseUrl.getProtocol()).append("://");
    result.append(baseUrl.getHost());/*from   w  w  w  . j  a  v  a2 s  .c o  m*/
    if (baseUrl.getPort() > 0) {
        result.append(':').append(baseUrl.getPort());
    }

    return result.toString();
}

From source file:org.apache.taverna.activities.rest.HTTPRequestHandler.java

/**
 * This method is the entry point to the invocation of a remote REST
 * service. It accepts a number of parameters from the related REST activity
 * and uses those to assemble, execute and fetch results of a relevant HTTP
 * request.//from   w w w.ja  v a2 s  .  co  m
 *
 * @param requestURL
 *            The URL for the request to be made. This cannot be taken from
 *            the <code>configBean</code>, because this should be the
 *            complete URL which may be directly used to make the request (
 *            <code>configBean</code> would only contain the URL signature
 *            associated with the REST activity).
 * @param configBean
 *            Configuration of the associated REST activity is passed to
 *            this class as a configuration bean. Settings such as HTTP
 *            method, MIME types for "Content-Type" and "Accept" headers,
 *            etc are taken from the bean.
 * @param inputMessageBody
 *            Body of the message to be sent to the server - only needed for
 *            POST and PUT requests; for GET and DELETE it will be
 *            discarded.
 * @return
 */
@SuppressWarnings("deprecation")
public static HTTPRequestResponse initiateHTTPRequest(String requestURL,
        RESTActivityConfigurationBean configBean, Object inputMessageBody, Map<String, String> urlParameters,
        CredentialsProvider credentialsProvider) {
    ClientConnectionManager connectionManager = null;
    if (requestURL.toLowerCase().startsWith("https")) {
        // Register a protocol scheme for https that uses Taverna's
        // SSLSocketFactory
        try {
            URL url = new URL(requestURL); // the URL object which will
            // parse the port out for us
            int port = url.getPort();
            if (port == -1) // no port was defined in the URL
                port = HTTPS_DEFAULT_PORT; // default HTTPS port
            Scheme https = new Scheme("https",
                    new org.apache.http.conn.ssl.SSLSocketFactory(SSLContext.getDefault()), port);
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(https);
            connectionManager = new SingleClientConnManager(null, schemeRegistry);
        } catch (MalformedURLException ex) {
            logger.error("Failed to extract port from the REST service URL: the URL " + requestURL
                    + " is malformed.", ex);
            // This will cause the REST activity to fail but this method
            // seems not to throw an exception so we'll just log the error
            // and let it go through
        } catch (NoSuchAlgorithmException ex2) {
            // This will cause the REST activity to fail but this method
            // seems not to throw an exception so we'll just log the error
            // and let it go through
            logger.error("Failed to create SSLContext for invoking the REST service over https.", ex2);
        }
    }

    switch (configBean.getHttpMethod()) {
    case GET:
        return doGET(connectionManager, requestURL, configBean, urlParameters, credentialsProvider);
    case POST:
        return doPOST(connectionManager, requestURL, configBean, inputMessageBody, urlParameters,
                credentialsProvider);
    case PUT:
        return doPUT(connectionManager, requestURL, configBean, inputMessageBody, urlParameters,
                credentialsProvider);
    case DELETE:
        return doDELETE(connectionManager, requestURL, configBean, urlParameters, credentialsProvider);
    default:
        return new HTTPRequestResponse(new Exception(
                "Error: something went wrong; " + "no failure has occurred, but but unexpected HTTP method (\""
                        + configBean.getHttpMethod() + "\") encountered."));
    }
}

From source file:com.icesoft.faces.webapp.parser.JspPageToDocument.java

/**
 * Construct a full URL to the specified path given the URL
 * to some other resource in the bundle//  w  w  w.  j  a  v  a 2s . co m
 *
 * @param url
 * @param path
 * @return locaion
 */

private static String[] getBundleLocation(URL url, String path) {
    String protocol = url.getProtocol();
    String host = url.getHost();
    String port = String.valueOf(url.getPort());
    String urlString = protocol + "://" + host + ":" + port + "/" + path;
    return new String[] { urlString, null };
}

From source file:UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified host.
 * @param u the URL on which to base the returned URL
 * @param newHost the new host to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified host
 * @throws MalformedURLException if there is a problem creating the new URL
 *//* www .  j av a2s.c o m*/
public static URL getUrlWithNewHost(final URL u, final String newHost) throws MalformedURLException {
    return createNewUrl(u.getProtocol(), newHost, u.getPort(), u.getPath(), u.getRef(), u.getQuery());
}

From source file:UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified reference.
 * @param u the URL on which to base the returned URL
 * @param newRef the new reference to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified reference
 * @throws MalformedURLException if there is a problem creating the new URL
 *///from w  ww  . j  a v a 2s  .  c om
public static URL getUrlWithNewRef(final URL u, final String newRef) throws MalformedURLException {
    return createNewUrl(u.getProtocol(), u.getHost(), u.getPort(), u.getPath(), newRef, u.getQuery());
}

From source file:UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified protocol.
 * @param u the URL on which to base the returned URL
 * @param newProtocol the new protocol to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified protocol
 * @throws MalformedURLException if there is a problem creating the new URL
 *//*from ww w  .  ja  va  2 s.c  o m*/
public static URL getUrlWithNewProtocol(final URL u, final String newProtocol) throws MalformedURLException {
    return createNewUrl(newProtocol, u.getHost(), u.getPort(), u.getPath(), u.getRef(), u.getQuery());
}