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:io.kamax.mxisd.dns.ClientDnsOverwrite.java

public URIBuilder transform(URI initial) {
    URIBuilder builder = new URIBuilder(initial);
    Entry mapping = mappings.get(initial.getHost());
    if (mapping == null) {
        throw new InternalServerError("No DNS client override for " + initial.getHost());
    }/*from ww w. j  a v a2 s.c om*/

    try {
        URL target = new URL(mapping.getValue());
        builder.setScheme(target.getProtocol());
        builder.setHost(target.getHost());
        if (target.getPort() != -1) {
            builder.setPort(target.getPort());
        }

        return builder;
    } catch (MalformedURLException e) {
        log.warn("Skipping DNS overwrite entry {} due to invalid value [{}]: {}", mapping.getName(),
                mapping.getValue(), e.getMessage());
        throw new ConfigurationException(
                "Invalid DNS overwrite entry in homeserver client: " + mapping.getName(), e.getMessage());
    }
}

From source file:com.constellio.app.modules.es.connectors.http.fetcher.config.BasicUrlNormalizer.java

@Override
public String normalize(String url) throws MalformedURLException, URISyntaxException {
    String trimmedUrl = StringUtils.trim(url);
    String noFragmentUrl = StringUtils.substringBefore(trimmedUrl, "#");
    if (StringUtils.isEmpty(new URL(noFragmentUrl).getFile())) {
        noFragmentUrl = noFragmentUrl + "/";
    }//from   www  . jav a2  s  .co m
    URL normalizedUrl = new URL(noFragmentUrl);
    String lowerCaseHost = StringUtils.lowerCase(normalizedUrl.getHost());
    normalizedUrl = new URL(normalizedUrl.getProtocol(), lowerCaseHost, normalizedUrl.getPort(),
            normalizedUrl.getFile());
    return normalizedUrl.toURI().normalize().toString();
}

From source file:edu.brandeis.cs.planner.service.Metadata.java

protected void init() {
    boolean use_proxy = ConfigXML.config().getBoolean("connection/proxies/use_proxy");
    if (use_proxy) {
        client.setProxy(ConfigXML.config().getString("connection/proxies/http_proxy"));
    }//from w ww.jav  a 2s.  co  m
    String service_manager = ConfigXML.config().getString("grids/grid/service_manager");
    try {
        URL url = new URL(service_manager);
        String host = url.getHost();
        int port = url.getPort();
        username = ConfigXML.config().getString(
                "connection/credentials/credential[@host='" + host + "' and @port='" + port + "']/username");
        password = ConfigXML.config().getString(
                "connection/credentials/credential[@host='" + host + "' and @port='" + port + "']/password");
        logger.debug("host={}", host);
        logger.debug("port={}", port);
        logger.debug("username={}", username);
    } catch (MalformedURLException e) {
        logger.warn("Wrong Service Manager", e);
        e.printStackTrace();
    }
    for (String wsdlString : wsdls) {
        String metadataString = callMetadata(wsdlString);
        metadataJsons.add(metadataString);
    }
}

From source file:com.gargoylesoftware.htmlunit.CookieManager.java

/**
 * Gets the port of the URL./* w  ww. j  av  a  2 s . c o  m*/
 * This functionality is implemented here as protected method to allow subclass to change it
 * as workaround to <a href="http://code.google.com/p/googleappengine/issues/detail?id=4784">
 * Google App Engine bug 4784</a>.
 * @param url the URL
 * @return the port use to connect the server
 */
protected int getPort(final URL url) {
    if (url.getPort() != -1) {
        return url.getPort();
    }
    return url.getDefaultPort();
}

From source file:com.kagilum.plugins.icescrum.IceScrumSession.java

private void setAuthentication() throws MalformedURLException {
    int port;//from   www  . j  ava 2  s  .  c  om
    URL url = new URL(settings.getUrl() + "/version/");
    if (url.getPort() == -1) {
        port = url.getDefaultPort();
    } else {
        port = url.getPort();
    }
    client.getState().setCredentials(new AuthScope(url.getHost(), port),
            new UsernamePasswordCredentials(settings.getUsername(), settings.getPassword()));
}

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

