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:org.openqa.grid.internal.utils.SelfRegisteringRemote.java

private boolean isAlreadyRegistered(RegistrationRequest node) {

    HttpClient client = httpClientFactory.getHttpClient();
    try {//from  w w  w  .j av a  2  s. c o  m
        String tmp = "http://" + node.getConfiguration().get(RegistrationRequest.HUB_HOST) + ":"
                + node.getConfiguration().get(RegistrationRequest.HUB_PORT) + "/grid/api/proxy";
        URL api = new URL(tmp);
        HttpHost host = new HttpHost(api.getHost(), api.getPort());

        String id = (String) node.getConfiguration().get(RegistrationRequest.ID);
        if (id == null) {
            id = (String) node.getConfiguration().get(RegistrationRequest.REMOTE_HOST);
        }
        BasicHttpRequest r = new BasicHttpRequest("GET", api.toExternalForm() + "?id=" + id);

        HttpResponse response = client.execute(host, r);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new GridException("Hub is down or not responding.");
        }
        JSONObject o = extractObject(response);
        return (Boolean) o.get("success");
    } catch (Exception e) {
        throw new GridException("Hub is down or not responding: " + e.getMessage());
    }
}

From source file:org.openmrs.module.dhisreport.web.controller.Dhis2ServerController.java

public boolean testConnection(URL url, String username, String password, HttpDhis2Server server,
        WebRequest webRequest, ModelMap model) {
    String host = url.getHost();//from   w w  w  .  j av  a 2 s.c  om
    int port = url.getPort();

    HttpHost targetHost = new HttpHost(host, port, url.getProtocol());
    DefaultHttpClient httpclient = new DefaultHttpClient();
    BasicHttpContext localcontext = new BasicHttpContext();

    try {
        HttpGet httpGet = new HttpGet(url.getPath()); // +
        // DATAVALUESET_PATH
        // );
        httpGet.addHeader(
                BasicScheme.authenticate(new UsernamePasswordCredentials(username, password), "UTF-8", false));

        HttpResponse response = httpclient.execute(targetHost, httpGet, localcontext);

        //System.out.println( "Http Response :" + response + ":" + response.getStatusLine().getStatusCode() );

        if (response.getStatusLine().getStatusCode() == 200) {
            log.debug("Dhis2 server configured: " + username + ":xxxxxx  " + url.toExternalForm());
            return true;
        }

        else {
            log.debug("Dhis2 server not configured");
            return false;
        }
    } catch (IOException ex) {
        log.debug("Problem accessing DHIS2 server: " + ex.toString());
        return false;
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com._17od.upm.transport.HTTPTransport.java

public void delete(String targetLocation, String name, String username, String password)
        throws TransportException {

    targetLocation = addTrailingSlash(targetLocation) + "deletefile.php";

    PostMethod post = new PostMethod(targetLocation);
    post.addParameter("fileToDelete", name);

    //This part is wrapped in a try/finally so that we can ensure
    //the connection to the HTTP server is always closed cleanly 
    try {/*from  w w  w . jav a  2  s  .co  m*/

        //Set the authentication details
        if (username != null) {
            Credentials creds = new UsernamePasswordCredentials(new String(username), new String(password));
            URL url = new URL(targetLocation);
            AuthScope authScope = new AuthScope(url.getHost(), url.getPort());
            client.getState().setCredentials(authScope, creds);
            client.getParams().setAuthenticationPreemptive(true);
        }

        int status = client.executeMethod(post);
        if (status != HttpStatus.SC_OK) {
            throw new TransportException(
                    "There's been some kind of problem deleting a file on the HTTP server.\n\nThe HTTP error message is ["
                            + HttpStatus.getStatusText(status) + "]");
        }

        if (!post.getResponseBodyAsString().equals("OK")) {
            throw new TransportException(
                    "There's been some kind of problem deleting a file to the HTTP server.\n\nThe error message is ["
                            + post.getResponseBodyAsString() + "]");
        }

    } catch (MalformedURLException e) {
        throw new TransportException(e);
    } catch (HttpException e) {
        throw new TransportException(e);
    } catch (IOException e) {
        throw new TransportException(e);
    } finally {
        post.releaseConnection();
    }

}

From source file:de.codecentric.boot.admin.zuul.filters.route.SimpleHostRoutingFilter.java

private HttpHost getHttpHost(URL host) {
    HttpHost httpHost = new HttpHost(host.getHost(), host.getPort(), host.getProtocol());
    return httpHost;
}

From source file:com.predic8.membrane.core.interceptor.rewrite.ReverseProxyingInterceptor.java

/**
 * handles "Destination" header (see RFC 2518 section 9.3; also used by WebDAV)
 *//* ww  w .  jav  a  2s.  c  om*/
@Override
public Outcome handleRequest(Exchange exc) throws Exception {
    if (exc.getRequest() == null)
        return Outcome.CONTINUE;
    String destination = exc.getRequest().getHeader().getFirstValue(Header.DESTINATION);
    if (destination == null)
        return Outcome.CONTINUE;
    if (!destination.contains("://"))
        return Outcome.CONTINUE; // local redirect (illegal by spec)
    // do not rewrite, if the client does not refer to the same host
    if (!isSameSchemeHostAndPort(getProtocol(exc) + "://" + exc.getRequest().getHeader().getHost(),
            destination))
        return Outcome.CONTINUE;
    // if we cannot determine the target hostname
    if (exc.getDestinations().isEmpty()) {
        // just remove the schema/hostname/port. this is illegal (by the spec),
        // but most clients understand it
        exc.getRequest().getHeader().setValue(Header.DESTINATION, new URL(destination).getFile());
        return Outcome.CONTINUE;
    }
    URL target = new URL(exc.getDestinations().get(0));
    // rewrite to our schema, host and port
    exc.getRequest().getHeader().setValue(Header.DESTINATION,
            Relocator.getNewLocation(destination, target.getProtocol(), target.getHost(),
                    target.getPort() == -1 ? target.getDefaultPort() : target.getPort()));
    return Outcome.CONTINUE;
}

From source file:net.siegmar.japtproxy.fetcher.HttpClientConfigurer.java

protected void configureProxy(final HttpClientBuilder httpClientBuilder, final String proxy)
        throws InitializationException {
    final URL proxyUrl;
    try {/*www .  j ava2s.  c o m*/
        proxyUrl = new URL(proxy);
    } catch (final MalformedURLException e) {
        throw new InitializationException("Invalid proxy url", e);
    }

    final String proxyHost = proxyUrl.getHost();
    final int proxyPort = proxyUrl.getPort() != -1 ? proxyUrl.getPort() : proxyUrl.getDefaultPort();

    LOG.info("Set proxy server to '{}:{}'", proxyHost, proxyPort);
    httpClientBuilder.setRoutePlanner(new DefaultProxyRoutePlanner(new HttpHost(proxyHost, proxyPort)));

    final String userInfo = proxyUrl.getUserInfo();
    if (userInfo != null) {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), buildCredentials(userInfo));

        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }
}

