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:net.sf.jsptest.compiler.jsp20.mock.MockHttpServletRequest.java

public void setRequestURL(String requestUrl) {
    try {/*from w ww  .  j  a va 2s .co  m*/
        URL url = new URL(requestUrl);
        setScheme(url.getProtocol());
        setServerName(url.getHost());
        setServerPort(url.getPort());
        setRequestURI(url.getPath());
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}

From source file:it.geosdi.era.server.servlet.HTTPProxy.java

/**
 * Retreives all of the headers from the servlet request and sets them on
 * the proxy request/* w  w w. ja  v a  2s .c o m*/
 * 
 * @param httpServletRequest The request object representing the client's
 *                            request to the servlet engine
 * @param httpMethodProxyRequest The request that we are about to send to
 *                                the proxy host
 */
@SuppressWarnings("unchecked")
private void setProxyRequestHeaders(URL url, HttpServletRequest httpServletRequest,
        HttpMethod httpMethodProxyRequest) {
    this.stringProxyHost = url.getHost();
    this.intProxyPort = url.getPort();
    this.stringProxyPath = url.getPath();

    // Get an Enumeration of all of the header names sent by the client
    Enumeration enumerationOfHeaderNames = httpServletRequest.getHeaderNames();
    while (enumerationOfHeaderNames.hasMoreElements()) {
        String stringHeaderName = (String) enumerationOfHeaderNames.nextElement();
        if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME))
            continue;
        // As per the Java Servlet API 2.5 documentation:
        //      Some headers, such as Accept-Language can be sent by clients
        //      as several headers each with a different value rather than
        //      sending the header as a comma separated list.
        // Thus, we get an Enumeration of the header values sent by the client
        Enumeration enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName);
        while (enumerationOfHeaderValues.hasMoreElements()) {
            String stringHeaderValue = (String) enumerationOfHeaderValues.nextElement();
            // In case the proxy host is running multiple virtual servers,
            // rewrite the Host header to ensure that we get content from
            // the correct virtual server
            if (stringHeaderName.equalsIgnoreCase(STRING_HOST_HEADER_NAME)) {
                stringHeaderValue = getProxyHostAndPort();
            }
            // Skip GZIP Responses
            if (stringHeaderName.equalsIgnoreCase(HTTP_HEADER_ACCEPT_ENCODING)
                    && stringHeaderValue.toLowerCase().contains("gzip"))
                continue;
            if (stringHeaderName.equalsIgnoreCase(HTTP_HEADER_CONTENT_ENCODING)
                    && stringHeaderValue.toLowerCase().contains("gzip"))
                continue;
            if (stringHeaderName.equalsIgnoreCase(HTTP_HEADER_TRANSFER_ENCODING))
                continue;
            Header header = new Header(stringHeaderName, stringHeaderValue);
            // Set the same header on the proxy request
            httpMethodProxyRequest.setRequestHeader(header);
        }
    }
}

From source file:com.google.acre.appengine.script.AppEngineAsyncUrlfetch.java

