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:com.dmsl.anyplace.utils.NetworkUtils.java

public static String encodeURL(String urlStr) throws URISyntaxException, MalformedURLException {
    URL url = new URL(urlStr);
    URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
            url.getQuery(), url.getRef());
    url = uri.toURL();/*from w  w w .java  2  s  .  c  o m*/
    return url.toString();
}

From source file:com.doculibre.constellio.utils.ConnectorManagerRequestUtils.java

public static Element sendGet(ConnectorManager connectorManager, String servletPath,
        Map<String, String> paramsMap) {
    if (paramsMap == null) {
        paramsMap = new HashMap<String, String>();
    }/*  www.j a v a 2 s  . com*/

    try {
        HttpParams params = new BasicHttpParams();
        for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
            String paramName = (String) it.next();
            String paramValue = (String) paramsMap.get(paramName);
            params.setParameter(paramName, paramValue);
        }

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
        HttpProtocolParams.setUseExpectContinue(params, true);

        BasicHttpProcessor 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());

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

        HttpContext context = new BasicHttpContext(null);
        URL connectorManagerURL = new URL(connectorManager.getUrl());
        HttpHost host = new HttpHost(connectorManagerURL.getHost(), connectorManagerURL.getPort());

        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
        ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

        try {
            String target = connectorManager.getUrl() + servletPath;
            boolean firstParam = true;
            for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
                String paramName = (String) it.next();
                String paramValue = (String) paramsMap.get(paramName);

                if (firstParam) {
                    target += "?";
                    firstParam = false;
                } else {
                    target += "&";
                }
                target += paramName + "=" + paramValue;
            }

            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("GET", target);
            LOGGER.fine(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            LOGGER.fine("<< Response: " + response.getStatusLine());
            String entityText = EntityUtils.toString(response.getEntity());
            LOGGER.fine(entityText);
            LOGGER.fine("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                LOGGER.fine("Connection kept alive...");
            }

            try {
                Document xml = DocumentHelper.parseText(entityText);
                return xml.getRootElement();
            } catch (Exception e) {
                LOGGER.severe("Error caused by text : " + entityText);
                throw e;
            }
        } finally {
            conn.close();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.doculibre.constellio.opensearch.OpenSearchSolrServer.java

public static Element sendGet(String openSearchServerURLStr, Map<String, String> paramsMap) {
    if (paramsMap == null) {
        paramsMap = new HashMap<String, String>();
    }//from w  w  w  .j  a v  a 2 s  .co  m

    try {
        HttpParams params = new BasicHttpParams();
        for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
            String paramName = (String) it.next();
            String paramValue = (String) paramsMap.get(paramName);
            params.setParameter(paramName, paramValue);
        }

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, CharSetUtils.UTF_8);
        HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
        HttpProtocolParams.setUseExpectContinue(params, true);

        BasicHttpProcessor 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());

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

        HttpContext context = new BasicHttpContext(null);
        URL openSearchServerURL = new URL(openSearchServerURLStr);
        String host = openSearchServerURL.getHost();
        int port = openSearchServerURL.getPort();
        if (port == -1) {
            port = 80;
        }
        HttpHost httpHost = new HttpHost(host, port);

        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
        ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, httpHost);

        try {
            boolean firstParam = true;
            for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
                String paramName = (String) it.next();
                String paramValue = (String) paramsMap.get(paramName);
                if (paramValue != null) {
                    try {
                        paramValue = URLEncoder.encode(paramValue, CharSetUtils.ISO_8859_1);
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }
                }

                if (firstParam) {
                    openSearchServerURLStr += "?";
                    firstParam = false;
                } else {
                    openSearchServerURLStr += "&";
                }
                openSearchServerURLStr += paramName + "=" + paramValue;
            }

            if (!conn.isOpen()) {
                Socket socket = new Socket(host, port);
                conn.bind(socket, params);
            }
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("GET",
                    openSearchServerURLStr);
            LOGGER.fine(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            LOGGER.fine("<< Response: " + response.getStatusLine());
            String entityText = EntityUtils.toString(response.getEntity());
            LOGGER.fine(entityText);
            LOGGER.fine("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                LOGGER.fine("Connection kept alive...");
            }

            try {
                Document xml = DocumentHelper.parseText(entityText);
                return xml.getRootElement();
            } catch (RuntimeException e) {
                LOGGER.severe("Error caused by text : " + entityText);
                throw e;
            }
        } finally {
            conn.close();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:lucee.commons.net.http.httpclient3.HTTPEngine3Impl.java

/**
 * FUNKTIONIERT NICHT, HOST WIRD NICHT UEBERNOMMEN
 * Clones a http method and sets a new url
 * @param src//from   ww w . j  a v  a  2 s . co m
 * @param url
 * @return
 */
private static HttpMethod clone(HttpMethod src, URL url) {
    HttpMethod trg = HttpMethodCloner.clone(src);
    HostConfiguration trgConfig = trg.getHostConfiguration();
    trgConfig.setHost(url.getHost(), url.getPort(), url.getProtocol());
    trg.setPath(url.getPath());
    trg.setQueryString(url.getQuery());

    return trg;
}

From source file:com.hypersocket.client.hosts.HostsFileManager.java

public static URL sanitizeURL(String url) throws MalformedURLException {

    URL u = new URL(url);
    String hostname = IPAddressValidator.getInstance().getGuaranteedHostname(u.getHost());
    return new URL(u.getProtocol(), hostname, u.getPort(), u.getFile());
}

From source file:org.eclipse.wst.json.core.internal.download.HttpClientProvider.java

private static File download(File file, URL url) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    OutputStream out = null;//from  www  . j  av a 2 s.  c o m
    file.getParentFile().mkdirs();
    try {
        HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        Builder builder = RequestConfig.custom();
        HttpHost proxy = getProxy(target);
        if (proxy != null) {
            builder = builder.setProxy(proxy);
        }
        RequestConfig config = builder.build();
        HttpGet request = new HttpGet(url.toURI());
        request.setConfig(config);
        response = httpclient.execute(target, request);
        InputStream in = response.getEntity().getContent();
        out = new BufferedOutputStream(new FileOutputStream(file));
        copy(in, out);
        return file;
    } catch (Exception e) {
        logWarning(e);
        ;
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
            }
        }
        try {
            httpclient.close();
        } catch (IOException e) {
        }
    }
    return null;
}