From source file:com.devicehive.application.filter.SwaggerFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    URL requestUrl = new URL(request.getRequestURL().toString());
    logger.debug("Swagger filter triggered by '{}: {}'. Request will be redirected to swagger page",
            request.getMethod(), requestUrl);

    String swaggerJsonUrl = String.format("%s://%s:%s%s%s/swagger.json", requestUrl.getProtocol(),
            requestUrl.getHost(),/*ww w  . ja  va 2 s .  c  o  m*/
            requestUrl.getPort() == -1 ? requestUrl.getDefaultPort() : requestUrl.getPort(),
            request.getContextPath(), JerseyConfig.REST_PATH);
    String url = request.getContextPath() + "/swagger.html?url=" + swaggerJsonUrl;

    logger.debug("Request is being redirected to '{}'", url);
    response.sendRedirect(url);
}

From source file:org.apache.nifi.elasticsearch.ElasticSearchClientServiceImpl.java

private void setupClient(ConfigurationContext context) throws MalformedURLException, InitializationException {
    final String hosts = context.getProperty(HTTP_HOSTS).evaluateAttributeExpressions().getValue();
    String[] hostsSplit = hosts.split(",[\\s]*");
    this.url = hostsSplit[0];
    final SSLContextService sslService = context.getProperty(PROP_SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    final String username = context.getProperty(USERNAME).evaluateAttributeExpressions().getValue();
    final String password = context.getProperty(PASSWORD).evaluateAttributeExpressions().getValue();

    final Integer connectTimeout = context.getProperty(CONNECT_TIMEOUT).asInteger();
    final Integer readTimeout = context.getProperty(SOCKET_TIMEOUT).asInteger();
    final Integer retryTimeout = context.getProperty(RETRY_TIMEOUT).asInteger();

    HttpHost[] hh = new HttpHost[hostsSplit.length];
    for (int x = 0; x < hh.length; x++) {
        URL u = new URL(hostsSplit[x]);
        hh[x] = new HttpHost(u.getHost(), u.getPort(), u.getProtocol());
    }//from  w  w  w.j  a  v a2  s .  c o m

    final SSLContext sslContext;
    try {
        sslContext = (sslService != null && sslService.isKeyStoreConfigured()
                && sslService.isTrustStoreConfigured()) ? buildSslContext(sslService) : null;
    } catch (IOException | CertificateException | NoSuchAlgorithmException | UnrecoverableKeyException
            | KeyStoreException | KeyManagementException e) {
        getLogger().error("Error building up SSL Context from the supplied configuration.", e);
        throw new InitializationException(e);
    }

    RestClientBuilder builder = RestClient.builder(hh).setHttpClientConfigCallback(httpClientBuilder -> {
        if (sslContext != null) {
            httpClientBuilder = httpClientBuilder.setSSLContext(sslContext);
        }

        if (username != null && password != null) {
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(username, password));
            httpClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }

        return httpClientBuilder;
    }).setRequestConfigCallback(requestConfigBuilder -> {
        requestConfigBuilder.setConnectTimeout(connectTimeout);
        requestConfigBuilder.setSocketTimeout(readTimeout);
        return requestConfigBuilder;
    }).setMaxRetryTimeoutMillis(retryTimeout);

    this.client = builder.build();
    this.highLevelClient = new RestHighLevelClient(client);
}