private Scriptable callback_result(AsyncRequest req, HTTPResponse res) {

    long waiting_time = System.currentTimeMillis() - req.start_time;

    URL furl = res.getFinalUrl();
    if (furl == null) {
        furl = req.url;/*from  w  w  w.j a  v a  2s.c  o  m*/
    }

    BrowserCompatSpecFactory bcsf = new BrowserCompatSpecFactory();
    CookieSpec cspec = bcsf.newInstance(null);
    String protocol = furl.getProtocol();
    boolean issecure = ("https".equals(protocol));
    int port = furl.getPort();
    if (port == -1)
        port = 80;
    CookieOrigin origin = new CookieOrigin(furl.getHost(), port, furl.getPath(), issecure);

    Context ctx = Context.getCurrentContext();
    Scriptable out = ctx.newObject(_scope);
    Scriptable headers = ctx.newObject(_scope);
    Scriptable cookies = ctx.newObject(_scope);

    out.put("status", out, res.getResponseCode());

    String response_body = null;

    try {
        response_body = new String(res.getContent(), getResponseEncoding(res));
        out.put("body", out, response_body);
    } catch (java.io.UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }

    out.put("headers", out, headers);
    out.put("cookies", out, cookies);

    StringBuilder response_header_log = new StringBuilder();
    for (HTTPHeader h : res.getHeaders()) {
        if (h.getName().equalsIgnoreCase("set-cookie")) {
            String set_cookie = h.getValue();
            Matcher m = Pattern.compile("\\s*(([^,]|(,\\s*\\d))+)").matcher(set_cookie);
            while (m.find()) {
                Header ch = new BasicHeader("Set-Cookie", set_cookie.substring(m.start(), m.end()));
                try {
                    List<Cookie> pcookies = cspec.parse(ch, origin);
                    for (Cookie c : pcookies) {
                        cookies.put(c.getName(), cookies, new AcreCookie(c).toJsObject(_scope));
                    }
                } catch (MalformedCookieException e) {
                    // we've occasionally choked on cookie-set,
                    // e.g. www.google.com returning expires=; expires=Mon, 01-Jan-1990 00:00:00 GMT;
                    // no solution but at least log exactly what's happening.
                    String cookiestring = ch.toString();
                    _logger.warn("urlfetch.response.async", "exception thrown on bad cookie " + cookiestring);
                    throw new RuntimeException(e);
                }
            }
        }

        headers.put(h.getName(), headers, h.getValue());
        response_header_log.append(h.getName() + ": " + h.getValue() + ", ");
    }

    boolean system = req.system;
    boolean log_to_user = req.log_to_user;

    String log_body = new String();
    if (res.getResponseCode() != 200 && response_body != null) {
        log_body = response_body;
    }

    _logger.syslog4j("INFO", "urlfetch.response.async", "URL", furl.toString(), "Status",
            Integer.toString(res.getResponseCode()), "Headers", response_header_log, "Body", log_body);

    if (system && log_to_user) {
        _response.userlog4j("INFO", "urlfetch.response.async", "URL", furl.toString(), "Status",
                Integer.toString(res.getResponseCode()), "Headers", response_header_log);
    }

    _costCollector.collect((system) ? "asuc" : "auuc").collect((system) ? "asuw" : "auuw", waiting_time);

    return out;
}

From source file:org.jboss.as.test.integration.domain.suites.ResponseStreamTestCase.java

private HttpClient getHttpClient(URL url) {
    shutdownHttpClient();//from w w w.  j ava  2 s. co  m
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
            new AuthScope(url.getHost(), url.getPort(), "ManagementRealm", AuthSchemes.DIGEST),
            new UsernamePasswordCredentials(DomainLifecycleUtil.SLAVE_HOST_USERNAME,
                    DomainLifecycleUtil.SLAVE_HOST_PASSWORD));

    httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build();

    return httpClient;
}

From source file:org.openqa.grid.internal.utils.SelfRegisteringRemote.java

private void registerToHub(boolean checkPresenceFirst) {
    if (!checkPresenceFirst || !isAlreadyRegistered(nodeConfig)) {
        String tmp = "http://" + nodeConfig.getConfiguration().get(RegistrationRequest.HUB_HOST) + ":"
                + nodeConfig.getConfiguration().get(RegistrationRequest.HUB_PORT) + "/grid/register";

        HttpClient client = httpClientFactory.getHttpClient();
        try {/* w  w w . j  av a2s  .  c  om*/
            URL registration = new URL(tmp);
            log.info("Registering the node to hub :" + registration);

            BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST",
                    registration.toExternalForm());
            String json = nodeConfig.toJSON();
            r.setEntity(new StringEntity(json));

            HttpHost host = new HttpHost(registration.getHost(), registration.getPort());
            HttpResponse response = client.execute(host, r);
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new RuntimeException("Error sending the registration request.");
            }
        } catch (Exception e) {
            throw new GridException("Error sending the registration request.", e);
        }
    } else {
        log.fine("The node is already present on the hub. Skipping registration.");
    }

}

From source file:client.lib.Client.java

public int test(String url) throws IOException, MalformedURLException {
    int successful = 0;
    URL entry = new URL(url);

    Request request = new Request.Builder().url(entry.toString()).build();

    Response response = httpClient.newCall(request).execute();
    System.out.println(response.protocol());

    try {//from  www . ja  v a  2s.  c  om
        JSONObject json = new JSONObject(response.body().string());

        JSONArray urls = json.getJSONArray("urls");
        for (int i = 0; i < urls.length(); ++i) {
            response = request(http2Client, new URL(urls.getString(i)));
            if (response != null) {
                successful++;
            }
        }

        URL finish = new URL(entry.getProtocol(), entry.getHost(), entry.getPort(), json.getString("finish"));
        request(httpClient, finish);

    } catch (JSONException e) {
        System.out.println(e.getMessage());
    }

    return successful;
}