From source file:org.pentaho.reporting.designer.extensions.pentaho.drilldown.PentahoParameterRefreshHandler.java

private static String getParameterServicePath(final AuthenticationData loginData,
        final PentahoPathModel pathModel) {
    try {/*  ww  w. ja  v  a2s.c  o  m*/
        final FileObject fileSystemRoot = PublishUtil.createVFSConnection(VFS.getManager(), loginData);
        final FileSystem fileSystem = fileSystemRoot.getFileSystem();

        // as of version 3.7 we do not need to check anything other than that the version information is there
        // later we may have to add additional checks in here to filter out known broken versions.

        final String localPath = pathModel.getLocalPath();
        final FileObject object = fileSystemRoot.resolveFile(localPath);
        final FileContent content = object.getContent();
        final String majorVersionText = (String) fileSystem.getAttribute(WebSolutionFileSystem.MAJOR_VERSION);

        if (StringUtils.isEmpty(majorVersionText) == false) {
            final String paramService = (String) content.getAttribute("param-service-url");
            if (StringUtils.isEmpty(paramService)) {
                return null;
            }
            if (paramService.startsWith("http://") || paramService.startsWith("https://")) {
                return paramService;
            }

            try {
                // Encode the URL (must use URI as URL encoding doesn't work on spaces correctly)
                final URL target = new URL(loginData.getUrl());
                final String host;
                if (target.getPort() != -1) {
                    host = target.getHost() + ":" + target.getPort();
                } else {
                    host = target.getHost();
                }

                return target.getProtocol() + "://" + host + paramService;
            } catch (MalformedURLException e) {
                UncaughtExceptionsModel.getInstance().addException(e);
                return null;
            }
        }

        final String extension = IOUtils.getInstance().getFileExtension(localPath);
        if (".prpt".equals(extension)) {
            logger.debug(
                    "Ancient pentaho system detected: parameter service does not deliver valid parameter values");

            final String name = pathModel.getName();
            final String path = pathModel.getPath();
            final String solution = pathModel.getSolution();

            final FastMessageFormat messageFormat = new FastMessageFormat(
                    "/content/reporting/?renderMode=XML&amp;solution={0}&amp;path={1}&amp;name={2}");
            messageFormat.setNullString("");
            return loginData.getUrl() + messageFormat.format(new Object[] { solution, path, name });
        }

        logger.debug("Ancient pentaho system detected: We will not have access to a working parameter service");
        return null;
    } catch (FileSystemException e) {
        UncaughtExceptionsModel.getInstance().addException(e);
        return null;
    }
}

