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:org.geosdi.geoplatform.connector.server.security.PreemptiveSecurityConnector.java

/**
 * If the URI don't have e port, retrieve the standard port wrt scheme
 * ["http" or "https"].//from  w  ww . j  a va  2  s.  co  m
 */
private int retrieveNoSetPort(URI uri) {
    int port = uri.getPort();
    if (port > 0) {
        return port;
    }

    String scheme = uri.getScheme();
    if ("https".equals(scheme)) {
        port = 443;
    } else if ("http".equals(scheme)) {
        port = 80; // TODO Test Catalog with credentials on port 80 (insert the URL without specifying the port)
    } else {
        throw new IllegalArgumentException("Scheme don't recognize");
    }

    return port;
}

From source file:io.servicecomb.foundation.common.net.URIEndpointObject.java

public URIEndpointObject(String endpoint) {
    URI uri = URI.create(endpoint);
    setHostOrIp(uri.getHost());//from w  ww . ja  va  2s .  c om
    if (uri.getPort() < 0) {
        // do not use default port
        throw new IllegalArgumentException("port not specified.");
    }
    setPort(uri.getPort());
    querys = splitQuery(uri);
    sslEnabled = Boolean.parseBoolean(getFirst(SSL_ENABLED_KEY));
}

From source file:com.mycompany.projecta.JenkinsScraper.java

public String scrape(String urlString, String username, String password)
        throws ClientProtocolException, IOException {
    URI uri = URI.create(urlString);
    HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
            new UsernamePasswordCredentials(username, password));
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);/* ww  w.ja v  a 2  s. com*/
    CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    HttpGet httpGet = new HttpGet(uri);
    // Add AuthCache to the execution context
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    HttpResponse response = httpClient.execute(host, httpGet, localContext);

    String resp = response.toString();

    return EntityUtils.toString(response.getEntity());
}

From source file:org.sigmond.net.AsyncHttpTask.java

protected HttpRequestInfo doInBackground(HttpRequestInfo... params) {
    HttpRequestInfo rinfo = params[0];//from  w  w  w  . j a  v a2  s. co m
    try {
        client.setCookieStore(rinfo.getCookieStore()); //cookie handling
        HttpResponse resp = client.execute(rinfo.getRequest()); //execute request

        //store any new cookies recieved
        CookieStore store = rinfo.getCookieStore();
        Header[] allHeaders = resp.getAllHeaders();
        CookieSpecBase base = new BrowserCompatSpec();
        URI uri = rinfo.getRequest().getURI();
        int port = uri.getPort();
        if (port <= 0)
            port = 80;
        CookieOrigin origin = new CookieOrigin(uri.getHost(), port, uri.getPath(), false);
        for (Header header : allHeaders) {
            List<Cookie> parse = base.parse(header, origin);
            for (Cookie cookie : parse) {
                if (cookie.getValue() != null && cookie.getValue() != "")
                    store.addCookie(cookie);
            }
        }
        rinfo.setCookieStore(store);
        //store the response
        rinfo.setResponse(resp);
        //process the response string. This is required in newer Android versions.
        //newer versions will not allow reading from a network response input stream in the main thread.
        rinfo.setResponseString(HttpUtils.responseToString(resp));
    } catch (Exception e) {
        rinfo.setException(e);
    }
    return rinfo;
}

From source file:org.apache.hadoop.gateway.hbase.HBaseCookieManager.java

protected HttpRequest createKerberosAuthenticationRequest(HttpUriRequest userRequest) {
    URI userUri = userRequest.getURI();
    try {//from   w ww . j  av  a2 s  .co  m
        URI authUri = new URI(userUri.getScheme(), null, userUri.getHost(), userUri.getPort(), "/version",
                userUri.getQuery(), null);
        HttpRequest authRequest = new HttpGet(authUri);
        return authRequest;
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(userUri.toString(), e);
    }
}

From source file:org.apache.hive.jdbc.Utils.java

/**
 * Read the next server coordinates (host:port combo) from ZooKeeper. Ignore the znodes already
 * explored. Also update the host, port, jdbcUriString fields of connParams.
 *
 * @param connParams//from w w  w .  j  a  v  a 2 s . c  o  m
 * @throws ZooKeeperHiveClientException
 */
