Example usage for java.net URL getDefaultPort

List of usage examples for java.net URL getDefaultPort

Introduction

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

Prototype

public int getDefaultPort() 

Source Link

Document

Gets the default port number of the protocol associated with this URL .

Usage

From source file:org.commonjava.indy.httprox.util.ProxyResponseHelper.java

private String getBaseUrl(URL url, boolean includeDefaultPort) {
    int port = getPort(url);
    String portStr;/*from  w w  w  .ja  va 2 s  .  co m*/
    if (includeDefaultPort || port != url.getDefaultPort()) {
        portStr = ":" + port;
    } else {
        portStr = "";
    }
    return String.format("%s://%s%s/", url.getProtocol(), url.getHost(), portStr);
}

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

protected void configureProxy(final HttpClientBuilder httpClientBuilder, final String proxy)
        throws InitializationException {
    final URL proxyUrl;
    try {//  w  ww  . j  a v  a  2  s.  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:org.fao.oaipmh.requests.Transport.java

public void setUrl(URL url) {
    host = url.getHost();//from w w  w  .  java 2  s.  c  om
    port = url.getPort();
    address = url.getPath();

    if (port == -1)
        port = url.getDefaultPort();
}

From source file:org.aludratest.service.gui.web.selenium.TAFMSSeleniumResourceService.java

@Override
public String acquire() {
    // prepare a JSON query to the given TAFMS server
    JSONObject query = new JSONObject();

    try {/*from ww  w  . j  a  va  2 s.c  o  m*/
        query.put("resourceType", "selenium");
        query.put("niceLevel", configuration.getIntValue("tafms.niceLevel", 0));
        String jobName = configuration.getStringValue("tafms.jobName");
        if (jobName != null && !"".equals(jobName)) {
            query.put("jobName", jobName);
        }
    } catch (JSONException e) {
    }

    // prepare authentication
    BasicCredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
            configuration.getStringValue("tafms.user"), configuration.getStringValue("tafms.password")));

    CloseableHttpClient client = HttpClientBuilder.create()
            .setConnectionReuseStrategy(new NoConnectionReuseStrategy()).disableConnectionState()
            .disableAutomaticRetries().setDefaultCredentialsProvider(provider).build();

    String message = null;
    try {
        boolean wait;

        // use preemptive authentication to avoid double connection count
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        URL url = new URL(getTafmsUrl());
        HttpHost host = new HttpHost(url.getHost(), url.getPort() == -1 ? url.getDefaultPort() : url.getPort(),
                url.getProtocol());
        authCache.put(host, basicAuth);

        // Add AuthCache to the execution context
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);

        do {
            // send a POST request to resource URL
            HttpPost request = new HttpPost(getTafmsUrl() + "resource");

            // attach query as JSON string data
            request.setEntity(new StringEntity(query.toString(), ContentType.APPLICATION_JSON));

            CloseableHttpResponse response = null;

            // fire request
            response = client.execute(request, localcontext);

            try {
                if (response.getStatusLine() == null) {
                    throw new ClientProtocolException("No HTTP status line transmitted");
                }

                message = extractMessage(response);
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    LOG.error("Exception when querying TAFMS server for resource. HTTP Status: "
                            + response.getStatusLine().getStatusCode() + ", message: " + message);
                    return null;
                }

                JSONObject object = new JSONObject(message);
                if (object.has("errorMessage")) {
                    LOG.error("TAFMS server reported an error: " + object.get("errorMessage"));
                    return null;
                }

                // continue wait?
                if (object.has("waiting") && object.getBoolean("waiting")) {
                    wait = true;
                    query.put("requestId", object.getString("requestId"));
                } else {
                    JSONObject resource = object.optJSONObject("resource");
                    if (resource == null) {
                        LOG.error("TAFMS server response did not provide a resource. Message was: " + message);
                        return null;
                    }

                    String sUrl = resource.getString("url");
                    hostResourceIds.put(sUrl, object.getString("requestId"));

                    return sUrl;
                }
            } finally {
                IOUtils.closeQuietly(response);
            }
        } while (wait);

        // should never come here
        return null;
    } catch (ClientProtocolException e) {
        LOG.error("Exception in HTTP transmission", e);
        return null;
    } catch (IOException e) {
        LOG.error("Exception in communication with TAFMS server", e);
        return null;
    } catch (JSONException e) {
        LOG.error("Invalid JSON received from TAFMS server. JSON message was: " + message, e);
        return null;
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:org.whispersystems.mmsmonster.mms.MmsConnection.java

protected CloseableHttpClient constructHttpClient() throws IOException {
    RequestConfig config = RequestConfig.custom().setConnectTimeout(20 * 1000)
            .setConnectionRequestTimeout(20 * 1000).setSocketTimeout(20 * 1000).setMaxRedirects(20).build();

    URL mmsc = new URL(apn.getMmsc());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();

    if (apn.hasAuthentication()) {
        credsProvider.setCredentials(/*  ww  w .j  a  v a 2s .  c om*/
                new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()),
                new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword()));
    }

    return HttpClients.custom().setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4())
            .setRedirectStrategy(new LaxRedirectStrategy()).setUserAgent("Android-Mms/2.0")
            .setConnectionManager(new BasicHttpClientConnectionManager()).setDefaultRequestConfig(config)
            .setDefaultCredentialsProvider(credsProvider).build();
}

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

