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:fr.dutra.confluence2wordpress.xmlrpc.CommonsXmlRpcTransportFactory.java

public CommonsXmlRpcTransportFactory(URL url, String proxyHost, int proxyPort, int maxConnections) {
    this.url = url;
    HostConfiguration hostConf = new HostConfiguration();
    hostConf.setHost(url.getHost(), url.getPort());
    if (proxyHost != null && proxyPort != -1) {
        hostConf.setProxy(proxyHost, proxyPort);
    }/* w  ww . jav  a 2s .  c om*/
    HttpConnectionManagerParams connParam = new HttpConnectionManagerParams();
    connParam.setMaxConnectionsPerHost(hostConf, maxConnections);
    connParam.setMaxTotalConnections(maxConnections);
    MultiThreadedHttpConnectionManager conMgr = new MultiThreadedHttpConnectionManager();
    conMgr.setParams(connParam);
    client = new HttpClient(conMgr);
    client.setHostConfiguration(hostConf);
}

From source file:top.lionxxw.zuulservice.filter.BookingCarRoutingFilter.java

/**
 * This method allows to set the route host into the Zuul request context provided as parameter.
 * The url is extracted from the orginal request and the host is extracted from it.
 *
 * @param ctx Zuul//from  w w  w .  j  a  v  a2 s .c om
 *
 * @throws MalformedURLException
 */
private void setRouteHost(RequestContext ctx) throws MalformedURLException {

    String urlS = ctx.getRequest().getRequestURL().toString();
    URL url = new URL(urlS);
    String protocol = url.getProtocol();
    String rootHost = url.getHost();
    int port = url.getPort();
    String portS = (port > 0 ? ":" + port : "");
    ctx.setRouteHost(new URL(protocol + "://" + rootHost + portS));

}

From source file:edu.uci.ics.crawler4j.robotstxt.RobotstxtServer.java

private HostDirectives fetchDirectives(URL url) {
    WebURL robotsTxtUrl = new WebURL();
    String host = getHost(url);/* w w  w.  j a  va  2 s . co m*/
    String port = (url.getPort() == url.getDefaultPort() || url.getPort() == -1) ? "" : ":" + url.getPort();
    robotsTxtUrl.setURL("http://" + host + port + "/robots.txt");
    HostDirectives directives = null;
    PageFetchResult fetchResult = null;
    try {
        fetchResult = pageFetcher.fetchHeader(robotsTxtUrl);
        if (fetchResult.getStatusCode() == HttpStatus.SC_OK) {
            Page page = new Page(robotsTxtUrl);
            fetchResult.fetchContent(page);
            if (Util.hasPlainTextContent(page.getContentType())) {
                try {
                    String content;
                    if (page.getContentCharset() == null) {
                        content = new String(page.getContentData());
                    } else {
                        content = new String(page.getContentData(), page.getContentCharset());
                    }
                    directives = RobotstxtParser.parse(content, config.getUserAgentName());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    } finally {
        if (fetchResult != null) {
            fetchResult.discardContentIfNotConsumed();
        }
    }
    if (directives == null) {
        // We still need to have this object to keep track of the time we //
        // fetched it
        directives = new HostDirectives();
    }
    synchronized (host2directivesCache) {
        if (host2directivesCache.size() == config.getCacheSize()) {
            String minHost = null;
            long minAccessTime = Long.MAX_VALUE;
            for (Entry<String, HostDirectives> entry : host2directivesCache.entrySet()) {
                if (entry.getValue().getLastAccessTime() < minAccessTime) {
                    minAccessTime = entry.getValue().getLastAccessTime();
                    minHost = entry.getKey();
                }
            }
            host2directivesCache.remove(minHost);
        }
        host2directivesCache.put(host, directives);
    }
    return directives;
}

From source file:com.blackducksoftware.tools.scmconnector.integrations.mercurial.MercurialConnector.java

/**
 * Constructs a valid HTTP url if a user *and* password is provided.
 *
 * @throws Exception//  w w  w  . j ava  2 s . co  m
 */
private void buildURL() throws Exception {
    if (StringUtils.isNotEmpty(user) && StringUtils.isNotEmpty(password)) {
        URL url = new URL(repositoryURL);
        String protocol = url.getProtocol();
        int port = url.getPort();
        String host = url.getHost();
        String path = url.getPath();

        URIBuilder builder = new URIBuilder();
        builder.setScheme(protocol);
        builder.setHost(host);
        builder.setPort(port);
        builder.setPath(path);
        builder.setUserInfo(user, password);

        repositoryURL = builder.toString();
        // log.info("Using path: " + repositoryURL); // Reveals password
    }
}

From source file:fx.browser.Window.java

public void setLocation(String location) throws URISyntaxException {
    System.out.println("# " + this.toString() + "-Classloader: " + getClass().getClassLoader().toString()
            + " setLocation()");
    this.location = location;
    HttpGet httpGet = new HttpGet(new URI(location));

    try (CloseableHttpResponse response = Browser.getHttpClient().execute(httpGet)) {
        switch (response.getStatusLine().getStatusCode()) {

        case HttpStatus.SC_OK:
            FXMLLoader loader = new FXMLLoader();
            Header header = response.getFirstHeader("class-loader-url");

            if (header != null) {
                URL url = new URL(location);

                url = new URL(url.getProtocol(), url.getHost(), url.getPort(), header.getValue());
                if (logger.isLoggable(Level.INFO)) {
                    logger.log(Level.INFO, "Set up remote classloader: {0}", url);
                }//  ww w .java 2s . c  om

                loader.setClassLoader(HttpClassLoader.getInstance(url, getClass().getClassLoader()));
            }

            try {
                ByteArrayOutputStream buffer = new ByteArrayOutputStream();

                response.getEntity().writeTo(buffer);
                response.close();
                setContent(loader.load(new ByteArrayInputStream(buffer.toByteArray())));
            } catch (Exception e) {
                response.close();
                logger.log(Level.INFO, e.toString(), e);
                Node node = loader.load(getClass().getResourceAsStream("/fxml/webview.fxml"));
                WebViewController controller = (WebViewController) loader.getController();

                controller.view(location);
                setContent(node);
            }

            break;

        case HttpStatus.SC_UNAUTHORIZED:
            response.close();
            Optional<Pair<String, String>> result = new LoginDialog().showAndWait();

            if (result.isPresent()) {
                URL url = new URL(location);

                Browser.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()),
                        new UsernamePasswordCredentials(result.get().getKey(), result.get().getValue()));
                setLocation(location);
            }

            break;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:io.fabric8.maven.core.handler.ProbeHandler.java

private HTTPGetAction getHTTPGetAction(String getUrl) {
    if (getUrl == null || !getUrl.subSequence(0, 4).toString().equalsIgnoreCase("http")) {
        return null;
    }//  w w w  .ja  va  2s.c  om
    try {
        URL url = new URL(getUrl);
        return new HTTPGetAction(url.getHost(), null /* headers */, url.getPath(),
                new IntOrString(url.getPort()), url.getProtocol());
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("Invalid URL " + getUrl + " given for HTTP GET readiness check");
    }
}

From source file:edu.internet2.middleware.grouper.changeLog.esb2.consumer.EsbHttpPublisher.java

@Override
public boolean dispatchEvent(String eventJsonString, String consumerName) {
    // TODO Auto-generated method stub

    String urlString = GrouperLoaderConfig
            .getPropertyString("changeLog.consumer." + consumerName + ".publisher.url");
    String username = GrouperLoaderConfig
            .getPropertyString("changeLog.consumer." + consumerName + ".publisher.username", "");
    String password = GrouperLoaderConfig
            .getPropertyString("changeLog.consumer." + consumerName + ".publisher.password", "");
    if (LOG.isDebugEnabled()) {
        LOG.debug("Consumer name: " + consumerName + " sending " + GrouperUtil.indent(eventJsonString, false)
                + " to " + urlString);
    }//  w  w  w  .ja  v a  2 s  .co  m
    int retries = GrouperLoaderConfig
            .getPropertyInt("changeLog.consumer." + consumerName + ".publisher.retries", 0);
    int timeout = GrouperLoaderConfig
            .getPropertyInt("changeLog.consumer." + consumerName + ".publisher.timeout", 60000);
    PostMethod post = new PostMethod(urlString);
    post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(retries, false));
    post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(timeout));
    post.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    RequestEntity requestEntity;
    try {
        requestEntity = new StringRequestEntity(eventJsonString, "application/json", "utf-8");

        post.setRequestEntity(requestEntity);
        HttpClient httpClient = new HttpClient();
        if (!(username.equals(""))) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Authenticating using basic auth");
            }
            URL url = new URL(urlString);
            httpClient.getState().setCredentials(new AuthScope(null, url.getPort(), null),
                    new UsernamePasswordCredentials(username, password));
            httpClient.getParams().setAuthenticationPreemptive(true);
            post.setDoAuthentication(true);
        }
        int statusCode = httpClient.executeMethod(post);
        if (statusCode == 200) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Status code 200 recieved, event sent OK");
            }
            return true;
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Status code " + statusCode + " recieved, event send failed");
            }
            return false;
        }
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}

