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.vp9.plugin.WebSocket.java

/**
 * Create the uri./*ww  w. j a  v a 2 s  .co  m*/
 * @param uriString
 * @return
 * @throws URISyntaxException
 */
private URI createURI(String uriString) throws URISyntaxException {
    URI uri = new URI(uriString);
    int port = uri.getPort();

    if (port == -1) {
        if ("ws".equals(uri.getScheme())) {
            port = 80;
        } else if ("wss".equals(uri.getScheme())) {
            port = 443;
        }
        uri = URIUtils.createURI(uri.getScheme(), uri.getHost(), port, uri.getPath(), uri.getQuery(),
                uri.getFragment());
    }
    return uri;
}

From source file:org.apache.hadoop.gateway.dispatch.AppCookieManager.java

/**
 * Fetches hadoop.auth cookie from hadoop service authenticating using SpNego
 * /*w  w  w  .  j a v a 2s . c o m*/
 * @param outboundRequest
 *          out going request
 * @param refresh
 *          flag indicating whether to refresh the cached cookie
 * @return hadoop.auth cookie from hadoop service authenticating using SpNego
 * @throws IOException
 *           in case of errors
 */
public String getAppCookie(HttpUriRequest outboundRequest, boolean refresh) throws IOException {

    URI uri = outboundRequest.getURI();
    String scheme = uri.getScheme();
    String host = uri.getHost();
    int port = uri.getPort();
    if (!refresh) {
        if (appCookie != null) {
            return appCookie;
        }
    }

    DefaultHttpClient client = new DefaultHttpClient();
    SPNegoSchemeFactory spNegoSF = new SPNegoSchemeFactory(/* stripPort */true);
    // spNegoSF.setSpengoGenerator(new BouncySpnegoTokenGenerator());
    client.getAuthSchemes().register(AuthPolicy.SPNEGO, spNegoSF);
    client.getCredentialsProvider().setCredentials(new AuthScope(/* host */null, /* port */-1, /* realm */null),
            EMPTY_JAAS_CREDENTIALS);

    clearAppCookie();
    String hadoopAuthCookie = null;
    HttpResponse httpResponse = null;
    try {
        HttpHost httpHost = new HttpHost(host, port, scheme);
        HttpRequest httpRequest = createKerberosAuthenticationRequest(outboundRequest);
        httpResponse = client.execute(httpHost, httpRequest);
        Header[] headers = httpResponse.getHeaders(SET_COOKIE);
        hadoopAuthCookie = getHadoopAuthCookieValue(headers);
        EntityUtils.consume(httpResponse.getEntity());
        if (hadoopAuthCookie == null) {
            LOG.failedSPNegoAuthn(uri.toString());
            auditor.audit(Action.AUTHENTICATION, uri.toString(), ResourceType.URI, ActionOutcome.FAILURE);
            throw new IOException("SPNego authn failed, can not get hadoop.auth cookie");
        }
    } finally {
        if (httpResponse != null) {
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                entity.getContent().close();
            }
        }

    }
    LOG.successfulSPNegoAuthn(uri.toString());
    auditor.audit(Action.AUTHENTICATION, uri.toString(), ResourceType.URI, ActionOutcome.SUCCESS);
    hadoopAuthCookie = HADOOP_AUTH_EQ + quote(hadoopAuthCookie);
    setAppCookie(hadoopAuthCookie);
    return appCookie;
}

From source file:org.apache.olingo.odata2.fit.misc.CxfCacheUriInfoIssueTest.java

@Test
public void checkContextForDifferentWithHostHeader()
        throws ClientProtocolException, IOException, ODataException, URISyntaxException {
    try {/*from  ww w  . ja va  2  s .  c  om*/
        FitStaticServiceFactory.bindService("123", getService());

        // 1st request: cache uri
        URI uri = URI.create(getEndpoint().toString() + "$metadata");
        HttpGet get1 = new HttpGet(uri);
        HttpResponse response1 = getHttpClient().execute(get1);
        assertNotNull(response1);

        URI serviceRoot1 = getService().getProcessor().getContext().getPathInfo().getServiceRoot();
        assertEquals(uri.getHost(), serviceRoot1.getHost());

        get1.reset();

        HttpGet get2 = new HttpGet(uri);
        get2.addHeader("Host", "bla:123");
        HttpResponse response2 = getHttpClient().execute(get2);
        assertNotNull(response2);

        URI serviceRoot2 = getService().getProcessor().getContext().getPathInfo().getServiceRoot();
        assertEquals("bla", serviceRoot2.getHost());
        assertEquals(123, serviceRoot2.getPort());

        URI requestUri = getService().getProcessor().getContext().getPathInfo().getRequestUri();
        assertEquals("bla", requestUri.getHost());
        assertEquals(123, requestUri.getPort());

    } finally {
        FitStaticServiceFactory.unbindService("123");
    }
}

