Example usage for java.net URI getPort

List of usage examples for java.net URI getPort

Introduction

In this page you can find the example usage for java.net URI getPort.

Prototype

public int getPort() 

Source Link

Document

Returns the port number of this URI.

Usage

From source file:com.subgraph.vega.impl.scanner.urls.ResponseAnalyzer.java

private URI stripQuery(URI uri) {
    try {//from  www  .  ja  v a 2s. c  o  m
        return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), null,
                null);
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:com.eviware.soapui.impl.rest.actions.oauth.OltuOAuth2ClientFacade.java

private void appendAccessTokenToQuery(HttpRequestBase request, OAuthBearerClientRequest oAuthClientRequest)
        throws OAuthSystemException {
    String queryString = getQueryStringFromOAuthClientRequest(oAuthClientRequest);
    URI oldUri = request.getURI();
    String requestQueryString = oldUri.getQuery() != null ? oldUri.getQuery() + "&" + queryString : queryString;

    try {//from  w  w w  . jav  a 2 s  .com
        request.setURI(URIUtils.createURI(oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
                oldUri.getRawPath(), requestQueryString, oldUri.getFragment()));
    } catch (URISyntaxException e) {
        throw new OAuthSystemException(e);
    }
}

From source file:com.couchbase.client.ClusterManager.java

/**
 * Connects to a given server if a connection has not been made to at least
 * one of the servers in the server list already.
 * @param uri/*from w  w  w. ja va2s .c o m*/
 * @return
 */
private boolean connect(URI uri) {
    host = new HttpHost(uri.getHost(), uri.getPort());
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
    try {
        if (!conn.isOpen()) {
            Socket socket = new Socket(host.getHostName(), host.getPort());
            conn.bind(socket, new SyncBasicHttpParams());
        }
        return true;
    } catch (IOException e) {
        return false;
    }
}

From source file:com.codeabovelab.dm.gateway.proxy.common.HttpProxyContext.java

public HttpProxyContext(HttpServletRequest request, HttpServletResponse response, URI target, String uid) {
    this.request = request;
    Assert.notNull(request, "request is null");
    this.response = response;
    Assert.notNull(response, "response is null");
    this.target = target;
    Assert.notNull(target, "target is null");
    this.targetHost = new HttpHost(target.getHost(), target.getPort(), target.getScheme());
    this.uid = uid;

}

From source file:org.sonatype.nexus.testsuite.security.nexus4383.Nexus4383LogoutResourceIT.java

/**
 * 1.) Make a get request to set a cookie </BR>
 * 2.) verify cookie works (do not send basic auth) </BR>
 * 3.) do logout  </BR>/*ww  w  .j  a  v  a  2  s  . c  o m*/
 * 4.) repeat step 2 and expect failure.
 */