From source file:edu.kit.dama.staging.entities.AdalapiProtocolConfiguration.java

/**
 * Get the unique protocol identifier for the provided Url. The identifier
 * is generated using the schema:/*from w  ww .  j a  v a2s .  co  m*/
 *
 * protocol[@host][:port]
 *
 * Valid identifiers according to this schema are e.g. http@myHost;
 * http@myHost:8080; ftp@anotherHost; file
 *
 * As there is no host/port information for Urls accessed via file protocol,
 * there is only one valid identifier for file Urls.
 *
 * @param pUrl A sample URL (protocol and authority are sufficient, e.g.
 * http://remoteHost:8080) as it should be accessed by the provided protocol
 * implementation.
 *
 * @return The identifier string.
 */
public final static String getProtocolIdentifier(URL pUrl) {
    String protocol = pUrl.getProtocol();
    if (protocol == null) {
        throw new IllegalArgumentException("The provided Url " + pUrl + " has no protocol specified.");
    }
    String host = pUrl.getHost();
    int port = pUrl.getPort();

    if (host == null) {
        return protocol;
    } else {
        return protocol + "@" + host + ((port > -1) ? ":" + Integer.toString(port) : "");
    }
}

From source file:com.mindquarry.desktop.util.HttpUtilities.java

private static HttpClient createHttpClient(String login, String pwd, String address)
        throws MalformedURLException {
    URL url = new URL(address);

    HttpClient client = new HttpClient();
    client.getParams().setSoTimeout(SOCKET_TIMEOUT);
    client.getParams().setParameter("http.connection.timeout", CONNECTION_TIMEOUT);
    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM),
            new UsernamePasswordCredentials(login, pwd));

    // apply proxy settings if necessary
    if ((store != null) && (store.getBoolean(ProxySettingsPage.PREF_PROXY_ENABLED))) {
        URL proxyUrl = new URL(store.getString(ProxySettingsPage.PREF_PROXY_URL));
        String proxyLogin = store.getString(ProxySettingsPage.PREF_PROXY_LOGIN);
        String proxyPwd = store.getString(ProxySettingsPage.PREF_PROXY_PASSWORD);

        client.getHostConfiguration().setProxy(proxyUrl.getHost(), proxyUrl.getPort());
        client.getState().setProxyCredentials(new AuthScope(proxyUrl.getHost(), proxyUrl.getPort()),
                new UsernamePasswordCredentials(proxyLogin, proxyPwd));
    }/* w ww.  j a  v  a2 s . co m*/
    return client;
}

From source file:crow.weibo.util.WeiboUtil.java

/**
 * ?URL,URL Path URL ???/*from   www.jav  a 2s. com*/
 * 
 * @param url
 * @return
 */
public static String getNormalizedUrl(String url) {
    try {
        URL ul = new URL(url);
        StringBuilder buf = new StringBuilder();
        buf.append(ul.getProtocol());
        buf.append("://");
        buf.append(ul.getHost());
        if ((ul.getProtocol().equals("http") || ul.getProtocol().equals("https")) && ul.getPort() != -1) {
            buf.append(":");
            buf.append(ul.getPort());
        }
        buf.append(ul.getPath());
        return buf.toString();
    } catch (Exception e) {
    }
    return null;
}