private boolean isSameSchemeHostAndPort(String location2, String location) throws MalformedURLException {
    try {/* www. j  ava2  s  .com*/
        if (location.startsWith("/") || location2.startsWith("/"))
            return false; // no host info available
        URL loc2 = new URL(location2);
        URL loc1 = new URL(location);
        if (loc2.getProtocol() != null && !loc2.getProtocol().equals(loc1.getProtocol()))
            return false;
        if (loc2.getHost() != null && !loc2.getHost().equals(loc1.getHost()))
            return false;
        int loc2Port = loc2.getPort() == -1 ? loc2.getDefaultPort() : loc2.getPort();
        int loc1Port = loc1.getPort() == -1 ? loc1.getDefaultPort() : loc1.getPort();
        if (loc2Port != loc1Port)
            return false;
        return true;
    } catch (MalformedURLException e) {
        log.warn("", e); // TODO: fix these cases
        return false;
    }
}

From source file:org.soaplab.clients.ServiceLocator.java

/**************************************************************************
 * Cut the 'endpoint' into host, port and context. Return the path
 * (the part of the URL without the leading slash) - because it
 * may be useful for extracting a service name (elsewhere).
 *************************************************************************/
protected String cutEndpoint(String endpoint) {
    try {//from   www  .  j av a  2  s . co  m
        URL url = new URL(endpoint);
        setHost(url.getHost());
        int p = url.getPort();
        if (p == -1)
            p = url.getDefaultPort();
        if (p > -1)
            setPort("" + p);
        String path = url.getPath();
        if (path.startsWith("/") && path.length() > 1)
            path = path.substring(1);
        if (StringUtils.contains(path, FIXED_URL_PATH)) {
            setContext(StringUtils.substringBefore(path, FIXED_URL_PATH));
        } else {
            setContext(StringUtils.substringBeforeLast(path, "/"));
        }
        return path;

    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("Not a valid URL passed to a ServiceLocator: '" + endpoint + "'");
    }
}

From source file:at.gv.egiz.pdfas.web.servlets.ProvidePDFServlet.java