static void updateConnParamsFromZooKeeper(JdbcConnectionParams connParams) throws ZooKeeperHiveClientException {
    // Add current host to the rejected list
    connParams.getRejectedHostZnodePaths().add(connParams.getCurrentHostZnodePath());
    // Get another HiveServer2 uri from ZooKeeper
    String serverUriString = ZooKeeperHiveClientHelper.getNextServerUriFromZooKeeper(connParams);
    // Parse serverUri to a java URI and extract host, port
    URI serverUri = null;
    try {
        // Note URL_PREFIX is not a valid scheme format, therefore leaving it null in the constructor
        // to construct a valid URI
        serverUri = new URI(null, serverUriString, null, null, null);
    } catch (URISyntaxException e) {
        throw new ZooKeeperHiveClientException(e);
    }
    String oldServerHost = connParams.getHost();
    int oldServerPort = connParams.getPort();
    String newServerHost = serverUri.getHost();
    int newServerPort = serverUri.getPort();
    connParams.setHost(newServerHost);
    connParams.setPort(newServerPort);
    connParams.setJdbcUriString(connParams.getJdbcUriString().replace(oldServerHost + ":" + oldServerPort,
            newServerHost + ":" + newServerPort));
}

From source file:org.piraso.client.net.HttpBasicAuthenticationTest.java

@Test
public void testAuthenticate() throws Exception {
    AbstractHttpClient client = mock(AbstractHttpClient.class);
    HttpContext context = mock(HttpContext.class);
    CredentialsProvider credentials = mock(CredentialsProvider.class);

    doReturn(credentials).when(client).getCredentialsProvider();

    HttpBasicAuthentication auth = new HttpBasicAuthentication(client, context);
    auth.setUserName("username");
    auth.setPassword("password");

    URI uri = URI.create("http://localhost:8080/test");

    auth.setTargetHost(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()));

    auth.execute();//from ww w.j  a  v  a 2  s . c om

    verify(credentials).setCredentials(Matchers.<AuthScope>any(), Matchers.<Credentials>any());
    verify(context).setAttribute(Matchers.<String>any(), any());
}

From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java

/**
 * For Basic auth, configure the context to do pre-emptive auth with the
 * credentials given./*from  ww  w  . jav a  2s.c o m*/
 * @param httpContext The context in use for the requests.
 * @param serverURI The RTC server we will be authenticating against
 * @param userId The userId to login with
 * @param password The password for the User
 * @param listener A listen to log messages to, Not required
 * @throws IOException Thrown if anything goes wrong
 */
private static void handleBasicAuthChallenge(HttpClientContext httpContext, String serverURI, String userId,
        String password, TaskListener listener) throws IOException {

    URI uri;
    try {
        uri = new URI(serverURI);
    } catch (URISyntaxException e) {
        throw new IOException(Messages.HttpUtils_invalid_server(serverURI), e);
    }
    HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(userId, password));
    httpContext.setAttribute(HttpClientContext.CREDS_PROVIDER, credsProvider);

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(target, basicAuth);

    // Add AuthCache to the execution context
    httpContext.setAuthCache(authCache);
}

From source file:com.jaeksoft.searchlib.web.AbstractServlet.java

protected static URI buildUri(URI uri, String additionalPath, String indexName, String login, String apiKey,
        String additionnalQuery) throws URISyntaxException {
    StringBuilder path = new StringBuilder(uri.getPath());
    if (additionalPath != null)
        path.append(additionalPath);/*from  ww  w.  ja v  a 2  s  .c o m*/
    StringBuilder query = new StringBuilder();
    if (indexName != null) {
        query.append("index=");
        query.append(indexName);
    }
    if (login != null) {
        query.append("&login=");
        query.append(login);
    }
    if (apiKey != null) {
        query.append("&key=");
        query.append(apiKey);
    }
    if (additionnalQuery != null) {
        if (query.length() > 0)
            query.append("&");
        query.append(additionnalQuery);
    }
    return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), path.toString(),
            query.toString(), uri.getFragment());

}

From source file:org.geosdi.geoplatform.connector.server.security.AbstractSecurityConnector.java

/**
 * Bind Credentials for {@link CredentialsProvider} class
 *
 * @param credentialsProvider/*from   w w w  .  j a va2  s  .  com*/
 */
protected void bindCredentials(CredentialsProvider credentialsProvider, URI targetURI) {
    if (this.authScope == null) {
        this.authScope = new AuthScope(targetURI.getHost(), targetURI.getPort());
    }

    credentialsProvider.setCredentials(authScope, new UsernamePasswordCredentials(username, password));
}