From source file:com.tremolosecurity.proxy.filter.PostProcess.java

private void fixRedirect(HttpFilterRequest req, HttpFilterResponse resp, String finalURL,
        org.apache.http.Header header) {
    String location = header.getValue();
    if (logger.isDebugEnabled()) {
        logger.debug("Current Location : '" + location + "'");
    }//  w  ww.j ava 2 s. c o m

    if (location.startsWith("/")) {

        StringBuffer b = new StringBuffer();
        b.append((req.isSecure() ? "https" : "http")).append("://").append(req.getServerName());
        if (!(req.getServerPort() == 80 || req.getServerPort() == 443)) {
            b.append(':').append(req.getServerPort());
        }
        b.append(location);

        location = b.toString();
        if (logger.isDebugEnabled()) {
            logger.debug("New Location : '" + location + "'");
        }

        resp.addHeader("Location", location);
    } else {
        try {
            URL url = new URL(location);
            URL target = new URL(finalURL);

            if (!(url.getProtocol().equalsIgnoreCase(target.getProtocol())
                    && url.getHost().equalsIgnoreCase(target.getHost())
                    && (url.getPort() == target.getPort()))) {
                resp.addHeader("Location", location);
            } else {

                StringBuffer b = new StringBuffer();
                b.append((req.isSecure() ? "https" : "http")).append("://").append(req.getServerName());
                if (!(req.getServerPort() == 80 || req.getServerPort() == 443)) {
                    b.append(':').append(req.getServerPort());
                }
                b.append(url.getPath());

                if (url.getQuery() != null) {
                    b.append('?').append(url.getQuery());
                }

                location = b.toString();
                if (logger.isDebugEnabled()) {
                    logger.debug("New Location : '" + location + "'");
                }
                resp.addHeader("Location", location);
            }
        } catch (MalformedURLException e) {
            //not a url, so let the browser worry about it
            resp.addHeader("Location", location);
        }

    }
}

From source file:com.servoy.extensions.plugins.http.BaseRequest.java

private Response executeRequest(String userName, String password, String workstation, String domain,
        boolean windowsAuthentication) throws Exception {
    HttpEntity entity = buildEntity();//from   w ww.  j av a 2 s.co  m
    if (entity != null)
        ((HttpEntityEnclosingRequestBase) method).setEntity(entity);

    Iterator<String> it = headers.keySet().iterator();
    while (it.hasNext()) {
        String name = it.next();
        String[] values = headers.get(name);
        for (String value : values) {
            method.addHeader(name, value);
        }
    }

    if (!Utils.stringIsEmpty(userName)) {
        BasicCredentialsProvider bcp = new BasicCredentialsProvider();
        URL _url = HttpProvider.createURLFromString(url, access);
        Credentials cred = null;
        if (windowsAuthentication) {
            if (context == null) {
                context = new BasicHttpContext();
            }
            cred = new NTCredentials(userName, password, workstation, domain);
        } else {
            cred = new UsernamePasswordCredentials(userName, password);
        }
        bcp.setCredentials(new AuthScope(_url.getHost(), _url.getPort()), cred);
        client.setCredentialsProvider(bcp);
    }

    return new Response(client.execute(method, context));
}

From source file:nya.miku.wishmaster.chans.dobrochan.DobroModule.java

private String sanitizeUrl(String urlStr) {
    if (urlStr == null)
        return null;
    try {/* w  w w .  j a  va2  s .  c o  m*/
        URL url = new URL(urlStr);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        return uri.toURL().toString();
    } catch (Exception e) {
        Logger.e(TAG, "sanitize url", e);
        return urlStr;
    }
}

From source file:com.xpn.xwiki.web.XWikiServletURLFactory.java

/**
 * {@inheritDoc}// w w  w .  j av  a  2s  .  c o  m
 * 
 * @see com.xpn.xwiki.web.XWikiDefaultURLFactory#getRequestURL(com.xpn.xwiki.XWikiContext)
 */
@Override
public URL getRequestURL(XWikiContext context) {
    final URL url = super.getRequestURL(context);
    try {
        final URL servurl = getServerURL(context);
        // if use apache mod_proxy we needed to know external host address
        return new URL(servurl.getProtocol(), servurl.getHost(), servurl.getPort(), url.getFile());
    } catch (MalformedURLException ex) {
        // This should not happen
        ex.printStackTrace();
        return url;
    }
}