@Test
public void testLogout() throws Exception {
    TestContext context = TestContainer.getInstance().getTestContext();
    String username = context.getAdminUsername();
    String password = context.getPassword();
    String url = this.getBaseNexusUrl() + RequestFacade.SERVICE_LOCAL + "status";
    String logoutUrl = this.getBaseNexusUrl() + RequestFacade.SERVICE_LOCAL + "authentication/logout";

    Header userAgentHeader = new BasicHeader("User-Agent", "Something Stateful");

    // default useragent is: Jakarta Commons-HttpClient/3.1[\r][\n]
    DefaultHttpClient httpClient = new DefaultHttpClient();
    URI nexusBaseURI = new URI(url);
    final BasicHttpContext localcontext = new BasicHttpContext();
    final HttpHost targetHost = new HttpHost(nexusBaseURI.getHost(), nexusBaseURI.getPort(),
            nexusBaseURI.getScheme());
    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    // HACK: Disable CSRFGuard support for now, its too problematic
    //String owaspQueryParams = null;
    HttpGet getMethod = new HttpGet(url);
    getMethod.addHeader(userAgentHeader);
    try {
        CloseableHttpResponse response = httpClient.execute(getMethod, localcontext);
        // HACK: Disable CSRFGuard support for now, its too problematic
        //Header owaspCsrfToken = response.getFirstHeader("OWASP_CSRFTOKEN");
        //assertThat(owaspCsrfToken, is(notNullValue()));
        //owaspQueryParams = "?" + owaspCsrfToken.getName() + "=" + owaspCsrfToken.getValue();
        Assert.assertEquals(response.getStatusLine().getStatusCode(), 200);
    } finally {
        getMethod.reset();
    }

    Cookie sessionCookie = this.getSessionCookie(httpClient.getCookieStore().getCookies());
    Assert.assertNotNull("Session Cookie not set", sessionCookie);

    httpClient.getCookieStore().clear(); // remove cookies
    httpClient.getCredentialsProvider().clear(); // remove auth

    // now with just the cookie
    httpClient.getCookieStore().addCookie(sessionCookie);
    // HACK: Disable CSRFGuard support for now, its too problematic
    //getMethod = new HttpGet(url + owaspQueryParams);
    getMethod = new HttpGet(url);
    try {
        Assert.assertEquals(httpClient.execute(getMethod).getStatusLine().getStatusCode(), 200);
    } finally {
        getMethod.reset();
    }

    // do logout
    // HACK: Disable CSRFGuard support for now, its too problematic
    //HttpGet logoutGetMethod = new HttpGet(logoutUrl + owaspQueryParams);
    HttpGet logoutGetMethod = new HttpGet(logoutUrl);
    try {
        final HttpResponse response = httpClient.execute(logoutGetMethod);
        Assert.assertEquals(response.getStatusLine().getStatusCode(), 200);
        Assert.assertEquals("OK", EntityUtils.toString(response.getEntity()));
    } finally {
        logoutGetMethod.reset();
    }

    // set cookie again
    httpClient.getCookieStore().clear(); // remove cookies
    httpClient.getCredentialsProvider().clear(); // remove auth

    httpClient.getCookieStore().addCookie(sessionCookie);
    HttpGet failedGetMethod = new HttpGet(url);
    try {
        final HttpResponse response = httpClient.execute(failedGetMethod);
        Assert.assertEquals(response.getStatusLine().getStatusCode(), 401);
    } finally {
        failedGetMethod.reset();
    }
}

From source file:com.fatwire.dta.sscrawler.App.java

private HostConfig createHostConfig(final URI uri) {
    final HostConfig hostConfig = new HostConfig();

    hostConfig.setHostname(uri.getHost());

    hostConfig.setPort(uri.getPort() == -1 ? 80 : uri.getPort());
    hostConfig.setDomain(uri.getPath());
    hostConfig.setProtocol(uri.getScheme());

    return hostConfig;

}

From source file:org.apache.zeppelin.notebook.repo.zeppelinhub.rest.HttpProxyClient.java

private CloseableHttpAsyncClient getAsyncProxyHttpClient(URI proxyUri) {
    LOG.info("Creating async proxy http client");
    PoolingNHttpClientConnectionManager cm = getAsyncConnectionManager();
    HttpHost proxy = new HttpHost(proxyUri.getHost(), proxyUri.getPort());

    HttpAsyncClientBuilder clientBuilder = HttpAsyncClients.custom();
    if (cm != null) {
        clientBuilder = clientBuilder.setConnectionManager(cm);
    }// w w w .j  a  v a 2s  . c  o  m

    if (proxy != null) {
        clientBuilder = clientBuilder.setProxy(proxy);
    }
    clientBuilder = setRedirects(clientBuilder);
    return clientBuilder.build();
}

From source file:org.coffeebreaks.validators.w3c.W3cMarkupValidator.java