protected void process(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from   www.  ja  va  2s. com*/
        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:net.hillsdon.reviki.wiki.renderer.creole.CreoleLinkContentsSplitter.java

/**
 * Splits links of the form target or text|target where target is
 * //w  ww  .  j a v  a2  s  .c  o m
 * PageName wiki:PageName PageName#fragment wiki:PageName#fragment
 * A String representing an absolute URI scheme://valid/absolute/uri
 * Any character not in the `unreserved`, `punct`, `escaped`, or `other` categories (RFC 2396),
 * and not equal '/' or '@', is %-encoded. 
 * 
 * @param in The String to split
 * @return The split LinkParts
 */
LinkParts split(final String in) {
    String target = StringUtils.trimToEmpty(StringUtils.substringBefore(in, "|"));
    String text = StringUtils.trimToNull(StringUtils.substringAfter(in, "|"));
    if (target == null) {
        target = "";
    }
    if (text == null) {
        text = target;
    }
    // Link target can be PageName, wiki:PageName or a URL.
    URI uri = null;
    try {
        URL url = new URL(target);

        uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        if (uri.getPath() == null || !uri.isAbsolute()) {
            uri = null;
        }
    } catch (URISyntaxException e) {
        // uri remains null
    } catch (MalformedURLException e) {
        // uri remains null
    }

    if (uri != null) {
        return new LinkParts(text, uri);
    } else {
        // Split into wiki:pageName
        String[] parts = target.split(":", 2);
        String wiki = null;
        String pageName = target;
        if (parts.length == 2) {
            wiki = parts[0];
            pageName = parts[1];
        }

        // Split into pageName#fragment
        parts = pageName.split("#", 2);
        String fragment = null;
        if (parts.length == 2) {
            pageName = parts[0];
            fragment = parts[1];
        }

        // Split into pageName/attachment
        parts = pageName.split("/", 2);
        String attachment = null;
        if (parts.length == 2) {
            pageName = parts[0];
            attachment = parts[1];
        }

        return new LinkParts(text, wiki, pageName, fragment, attachment);
    }
}

From source file:org.jasig.portal.security.provider.saml.Resource.java

/**
 * Sets up the SSL parameters of a connection to the WSP, including the
 * client certificate and server certificate trust.  The program that set up
 * the SAMLSession object is responsible for providing these optional SSL
 * parameters./*from w w  w . j  av  a 2s  .  c  o m*/
 *  
 * @param samlSession SAMLSession that already must contain a valid HttpClient for the WSP
 * @param resource Resource wrapper class that contains a resource URL
 * @throws MalformedURLException 
 */
public void setupWSPClientConnection(SAMLSession samlSession) throws MalformedURLException {
    URL url = new URL(resourceUrl);
    String protocol = url.getProtocol();
    int port = url.getPort();

    // Unless we are using SSL/TLS, there is no need to do the socket factory

    if (protocol.equalsIgnoreCase("https")) {
        SSLSocketFactory socketFactory = getWSPSocketFactory();

        if (port == -1)
            port = 443;

        Scheme sch = new Scheme(protocol, socketFactory, port);
        samlSession.getHttpClient().getConnectionManager().getSchemeRegistry().unregister(protocol);
        samlSession.getHttpClient().getConnectionManager().getSchemeRegistry().register(sch);
    }
}

From source file:com.esri.geoportal.commons.robots.BotsParser.java

private URL getRobotsTxtUrl(URL baseUrl) {
    try {/*from   w  w w .ja va  2s . co m*/
        if (baseUrl != null) {
            if (baseUrl.getPort() >= 0) {
                return new URL(String.format("%s://%s:%d/robots.txt", baseUrl.getProtocol(), baseUrl.getHost(),
                        baseUrl.getPort()));
            } else {
                return new URL(String.format("%s://%s/robots.txt", baseUrl.getProtocol(), baseUrl.getHost()));
            }
        }
    } catch (MalformedURLException ex) {
        LOG.warn("Invalid robots.txt url.", ex);
    }
    return null;
}

From source file:org.apache.metamodel.elasticsearch.rest.ElasticSearchRestDataContextFactory.java

private ElasticSearchRestClient createClient(final DataContextProperties properties)
        throws MalformedURLException {
    final URL url = new URL(properties.getUrl());
    final RestClientBuilder builder = RestClient.builder(new HttpHost(url.getHost(), url.getPort()));

    if (properties.getUsername() != null) {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(properties.getUsername(), properties.getPassword()));

        builder.setHttpClientConfigCallback(
                httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
    }// w  w  w.jav a  2  s .  c o m

    return new ElasticSearchRestClient(builder.build());
}