From source file:com.rinxor.cloud.cloudstack.api.CloudstackClient.java

public CloudstackResponse executeApiChangeJsonPostToGetRedirect(CloudstackRequest cloudstackRequest) {

    CloudstackResponse cloudstackResponse = new CloudstackResponse();
    try {/*w ww. j  av a2 s. c o m*/
        JSONObject obj = new JSONObject(cloudstackRequest.getUrlCommand());
        String urlCommand = "response=json&";

        Iterator itr = obj.keys();
        while (itr.hasNext()) {
            Object element = itr.next();
            String key = (String) element;
            urlCommand += key + "=" + (String) obj.get(key) + "&";
        }
        System.out.println("request: " + urlCommand);

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet getRequest = new HttpGet(CloudstackAPI.buildApiRequestURL(cfg.getApiUrl(), urlCommand));

        getRequest.addHeader("Cookie", cloudstackRequest.getCookie());
        getRequest.addHeader("Referer", cloudstackRequest.getReferer());
        URI u = new URI(cfg.getApiUrl());
        getRequest.addHeader("Host", u.getHost() + ":" + u.getPort());

        HttpResponse response = httpClient.execute(getRequest);

        cloudstackResponse.setStatusCode(response.getStatusLine().getStatusCode());
        cloudstackResponse.setResponseBody(EntityUtils.toString(response.getEntity()));

        if (response.getFirstHeader("Set-Cookie") != null) {
            cloudstackResponse.setSetCookie(response.getFirstHeader("Set-Cookie").getValue());
        }

    } catch (JSONException ex) {
        Logger.getLogger(CloudstackClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(CloudstackClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (URISyntaxException ex) {
        Logger.getLogger(CloudstackClient.class.getName()).log(Level.SEVERE, null, ex);
    }

    return cloudstackResponse;
}

From source file:net.bluemix.connectors.core.info.CloudantServiceInfo.java

public CloudantServiceInfo(String id, String url) throws URISyntaxException {
    super(id);//w w  w  .  j  a  va2 s  . c o  m
    URI uri = new URI(url);
    this.url = url.replaceFirst(CloudantServiceInfo.SCHEME, "http");
    this.host = uri.getHost();
    this.port = uri.getPort();
    String serviceInfoString = uri.getUserInfo();
    if (serviceInfoString != null) {
        String[] userInfo = serviceInfoString.split(":");
        this.username = userInfo[0];
        this.password = userInfo[1];
    }
}

From source file:org.apache.ambari.server.controller.internal.AppCookieManager.java

/**
 * Returns hadoop.auth cookie, doing needed SPNego authentication
 * //from w  ww. j  a  v a 2  s .  c o m
 * @param endpoint
 *          the URL of the Hadoop service
 * @param refresh
 *          flag indicating wehther to refresh the cookie, if
 *          <code>true</code>, we do a new SPNego authentication and refresh
 *          the cookie even if the cookie already exists in local cache
 * @return hadoop.auth cookie value
 * @throws IOException
 *           in case of problem getting hadoop.auth cookie
 */
public String getAppCookie(String endpoint, boolean refresh) throws IOException {

    HttpUriRequest outboundRequest = new HttpGet(endpoint);
    URI uri = outboundRequest.getURI();
    String scheme = uri.getScheme();
    String host = uri.getHost();
    int port = uri.getPort();
    String path = uri.getPath();
    if (!refresh) {
        String appCookie = endpointCookieMap.get(endpoint);
        if (appCookie != null) {
            return appCookie;
        }
    }

    clearAppCookie(endpoint);

    DefaultHttpClient client = new DefaultHttpClient();
    SPNegoSchemeFactory spNegoSF = new SPNegoSchemeFactory(/* stripPort */true);
    // spNegoSF.setSpengoGenerator(new BouncySpnegoTokenGenerator());
    client.getAuthSchemes().register(AuthPolicy.SPNEGO, spNegoSF);
    client.getCredentialsProvider().setCredentials(new AuthScope(/* host */null, /* port */-1, /* realm */null),
            EMPTY_JAAS_CREDENTIALS);

    String hadoopAuthCookie = null;
    HttpResponse httpResponse = null;
    try {
        HttpHost httpHost = new HttpHost(host, port, scheme);
        HttpRequest httpRequest = new HttpOptions(path);
        httpResponse = client.execute(httpHost, httpRequest);
        Header[] headers = httpResponse.getHeaders(SET_COOKIE);
        hadoopAuthCookie = getHadoopAuthCookieValue(headers);
        if (hadoopAuthCookie == null) {
            LOG.error("SPNego authentication failed, can not get hadoop.auth cookie for URL: " + endpoint);
            throw new IOException("SPNego authentication failed, can not get hadoop.auth cookie");
        }
    } finally {
        if (httpResponse != null) {
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                entity.getContent().close();
            }
        }

    }

    hadoopAuthCookie = HADOOP_AUTH_EQ + quote(hadoopAuthCookie);
    setAppCookie(endpoint, hadoopAuthCookie);
    if (LOG.isInfoEnabled()) {
        LOG.info("Successful SPNego authentication to URL:" + uri.toString());
    }
    return hadoopAuthCookie;
}

From source file:org.fao.geonet.MockRequestFactoryGeonet.java

@Override
public ClientHttpResponse execute(HttpUriRequest request, Function<HttpClientBuilder, Void> configurator)
        throws IOException {
    final URI uri = request.getURI();
    final Request key = new Request(uri.getHost(), uri.getPort(), uri.getScheme(), null);
    final XmlRequest xmlRequest = (XmlRequest) getRequest(key);
    return new MockClientHttpResponse(Xml.getString(xmlRequest.execute()).getBytes(Constants.CHARSET),
            HttpStatus.OK);//from  www .  j  av  a  2s. c o m
}

From source file:com.thoughtworks.go.util.command.UrlArgument.java

@Override
public String forDisplay() {
    try {/*from   w w  w .j  av  a2 s. c  o m*/
        URI uri = new URI(sanitizeUrl());
        if (uri.getUserInfo() != null) {
            uri = new URI(uri.getScheme(), clean(uri.getScheme(), uri.getUserInfo()), uri.getHost(),
                    uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
        }
        return uri.toString();
    } catch (URISyntaxException e) {
        return url;
    }
}

From source file:com.marvelution.hudson.plugins.apiv2.client.connectors.HttpClient3Connector.java

/**
 * Get the {@link AuthScope} for the {@link #server}
 * /*w w w  .  j  av a 2 s  .  c om*/
 * @return the {@link AuthScope}
 */
private AuthScope getAuthScope() {
    String host = AuthScope.ANY_HOST;
    int port = AuthScope.ANY_PORT;
    try {
        final URI hostUri = new URI(server.getHost());
        host = hostUri.getHost();
        if (hostUri.getPort() > -1) {
            port = hostUri.getPort();
        } else if ("http".equalsIgnoreCase(hostUri.getScheme())) {
            port = 80;
        } else if ("https".equalsIgnoreCase(hostUri.getScheme())) {
            port = 443;
        }
    } catch (URISyntaxException e) {
        // Failed to parse the server host URI
        // Fall-back on preset defaults
        log.error("Failed to parse the host URI", e);
    }
    return new AuthScope(host, port, "realm");
}

From source file:com.marvelution.hudson.plugins.apiv2.client.connectors.HttpClient4Connector.java

/**
 * Get the {@link AuthScope} for the {@link #server}
 * //w w  w .ja va2  s  . c  om
 * @return the {@link AuthScope}
 */
private AuthScope getAuthScope() {
    String host = AuthScope.ANY_HOST;
    int port = AuthScope.ANY_PORT;
    try {
        final URI hostUri = new URI(server.getHost());
        host = hostUri.getHost();
        if (hostUri.getPort() > -1) {
            port = hostUri.getPort();
        } else if ("http".equalsIgnoreCase(hostUri.getScheme())) {
            port = 80;
        } else if ("https".equalsIgnoreCase(hostUri.getScheme())) {
            port = 443;
        }
    } catch (URISyntaxException e) {
        // Failed to parse the server host URI
        // Fall-back on preset defaults
        log.error("Failed to parse the Server host url to an URI", e);
    }
    return new AuthScope(host, port, "realm");
}