From source file:com.celamanzi.liferay.portlets.rails286.HeadProcessor.java

protected HeadProcessor(String servlet, java.net.URL baseUrl, String namespace) {
    this.servlet = servlet;
    this.baseUrl = baseUrl;
    this.namespace = namespace;
    this.location = baseUrl.getProtocol() + "://" + baseUrl.getHost() + ":" + baseUrl.getPort() + servlet;
    log.debug("Initializing HeadProcessor @: " + this.location);
}

From source file:com._17od.upm.transport.HTTPTransport.java

public void put(String targetLocation, File file, String username, String password) throws TransportException {

    targetLocation = addTrailingSlash(targetLocation) + "upload.php";

    PostMethod post = new PostMethod(targetLocation);

    //This part is wrapped in a try/finally so that we can ensure
    //the connection to the HTTP server is always closed cleanly 
    try {/*from   www. ja v a2s.co  m*/

        Part[] parts = { new FilePart("userfile", file) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        //Set the HTTP authentication details
        if (username != null) {
            Credentials creds = new UsernamePasswordCredentials(new String(username), new String(password));
            URL url = new URL(targetLocation);
            AuthScope authScope = new AuthScope(url.getHost(), url.getPort());
            client.getState().setCredentials(authScope, creds);
            client.getParams().setAuthenticationPreemptive(true);
        }

        // This line makes the HTTP call
        int status = client.executeMethod(post);

        // I've noticed on Windows (at least) that PHP seems to fail when moving files on the first attempt
        // The second attempt works so lets just do that
        if (status == HttpStatus.SC_OK && post.getResponseBodyAsString().equals("FILE_WASNT_MOVED")) {
            status = client.executeMethod(post);
        }

        if (status != HttpStatus.SC_OK) {
            throw new TransportException(
                    "There's been some kind of problem uploading a file to the HTTP server.\n\nThe HTTP error message is ["
                            + HttpStatus.getStatusText(status) + "]");
        }

        if (!post.getResponseBodyAsString().equals("OK")) {
            throw new TransportException(
                    "There's been some kind of problem uploading a file to the HTTP server.\n\nThe error message is ["
                            + post.getResponseBodyAsString() + "]");
        }

    } catch (FileNotFoundException e) {
        throw new TransportException(e);
    } catch (MalformedURLException e) {
        throw new TransportException(e);
    } catch (HttpException e) {
        throw new TransportException(e);
    } catch (IOException e) {
        throw new TransportException(e);
    } finally {
        post.releaseConnection();
    }

}