protected void process(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//w  w  w .  ja v  a 2 s. c  o m
        String invokeURL = PdfAsHelper.getInvokeURL(request, response);

        if (invokeURL == null || !WebConfiguration.isProvidePdfURLinWhitelist(invokeURL)) {

            if (invokeURL != null) {
                logger.warn(invokeURL + " is not allowed by whitelist");
            }

            String template = PdfAsHelper.getProvideTemplate();
            template = template.replace(PDF_DATA_URL, PdfAsHelper.generatePdfURL(request, response));
            // Deliver to Browser directly!
            response.setContentType("text/html");
            response.getWriter().write(template);
            response.getWriter().close();
        } else {
            // Redirect Browser
            String template = PdfAsHelper.getInvokeRedirectTemplateSL();

            URL url = new URL(invokeURL);
            int p = url.getPort();
            //no port, but http or https --> use default port
            if ((url.getProtocol().equalsIgnoreCase("https") || url.getProtocol().equalsIgnoreCase("http"))
                    && p == -1) {
                p = url.getDefaultPort();
            }
            String invokeUrlProcessed = url.getProtocol() + "://" + // "http" + "://
                    url.getHost() + // "myhost"
                    ":" + // ":"
                    p + // "8080"
                    url.getPath();

            template = template.replace("##INVOKE_URL##", invokeUrlProcessed);

            String extraParams = UrlParameterExtractor.buildParameterFormString(url);
            template = template.replace("##ADD_PARAMS##", extraParams);

            byte[] signedData = PdfAsHelper.getSignedPdf(request, response);
            if (signedData != null) {
                template = template.replace("##PDFLENGTH##", String.valueOf(signedData.length));
            } else {
                throw new PdfAsException("No Signature data available");
            }

            String target = PdfAsHelper.getInvokeTarget(request, response);

            if (target == null) {
                target = "_self";
            }

            template = template.replace("##TARGET##", StringEscapeUtils.escapeHtml4(target));

            template = template.replace("##PDFURL##",
                    URLEncoder.encode(PdfAsHelper.generatePdfURL(request, response), "UTF-8"));
            response.setContentType("text/html");
            response.getWriter().write(template);
            response.getWriter().close();
        }
    } catch (Exception e) {
        PdfAsHelper.setSessionException(request, response, e.getMessage(), e);
        PdfAsHelper.gotoError(getServletContext(), request, response);
    }
}

From source file:org.apache.ambari.server.view.ViewURLStreamProvider.java

/**
 * Is it allowed to make calls to the supplied url
 * @param spec the URL//from w  w w  . j a  v a 2 s .c  om
 * @return
 */
protected boolean isProxyCallAllowed(String spec) {
    if (StringUtils.isNotBlank(spec) && this.getHostPortRestrictionHandler().proxyCallRestricted()) {
        try {
            URL url = new URL(spec);
            return this.getHostPortRestrictionHandler().allowProxy(url.getHost(),
                    Integer.toString(url.getPort() == -1 ? url.getDefaultPort() : url.getPort()));
        } catch (MalformedURLException ex) {
        }
    }

    return true;
}

From source file:org.nuxeo.connect.connector.AbstractConnectConnector.java

/**
 * @since 1.4//  ww  w. j  a va 2 s.c  o m
 */
protected File getCacheFileFor(String suffix) {
    String connectUrlString = ConnectUrlConfig.getBaseUrl();
    String cacheDir = NuxeoConnectClient.getProperty(NUXEO_TMP_DIR_PROPERTY,
            System.getProperty("java.io.tmpdir"));
    try {
        URL connectUrl = new URL(connectUrlString);
        String cachePrefix = connectUrl.getHost() + "_";
        int port = connectUrl.getPort();
        if (port == -1) {
            port = connectUrl.getDefaultPort();
        }
        if (port == -1) {
            cachePrefix = cachePrefix + "00_";
        } else {
            cachePrefix = cachePrefix + Integer.toString(port) + "_";
        }
        cachePrefix = cachePrefix + connectUrl.getPath().replaceAll("/", "#");
        String cacheFileName = cachePrefix + "_" + suffix + ".json";
        return new File(cacheDir, cacheFileName);
    } catch (MalformedURLException e) {
        String fallbackFileName = connectUrlString + "_" + suffix + ".json";
        return new File(cacheDir, fallbackFileName);
    }
}