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:com.gargoylesoftware.htmlunit.javascript.host.xml.XMLHttpRequest.java

private boolean isSameOrigin(final URL originUrl, final URL newUrl) {
    if (!originUrl.getHost().equals(newUrl.getHost())) {
        return false;
    }//from  w  w  w  .  j  a v  a  2  s. co m

    if (getBrowserVersion().hasFeature(XHR_IGNORE_PORT_FOR_SAME_ORIGIN)) {
        return true;
    }

    int originPort = originUrl.getPort();
    if (originPort == -1) {
        originPort = originUrl.getDefaultPort();
    }
    int newPort = newUrl.getPort();
    if (newPort == -1) {
        newPort = newUrl.getDefaultPort();
    }
    return originPort == newPort;
}

From source file:org.fao.geonet.csw.common.requests.CatalogRequest.java

/**
 * Set request URL host, port, address and path.
 * If URL contains query string parameters, those parameters are
 * preserved (and {@link CatalogRequest#excludedParameters} are
 * excluded). A complete GetCapabilities URL may be used for initialization.
 *//*from  ww w  .j  a  v a2 s  .  c om*/
public void setUrl(URL url) {
    this.host = url.getHost();
    this.port = url.getPort();
    this.protocol = url.getProtocol();
    this.address = url.toString();
    this.path = url.getPath();

    alSetupGetParams = new ArrayList<NameValuePair>();
    String query = url.getQuery();

    if (StringUtils.isNotEmpty(query)) {
        String[] params = query.split("&");
        for (String param : params) {
            String[] kvp = param.split("=");
            if (!excludedParameters.contains(kvp[0].toLowerCase())) {
                this.alSetupGetParams.add(new NameValuePair(kvp[0], kvp[1]));
            }
        }
    }

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

From source file:com.google.enterprise.connector.sharepoint.client.SharepointClientContext.java

public SharepointClientContext(ClientFactory clientFactory, String sharepointUrl, final String inDomain,
        final String inKdcHost, final String inUsername, final String inPassword,
        final String inGoogleConnectorWorkDir, final String inGoogleGlobalNamespace,
        final String inGoogleLocalNamespace, final String includedURls, final String excludedURls,
        final String inMySiteBaseURL, final String inAliasMapString, final FeedType inFeedType,
        boolean useSPSearchVisibility) throws SharepointException {
    // Avoid a deprecation warning on an overloaded Protocol constructor
    // by passing the argument as a ProtocolSocketFactory instead of an
    // SSLProtocolSocketFactory.
    ProtocolSocketFactory socketFactory = new SSLProtocolSocketFactory();
    Protocol.registerProtocol("https", new Protocol("https", socketFactory, SPConstants.SSL_DEFAULT_PORT));

    this.clientFactory = clientFactory;
    kdcServer = inKdcHost;//w ww.j a  v  a2 s  .com
    if (sharepointUrl == null) {
        throw new SharepointException("sharepoint URL is null");
    }
    if (inUsername == null) {
        throw new SharepointException("Username is null.");
    }
    if (inPassword == null) {
        throw new SharepointException("Password is null.");
    }
    if (inGoogleConnectorWorkDir == null) {
        throw new SharepointException("Working Directory is null.");
    }
    if (inFeedType == null) {
        throw new SharepointException("Feed Type is null.");
    }

    sharepointUrl = sharepointUrl.trim();

    if (sharepointUrl.endsWith(SPConstants.SLASH)) {
        sharepointUrl = sharepointUrl.substring(0, sharepointUrl.lastIndexOf(SPConstants.SLASH));
    }
    // Why to construct a SharePoint URL with default port as 80.
    try {
        final URL url = new URL(sharepointUrl);
        int port = url.getPort();
        if (-1 == port) {
            port = url.getDefaultPort();
        }
        siteURL = url.getProtocol() + SPConstants.URL_SEP + url.getHost() + SPConstants.COLON + port
                + url.getPath();
    } catch (final MalformedURLException e) {
        throw new SharepointException("Failed to construct sharepoint URL...", e);
    }

    if ((inDomain == null) || inDomain.trim().equals("")) {
        LOGGER.log(Level.CONFIG, "Trying to get domain information from username specified [ " + inUsername
                + " ] because domain field has not been explicitly specified.");
        domain = Util.getDomainFromUsername(inUsername);
    } else {
        domain = inDomain;
    }

    LOGGER.finest("domain set to " + domain);

    username = Util.getUserFromUsername(inUsername);
    LOGGER.finest("username set to " + username);

    this.setExcludedURlList(excludedURls, SPConstants.SEPARATOR);
    this.setIncludedURlList(includedURls, SPConstants.SEPARATOR);

    password = inPassword;
    googleGlobalNamespace = inGoogleGlobalNamespace;
    googleLocalNamespace = inGoogleLocalNamespace;
    googleConnectorWorkDir = inGoogleConnectorWorkDir;
    LOGGER.finest("googleConnectorWorkDir set to " + googleConnectorWorkDir);
    excludedURL_ParentDir = googleConnectorWorkDir + SPConstants.SLASH + SPConstants.EXCLUDED_URL_DIR;
    mySiteBaseURL = inMySiteBaseURL;
    LOGGER.finest("mySiteBaseURL set to " + mySiteBaseURL);
    aliasMap = parseAlias(inAliasMapString);

    feedType = inFeedType;
    LOGGER.finest("feedType set to " + feedType);
    LOGGER.finest("bFQDNConversion set to " + bFQDNConversion);

    this.useSPSearchVisibility = useSPSearchVisibility;

    LOGGER.config(" sharepointUrl = [" + sharepointUrl + "] , domain = [" + inDomain + "] , username = ["
            + inUsername + "] , googleConnectorWorkDir = [" + inGoogleConnectorWorkDir
            + "] , googleGlobalNamespace = [" + inGoogleGlobalNamespace + "] , googleLocalNamespace = ["
            + inGoogleLocalNamespace + "] , includedURls = [" + includedURls + "] , excludedURls = ["
            + excludedURls + "] , mySiteBaseURL = [" + inMySiteBaseURL + "], aliasMapString = ["
            + inAliasMapString + "], FeedType [" + inFeedType + "], useSPSearchVisibility = ["
            + useSPSearchVisibility + "]");
}

From source file:ORG.oclc.os.SRW.SRUServerTester.java

public String test() {
    int i;//from w ww.j  a va  2s  .c om

    out("running SRU tests for baseURL: ");
    out(baseURL);
    out('\n');

    out("tests of Explain");
    out('\n');
    if (!isExplainResponse(sruRead(baseURL)))
        failed();
    if (!isExplainResponse(sruRead(baseURL + "?")))
        failed();
    if (!isExplainResponse(sruRead(baseURL + "?operation=explain")))
        failed();
    if (!isExplainResponse(sruRead(baseURL + "?version=1.1")))
        failed();
    if (!isExplainResponse(sruRead(baseURL + "?operation=explain&version=1.1")))
        failed();
    originalBaseURL = baseURL = baseURL + "?";

    if (explainDoc != null) {
        // use the host:port/database to construct an explain request
        String ExplainResponsePath = "/srw:explainResponse/srw:record/srw:recordData/exp:explain";
        String host = getNodeText(explainDoc, ExplainResponsePath + "/exp:serverInfo/exp:host");
        String port = getNodeText(explainDoc, ExplainResponsePath + "/exp:serverInfo/exp:port");
        String database = getNodeText(explainDoc, ExplainResponsePath + "/exp:serverInfo/exp:database");
        if (database.startsWith("/")) {
            out("  ** Warning: explain/serverInfo/database should not begin with a slash ('/')");
            out('\n');
            out("  ** explain/serverInfo/database = ");
            out(database);
            out('\n');
            numWarns++;
            database = database.substring(1);
        }
        String save = baseURL;
        if (port == null || port.length() == 0) {
            out("  ** Warning: your explain record has not specified a port number.");
            out('\n');
            out("  It should have been set explicitly to 80.");
            out('\n');
            numWarns++;
        }
        if ("80".equals(port) || "8080".equals(port) || "7090".equals(port))
            baseURL = "http://" + host + ":" + port + "/" + database + "?";
        else {
            out("  ** Warning: your explain record claims that its host is on port " + port);
            out('\n');
            out("  the SRUServerTester is restricted to testing on ports 80, 8080 and 7090.");
            out('\n');
            out("  Further testing will ignore the host and port provided in the");
            out('\n');
            out("  explain record");
            out('\n');
            numWarns++;
        }
        if (!isExplainResponse(sruRead(baseURL))) {
            out("</pre><pre class='red'>");
            failed();
            baseURL = save;
            out("</pre><pre class='red'>");
            out("  ** Error: the URL created by combining your host, port and database name\n");
            out("  ** resulted in a bad URL\n");
            try {
                URL url = new URL(baseURL);
                out("  ** Comparing the URL I was given to your Explain record:\n");
                out("  ** original host: " + url.getHost() + ", Explain host: " + host + "\n");
                out("  ** original port: " + (url.getPort() == -1 ? url.getDefaultPort() : url.getPort())
                        + ", Explain port: " + port + "\n");
                out("  ** original database: " + url.getPath() + ", Explain database: " + database + "\n");
            } catch (MalformedURLException e) {
            }
            out("</pre><pre>");
            numFailed++;
        }
        // construct a list of indexes from the explainResponse
        NodeList indexes = getNodeList(explainDoc, ExplainResponsePath + "/exp:indexInfo/exp:index");
        if (indexes.getLength() == 0) {
            out("</pre><pre class='red'>");
            out("\n\n**** Severe: no indexes found in the Explain record\n");
            out("</pre><pre>");
        }
        NodeList supports = getNodeList(explainDoc, ExplainResponsePath + "/exp:configInfo/exp:supports");
        baseURL = baseURL + "version=1.1";
        out('\n');

        // scan tests
        out("tests of Scan");
        out('\n');
        // let's see if they've said they don't support scan
        Node node;
        String type;
        for (i = 0; i < supports.getLength(); i++) {
            node = supports.item(i);
            type = getNodeText(node, "@type");
            if (type != null && type.equals("scan")) {
                if (getNodeText(node, null).equals("false")) {
                    scanSupported = false;
                    out(" scan not supported\n");
                }
                break;
            }
        }
        Document scanDoc = null;
        String index = null, scanable, scanResponse, set, term;
        for (i = 0; i < indexes.getLength() && scanSupported; i++) {
            node = indexes.item(i);
            set = getNodeText(node, "exp:map/exp:name/@set");
            if (set != null && set.length() > 0)
                index = set + "." + getNodeText(node, "exp:map/exp:name");
            else
                index = getNodeText(node, "exp:map/exp:name");
            scanable = getNodeText(node, "@scan");
            if (index.equals("cql.resultSetId") || (scanable != null && scanable.equals("false"))) {
                out("    skipping non-scanable index " + index + "\n");
                continue;
            }
            if (!scanIndex(index, "=", "dog"))
                failed();
            if (!scanIndex(index, "exact", "dog"))
                failed();
        }
        out('\n');

        // searchRetrieve tests
        Term t = null;
        out("tests of searchRetrieve");
        out('\n');
        if (vTerms.size() > 0) { // yay!  we have a list of good terms from the scan tests!
            for (i = 0; i < vTerms.size(); i++) {
                t = vTerms.get(i);
                if (!search(t))
                    failed();
                if (!search(new Term(t.index, t.relation, t.term + "xxxx", "0")))
                    failed();
            }
            termForTesting = t;
        }
        //            if(termForTesting==null) { // we'll walk through the index list again
        for (i = 0; i < indexes.getLength(); i++) {
            node = indexes.item(i);
            set = getNodeText(node, "exp:map/exp:name/@set");
            if (set != null && set.length() > 0)
                index = set + "." + getNodeText(node, "exp:map/exp:name");
            else
                index = getNodeText(node, "exp:map/exp:name");
            if (!index.equals("cql.resultSetId")) {
                if (!search(index, "=", "dog"))
                    failed();
                if (!search(index, "+exact+", "dog"))
                    failed();
            }
        }
        termForTesting = new Term(index, "=", "dog", "-1");
        //            }
    }

    testDiagnostics();

    out('\n');
    out(numWarns + " warnings given");
    out('\n');
    out(numTests + " tests given");
    out('\n');
    out(numFailed + " tests failed");
    out('\n');
    if (good)
        out("all test passed!");
    else
        out("problems detected!");
    out('\n');
    String ret = sb.toString();
    return ret;
}

From source file:org.eclipse.cft.server.core.internal.client.CloudFoundryServerBehaviour.java

/**
 * Creates a new client to the specified server URL using the given
 * credentials. This does NOT connect the client to the server, nor does it
 * set the client as the session client for the server behaviour. The
 * session client is set indirectly via {@link #connect(IProgressMonitor)}
 * @param serverURL server to connect to. Must NOT be null.
 * @param credentials must not be null.//  w  w w . ja va2 s  .  c o  m
 * @param cloudSpace optional. Can be null, as a client can be created
 * without specifying an org/space (e.g. a client can be created for the
 * purpose of looking up all the orgs/spaces in a server)
 * @param selfSigned true if connecting to a server with self signed
 * certificate. False otherwise
 * @return non-null client.
 * @throws CoreException if failed to create client.
 */
private static CloudFoundryOperations createClientWithCredentials(String serverURL,
        CloudCredentials credentials, CloudFoundrySpace cloudSpace, boolean selfSigned) throws CoreException {

    URL url;
    try {
        url = new URL(serverURL);
        int port = url.getPort();
        if (port == -1) {
            port = url.getDefaultPort();
        }

        // If no cloud space is specified, use appropriate client factory
        // API to create a non-space client
        // NOTE that using a space API with null org and space will result
        // in errors as that API will
        // expect valid org and space values.
        return cloudSpace != null
                ? CloudFoundryPlugin.getCloudFoundryClientFactory().getCloudFoundryOperations(credentials, url,
                        cloudSpace.getOrgName(), cloudSpace.getSpaceName(), selfSigned)
                : CloudFoundryPlugin.getCloudFoundryClientFactory().getCloudFoundryOperations(credentials, url,
                        selfSigned);
    } catch (MalformedURLException e) {
        throw new CoreException(new Status(IStatus.ERROR, CloudFoundryPlugin.PLUGIN_ID,
                "The server url " + serverURL + " is invalid: " + e.getMessage(), e)); //$NON-NLS-1$ //$NON-NLS-2$
    }
}

From source file:org.exjello.mail.Exchange2003Connection.java

private void signOn() throws Exception {
    HttpClient client = getClient();/*from w ww  . ja  v  a2 s. c  o  m*/
    URL serverUrl = new URL(server);
    String host = serverUrl.getHost();
    int port = serverUrl.getPort();
    if (port == -1)
        port = serverUrl.getDefaultPort();
    AuthScope authScope = new AuthScope(host, port);

    if (username.indexOf("\\") < 0) {
        client.getState().setCredentials(authScope, new UsernamePasswordCredentials(username, password));
    } else {
        // Try to connect with NTLM authentication
        String domainUser = username.substring(username.indexOf("\\") + 1, username.length());
        String domain = username.substring(0, username.indexOf("\\"));
        client.getState().setCredentials(authScope, new NTCredentials(domainUser, password, host, domain));
    }

    boolean authenticated = false;
    OptionsMethod authTest = new OptionsMethod(server + "/exchange");
    try {
        authenticated = (client.executeMethod(authTest) < 400);
    } finally {
        try {
            InputStream stream = authTest.getResponseBodyAsStream();
            byte[] buf = new byte[65536];
            try {
                if (session.getDebug()) {
                    PrintStream log = session.getDebugOut();
                    log.println("Response Body:");
                    int count;
                    while ((count = stream.read(buf, 0, 65536)) != -1) {
                        log.write(buf, 0, count);
                    }
                    log.flush();
                    log.println();
                } else {
                    while (stream.read(buf, 0, 65536) != -1)
                        ;
                }
            } catch (Exception ignore) {
            } finally {
                try {
                    stream.close();
                } catch (Exception ignore2) {
                }
            }
        } finally {
            authTest.releaseConnection();
        }
    }
    if (!authenticated) {
        PostMethod op = new PostMethod(server + SIGN_ON_URI);
        op.setRequestHeader("Content-Type", FORM_URLENCODED_CONTENT_TYPE);
        op.addParameter("destination", server + "/exchange");
        op.addParameter("flags", "0");
        op.addParameter("username", username);
        op.addParameter("password", password);
        try {
            int status = client.executeMethod(op);
            if (status >= 400) {
                throw new IllegalStateException("Sign-on failed: " + status);
            }
        } finally {
            try {
                InputStream stream = op.getResponseBodyAsStream();
                byte[] buf = new byte[65536];
                try {
                    if (session.getDebug()) {
                        PrintStream log = session.getDebugOut();
                        log.println("Response Body:");
                        int count;
                        while ((count = stream.read(buf, 0, 65536)) != -1) {
                            log.write(buf, 0, count);
                        }
                        log.flush();
                        log.println();
                    } else {
                        while (stream.read(buf, 0, 65536) != -1)
                            ;
                    }
                } catch (Exception ignore) {
                } finally {
                    try {
                        stream.close();
                    } catch (Exception ignore2) {
                    }
                }
            } finally {
                op.releaseConnection();
            }
        }
    }
    findInbox();
}

From source file:org.geotools.data.wfs.protocol.http.AbstractHttpProtocol.java

protected String createUri(final URL baseUrl, final Map<String, String> queryStringKvp) {
    final String query = baseUrl.getQuery();
    Map<String, String> finalKvpMap = new HashMap<String, String>(queryStringKvp);
    if (query != null && query.length() > 0) {
        Map<String, String> userParams = new CaseInsensitiveMap(queryStringKvp);
        String[] rawUrlKvpSet = query.split("&");
        for (String rawUrlKvp : rawUrlKvpSet) {
            int eqIdx = rawUrlKvp.indexOf('=');
            String key, value;//from  ww  w .  j a va2  s  .c  o m
            if (eqIdx > 0) {
                key = rawUrlKvp.substring(0, eqIdx);
                value = rawUrlKvp.substring(eqIdx + 1);
            } else {
                key = rawUrlKvp;
                value = null;
            }
            try {
                value = URLDecoder.decode(value, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
            if (userParams.containsKey(key)) {
                LOGGER.fine("user supplied value for query string argument " + key
                        + " overrides the one in the base url");
            } else {
                finalKvpMap.put(key, value);
            }
        }
    }

    String protocol = baseUrl.getProtocol();
    String host = baseUrl.getHost();
    int port = baseUrl.getPort();
    String path = baseUrl.getPath();

    StringBuilder sb = new StringBuilder();
    sb.append(protocol).append("://").append(host);
    if (port != -1 && port != baseUrl.getDefaultPort()) {
        sb.append(':');
        sb.append(port);
    }
    if (!"".equals(path) && !path.startsWith("/")) {
        sb.append('/');
    }
    sb.append(path).append('?');

    String key, value;
    try {
        Entry<String, String> kvp;
        for (Iterator<Map.Entry<String, String>> it = finalKvpMap.entrySet().iterator(); it.hasNext();) {
            kvp = it.next();
            key = kvp.getKey();
            value = kvp.getValue();
            if (value == null) {
                value = "";
            } else {
                value = URLEncoder.encode(value, "UTF-8");
            }
            sb.append(key);
            sb.append('=');
            sb.append(value);
            if (it.hasNext()) {
                sb.append('&');
            }
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }

    final String finalUrlString = sb.toString();
    return finalUrlString;
}

From source file:org.bonitasoft.connectors.rest.RESTConnector.java

/**
 * Execute a given request//w  ww. j a va 2s  . c  o m
 * 
 * @param request The request to execute
 * @return The response of the executed request
 * @throws Exception any exception that might occur
 */
public void execute(final Request request) throws Exception {
    CloseableHttpClient httpClient = null;

    try {
        final URL url = request.getUrl();
        final String urlHost = url.getHost();

        final Builder requestConfigurationBuilder = RequestConfig.custom();
        requestConfigurationBuilder.setConnectionRequestTimeout(CONNECTION_TIMEOUT);
        requestConfigurationBuilder.setRedirectsEnabled(request.isRedirect());

        final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
        setSSL(request.getSsl(), httpClientBuilder);
        setProxy(request.getProxy(), httpClientBuilder, requestConfigurationBuilder);
        setCookies(requestConfigurationBuilder, httpClientBuilder, request.getCookies(), urlHost);

        final RequestBuilder requestBuilder = getRequestBuilderFromMethod(request.getRestMethod());
        requestBuilder.setVersion(
                new ProtocolVersion(HTTP_PROTOCOL, HTTP_PROTOCOL_VERSION_MAJOR, HTTP_PROTOCOL_VERSION_MINOR));
        int urlPort = url.getPort();
        if (url.getPort() == -1) {
            urlPort = url.getDefaultPort();
        }
        final String urlProtocol = url.getProtocol();
        final String urlStr = url.toString();
        requestBuilder.setUri(urlStr);
        setHeaders(requestBuilder, request.getHeaders());
        if (!HTTPMethod.GET.equals(HTTPMethod.valueOf(requestBuilder.getMethod()))) {
            final String body = request.getBody();
            if (body != null) {
                requestBuilder.setEntity(new StringEntity(request.getBody(), request.getContentType()));
            }
        }

        final HttpContext httpContext = setAuthorizations(requestConfigurationBuilder,
                request.getAuthorization(), request.getProxy(), urlHost, urlPort, urlProtocol,
                httpClientBuilder);

        requestBuilder.setConfig(requestConfigurationBuilder.build());
        httpClientBuilder.setDefaultRequestConfig(requestConfigurationBuilder.build());

        final HttpUriRequest httpRequest = requestBuilder.build();
        httpClient = httpClientBuilder.build();
        final CloseableHttpResponse httpResponse = httpClient.execute(httpRequest, httpContext);
        LOGGER.fine("Request sent.");
        setOutputs(httpResponse, request);
    } finally {
        try {
            if (httpClient != null) {
                httpClient.close();
            }
        } catch (final IOException ex) {
            logException(ex);
        }
    }
}

From source file:net.www_eee.portal.channels.ProxyChannel.java

/**
 * <p>/*from  ww  w.  j av a  2  s. c o m*/
 * Do the supplied {@link URL}'s both point to the same {@linkplain URL#getHost() host} and {@linkplain URL#getPort()
 * port}?
 * </p>
 * 
 * <p>
 * If either of the supplied URL's don't specify a {@linkplain URL#getPort() port}, the
 * {@linkplain URL#getDefaultPort() default} will be used. If there is no default port, the comparison will fail
 * unless both have no default.
 * </p>
 * 
 * @param url1 The first URL.
 * @param url2 The second URL.
 * @return <code>true</code> if the URL's point to the same host and port.
 * @throws IllegalArgumentException If <code>url1</code> or <code>url2</code> is <code>null</code>.
 */
protected static final boolean equalHostAndPort(final @Nullable URL url1, final @Nullable URL url2)
        throws IllegalArgumentException {
    if (url1 == null)
        throw new IllegalArgumentException("null url1");
    if (url2 == null)
        throw new IllegalArgumentException("null url2");
    if (!StringUtil.equal(StringUtil.mkNull(url1.getHost()), StringUtil.mkNull(url2.getHost()), false))
        return false;
    final int url1Port = (url1.getPort() >= 0) ? url1.getPort() : url1.getDefaultPort();
    final int url2Port = (url2.getPort() >= 0) ? url2.getPort() : url2.getDefaultPort();
    if (url1Port != url2Port)
        return false;
    return true;
}