Example usage for java.net URI getHost

List of usage examples for java.net URI getHost

Introduction

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

Prototype

public String getHost() 

Source Link

Document

Returns the host component of this URI.

Usage

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

protected HttpRequestInfo doInBackground(HttpRequestInfo... params) {
    HttpRequestInfo rinfo = params[0];// w w w .j  a  v a 2s . c o  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.reef.runtime.hdinsight.client.yarnrest.HDInsightInstance.java

private String getHost() throws URISyntaxException {
    final URI uri = new URI(this.instanceUrl);
    return uri.getHost();
}

From source file:com.github.sardine.AuthenticationTest.java

@Test
public void testDigestAuthWithBasicPreemptiveAuthenticationEnabled() throws Exception {
    Sardine sardine = SardineFactory.begin(properties.getProperty("username"),
            properties.getProperty("password"));
    try {// w ww .j  av  a 2 s .c  o  m
        URI url = URI.create("http://sudo.ch/dav/digest/");
        sardine.enablePreemptiveAuthentication(url.getHost());
        sardine.list(url.toString());
        fail("Expected authentication to fail becuase of preemptive credential cache");
    } catch (SardineException e) {
        // If preemptive basic authentication is enabled, we cannot login
        // with digest authentication. This is currently expected.
        assertEquals(401, e.getStatusCode());
    }
}

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 va 2 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.cloudcrawler.domain.crawler.robotstxt.RobotsTxtService.java

/**
 * This method is used to evaluate if the provided uri is
 * allowed to be crawled against the robots.txt of the website.
 *
 * @param uri/*from  w w w  . j  a v  a2  s  . c om*/
 * @return
 * @throws Exception
 */
public boolean isAllowedUri(URI uri) throws Exception {
    URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.setScheme(uri.getScheme());
    uriBuilder.setHost(uri.getHost());
    uriBuilder.setUserInfo(uri.getUserInfo());
    uriBuilder.setPath("/robots.txt");

    URI robotsTxtUri = uriBuilder.build();
    BaseRobotRules rules = (BaseRobotRules) cache.get(robotsTxtUri.toString());

    if (rules == null) {
        HttpResponse response = httpService.get(robotsTxtUri);

        try {

            // HACK! DANGER! Some sites will redirect the request to the top-level domain
            // page, without returning a 404. So look for a response which has a redirect,
            // and the fetched content is not plain text, and assume it's one of these...
            // which is the same as not having a robotstxt.txt file.

            String contentType = response.getEntity().getContentType().getValue();
            boolean isPlainText = (contentType != null) && (contentType.startsWith("text/plain"));

            if (response.getStatusLine().getStatusCode() == 404 || !isPlainText) {
                rules = robotsTxtParser.failedFetch(HttpStatus.SC_GONE);
            } else {
                StringWriter writer = new StringWriter();

                IOUtils.copy(response.getEntity().getContent(), writer);

                rules = robotsTxtParser.parseContent(uri.toString(), writer.toString().getBytes(),
                        response.getEntity().getContentType().getValue(), httpService.getUserAgent());

            }
        } catch (Exception e) {
            EntityUtils.consume(response.getEntity());
            throw e;
        }

        EntityUtils.consume(response.getEntity());
        cache.set(robotsTxtUri.toString(), 60 * 60 * 24, rules);
    }

    return rules.isAllowed(uri.toString());
}

From source file:org.mobicents.servlet.sip.restcomm.interpreter.http.HttpRequestDescriptor.java

public HttpRequestDescriptor(final URI uri, final String method, final List<NameValuePair> parameters)
        throws UnsupportedEncodingException, URISyntaxException {
    super();/*w  w w . j av a2s. co m*/
    this.uri = URIUtils.createURI(uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath(), null, null);
    this.method = method;
    final String query = uri.getQuery();
    if (query != null) {
        parameters.addAll(URLEncodedUtils.parse(uri, "UTF-8"));
    }
    this.parameters = parameters;
}

From source file:com.nebhale.cyclinglibrary.repository.RepositoryConfiguration.java

@Bean
DataSource dataSource() throws URISyntaxException {
    String dbUrlProperty = System.getenv(DB_URL_PROPERTY_NAME);
    Assert.hasText(dbUrlProperty,/*from  w  w w.ja v a 2s  . c o  m*/
            String.format("The enviroment variable '%s' must be specified", DB_URL_PROPERTY_NAME));

    URI dbUri = new URI(dbUrlProperty);

    String username = dbUri.getUserInfo().split(":")[0];
    String password = dbUri.getUserInfo().split(":")[1];
    String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath()
            + "?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory";

    BoneCPDataSource dataSource = new BoneCPDataSource();
    dataSource.setDriverClass(Driver.class.getCanonicalName());
    dataSource.setJdbcUrl(dbUrl);
    dataSource.setUsername(username);
    dataSource.setPassword(password);

    Flyway flyway = new Flyway();
    flyway.setDataSource(dataSource);
    flyway.migrate();

    return dataSource;
}

From source file:com.sap.core.odata.testutil.tool.core.AbstractTestClient.java

private DefaultHttpClient createHttpClient(final CallerConfig config) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    if (config.isProxySet()) {
        initProxy(httpClient, config);//  w  ww. ja v a  2s.  c o m
    }

    if (config.isBasicAuthCredentialsSet()) {
        final URI baseUri = config.getBaseUri();
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(baseUri.getHost(), baseUri.getPort()),
                new UsernamePasswordCredentials(config.getBasicAuthCredentials()));
    }
    return httpClient;
}

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

/**
 * Returns hadoop.auth cookie, doing needed SPNego authentication
 * /*from ww w.  j  a v a 2s . 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:com.anrisoftware.simplerest.owncloud.DefaultOwncloudAccountURIFromEnv.java

private URI fromCredentials() {
    try {/* w ww  .  ja  v  a2  s . c o  m*/
        URI base = new URI(owncloudBaseUri);
        String string = format("%s://%s:%s@%s/%s", base.getScheme(), owncloudAccountUser,
                owncloudAccountPassword, base.getHost(), base.getPath());
        try {
            return new URI(string);
        } catch (URISyntaxException e) {
            throw new BuildAccountURIException(e, string);
        }
    } catch (URISyntaxException e) {
        throw new BuildAccountURIException(e, owncloudBaseUri);
    }
}