private ValidationResult validateW3cMarkup(String type, String value, boolean get) throws IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpRequestBase method;// ww  w.j ava2 s .c o  m
    if (get) {
        List<NameValuePair> qParams = new ArrayList<NameValuePair>();
        qParams.add(new BasicNameValuePair("output", "soap12"));
        qParams.add(new BasicNameValuePair(type, value));

        try {
            URI uri = new URI(baseUrl + (baseUrl.endsWith("/") ? "" : "/") + "check");
            URI uri2 = URIUtils.createURI(uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath(),
                    URLEncodedUtils.format(qParams, "UTF-8"), null);
            method = new HttpGet(uri2);
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException("invalid uri. Check your baseUrl " + baseUrl, e);
        }
    } else {
        HttpPost httpPost = new HttpPost(baseUrl + (baseUrl.endsWith("/") ? "" : "/") + "check");
        List<NameValuePair> formParams = new ArrayList<NameValuePair>();
        formParams.add(new BasicNameValuePair("output", "soap12"));
        formParams.add(new BasicNameValuePair(type, value));
        UrlEncodedFormEntity requestEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
        httpPost.setEntity(requestEntity);
        method = httpPost;
    }
    HttpResponse response = httpclient.execute(method);
    HttpEntity responseEntity = response.getEntity();
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode >= HttpStatus.SC_BAD_REQUEST) {
        throw new IllegalStateException(
                "Unexpected HTTP status code: " + statusCode + ". Implementation error ?");
    }
    if (responseEntity == null) {
        throw new IllegalStateException(
                "No entity but HTTP status code: " + statusCode + ". Server side error ?");
    }

    InputStream entityContentInputStream = responseEntity.getContent();
    StringWriter output = new StringWriter();
    IOUtils.copy(entityContentInputStream, output, "UTF-8");
    final String soap = output.toString();

    // we can use the response headers instead of the soap
    // final W3cSoapValidatorSoapOutput soapObject = parseSoapObject(soap);

    String headerValue = getHeaderValue(response, "X-W3C-Validator-Status");
    final boolean indeterminate = headerValue.equals("Abort");
    final int errorCount = Integer.parseInt(getHeaderValue(response, "X-W3C-Validator-Errors"));
    final int warningCount = Integer.parseInt(getHeaderValue(response, "X-W3C-Validator-Warnings"));

    return new ValidationResult() {
        public boolean isResultIndeterminate() {
            return indeterminate;
        }

        public int getErrorCount() {
            return errorCount;
        }

        public int getWarningCount() {
            return warningCount;
        }

        public String getResponseContent() {
            return soap;
        }
    };
}

From source file:com.linkedin.r2.message.rest.QueryTunnelUtil.java

/**
 * @param request   a RestRequest object to be encoded as a tunneled POST
 * @param requestContext a RequestContext object associated with the request
 * @param threshold the size of the query params above which the request will be encoded
 *
 * @return an encoded RestRequest/*from   www .ja v  a  2s. c  o m*/
 */
public static RestRequest encode(final RestRequest request, RequestContext requestContext, int threshold)
        throws URISyntaxException, MessagingException, IOException {
    URI uri = request.getURI();

    // Check to see if we should tunnel this request by testing the length of the query
    // if the query is NULL, we won't bother to encode.
    // 0 length is a special case that could occur with a url like http://www.foo.com?
    // which we don't want to encode, because we'll lose the "?" in the process
    // Otherwise only encode queries whose length is greater than or equal to the
    // threshold value.

    String query = uri.getRawQuery();

    boolean forceQueryTunnel = requestContext.getLocalAttr(R2Constants.FORCE_QUERY_TUNNEL) != null
            && (Boolean) requestContext.getLocalAttr(R2Constants.FORCE_QUERY_TUNNEL);

    if (query == null || query.length() == 0 || (query.length() < threshold && !forceQueryTunnel)) {
        return request;
    }

    RestRequestBuilder requestBuilder = new RestRequestBuilder(request);

    // reconstruct URI without query
    uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), null,
            uri.getFragment());

    // If there's no existing body, just pass the request as x-www-form-urlencoded
    ByteString entity = request.getEntity();
    if (entity == null || entity.length() == 0) {
        requestBuilder.setHeader(HEADER_CONTENT_TYPE, FORM_URL_ENCODED);
        requestBuilder.setEntity(ByteString.copyString(query, Data.UTF_8_CHARSET));
    } else {
        // If we have a body, we must preserve it, so use multipart/mixed encoding

        MimeMultipart multi = createMultiPartEntity(entity, request.getHeader(HEADER_CONTENT_TYPE), query);
        requestBuilder.setHeader(HEADER_CONTENT_TYPE, multi.getContentType());
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        multi.writeTo(os);
        requestBuilder.setEntity(ByteString.copy(os.toByteArray()));
    }

    // Set the base uri, supply the original method in the override header, and change method to POST
    requestBuilder.setURI(uri);
    requestBuilder.setHeader(HEADER_METHOD_OVERRIDE, requestBuilder.getMethod());
    requestBuilder.setMethod(RestMethod.POST);

    return requestBuilder.build();
}