From source file:org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientImpl.java

public AvaticaCommonsHttpClientImpl(URL url) {
    this.host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    this.uri = toURI(Objects.requireNonNull(url));
    initializeClient();/*from w  ww . j a  v a 2s .c om*/
}

From source file:uk.ac.ox.oucs.vle.XcriPopulatorInput.java

public InputStream getInput(PopulatorContext context) throws PopulatorException {

    InputStream input = null;//from  ww  w  .j  a  va2  s .  c  o m
    HttpEntity entity = null;

    try {
        URL xcri = new URL(context.getURI());

        HttpHost targetHost = new HttpHost(xcri.getHost(), xcri.getPort(), xcri.getProtocol());

        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(context.getUser(), context.getPassword()));

        HttpGet httpget = new HttpGet(xcri.toURI());
        HttpResponse response = httpClient.execute(targetHost, httpget);
        entity = response.getEntity();

        if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
            throw new PopulatorException("Invalid Response [" + response.getStatusLine().getStatusCode() + "]");
        }

        input = entity.getContent();

    } catch (MalformedURLException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (IllegalStateException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (IOException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (URISyntaxException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } finally {
        if (null == input && null != entity) {
            try {
                entity.getContent().close();
            } catch (IOException e) {
                log.error("IOException [" + e + "]");
            }
        }
    }
    return input;
}

From source file:com.googlesource.gerrit.plugins.github.oauth.PooledHttpClientProvider.java

@Inject
PooledHttpClientProvider(@GerritServerConfig Config config, ProxyProperties proxyProperties) {
    this.proxy = proxyProperties;
    URL proxyUrl = proxyProperties.getProxyUrl();
    if (proxyUrl != null) {
        setProxyProperty("proxyHost", proxyUrl.getHost());
        setProxyProperty("proxyPort", "" + proxyUrl.getPort());
        setProxyProperty("proxyUser", proxyProperties.getUsername());
        setProxyProperty("proxyPassword", proxyProperties.getPassword());
    }/* w  w w  . ja va 2  s. com*/

    maxConnectionPerRoute = config.getInt("http", null, "pooledMaxConnectionsPerRoute", 16);
    maxTotalConnection = config.getInt("http", null, "pooledMaxTotalConnections", 32);
}