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.herrlado.engeo.Utils.java

/**
 * Update cookies from response.//ww w.  ja  v  a2s .  co m
 * 
 * @param cookies
 *            old {@link Cookie} list
 * @param headers
 *            {@link Header}s from {@link HttpResponse}
 * @param url
 *            requested URL
 * @throws URISyntaxException
 *             malformed URI
 * @throws MalformedCookieException
 *             malformed {@link Cookie}
 */
@Deprecated
public static void updateCookies(final ArrayList<Cookie> cookies, final Header[] headers, final String url)
        throws URISyntaxException, MalformedCookieException {
    final URI uri = new URI(url);
    int port = uri.getPort();
    if (port < 0) {
        if (url.startsWith("https")) {
            port = PORT_HTTPS;
        } else {
            port = PORT_HTTP;
        }
    }
    final CookieOrigin origin = new CookieOrigin(uri.getHost(), port, uri.getPath(), false);
    final CookieSpecBase cookieSpecBase = new BrowserCompatSpec();
    String name;
    String value;
    for (final Header header : headers) {
        for (final Cookie cookie : cookieSpecBase.parse(header, origin)) {
            // THE cookie
            name = cookie.getName();
            value = cookie.getValue();
            if (value == null || value.equals("")) {
                continue;
            }
            for (final Cookie c : cookies) {
                if (name.equals(c.getName())) {
                    cookies.remove(c);
                    cookies.add(cookie);
                    name = null;
                    break;
                }
            }
            if (name != null) {
                cookies.add(cookie);
            }
        }
    }
}

From source file:com.alehuo.wepas2016projekti.configuration.ProductionConfiguration.java

/**
 * Heroku -palvelussa kytetn PostgreSQL -tietokantaa tiedon
 * tallentamiseen. Tm metodi hakee herokusta tietokantayhteyden
 * mahdollistavat ympristmuuttujat./*from  w ww  .  java2  s  . co m*/
 *
 * @return @throws URISyntaxException
 */
@Bean
public BasicDataSource dataSource() throws URISyntaxException {
    URI dbUri = new URI(System.getenv("DATABASE_URL"));

    String username = dbUri.getUserInfo().split(":")[0];
    String password = dbUri.getUserInfo().split(":")[1];
    String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath();

    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setUrl(dbUrl);
    basicDataSource.setUsername(username);
    basicDataSource.setPassword(password);

    //Autocommit pois plt
    basicDataSource.setDefaultAutoCommit(false);

    return basicDataSource;
}

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:com.sun.jersey.client.apache.DefaultApacheHttpMethodExecutor.java

private HostConfiguration getHostConfiguration(HttpClient client, Map<String, Object> props) {
    Object proxy = props.get(ApacheHttpClientConfig.PROPERTY_PROXY_URI);
    if (proxy != null) {
        URI proxyUri = getProxyUri(proxy);

        String proxyHost = proxyUri.getHost();
        if (proxyHost == null) {
            proxyHost = "localhost";
        }/* w  w  w.j a v  a 2s  . c  om*/

        int proxyPort = proxyUri.getPort();
        if (proxyPort == -1) {
            proxyPort = 8080;
        }

        HostConfiguration hostConfig = new HostConfiguration(client.getHostConfiguration());
        String setHost = hostConfig.getProxyHost();
        int setPort = hostConfig.getProxyPort();

        if ((setHost == null) || (!setHost.equals(proxyHost)) || (setPort == -1) || (setPort != proxyPort)) {
            hostConfig.setProxyHost(new ProxyHost(proxyHost, proxyPort));
        }
        return hostConfig;
    } else {
        return null;
    }
}

From source file:de.vanita5.twittnuker.util.net.TwidereHttpClientImpl.java

@Override
public twitter4j.http.HttpResponse request(final twitter4j.http.HttpRequest req) throws TwitterException {
    final HostAddressResolver resolver = FactoryUtils.getHostAddressResolver(conf);
    final String urlString = req.getURL();
    final URI urlOrig = ParseUtils.parseURI(urlString);
    final String host = urlOrig.getHost(), authority = urlOrig.getAuthority();
    try {/*from   w  w  w .  ja  v  a  2 s .  com*/
        HttpRequestBaseHC4 commonsRequest;
        final String resolvedHost = resolver != null ? resolver.resolve(host) : null;
        final String resolvedUrl = !isEmpty(resolvedHost)
                ? urlString.replace("://" + host, "://" + resolvedHost)
                : urlString;
        final RequestMethod method = req.getMethod();
        if (method == RequestMethod.GET) {
            commonsRequest = new HttpGetHC4(resolvedUrl);
        } else if (method == RequestMethod.POST) {
            final HttpPostHC4 post = new HttpPostHC4(resolvedUrl);
            post.setEntity(getAsEntity(req.getParameters()));
            post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
            commonsRequest = post;
        } else if (method == RequestMethod.DELETE) {
            commonsRequest = new HttpDeleteHC4(resolvedUrl);
        } else if (method == RequestMethod.HEAD) {
            commonsRequest = new HttpHeadHC4(resolvedUrl);
        } else if (method == RequestMethod.PUT) {
            final HttpPutHC4 put = new HttpPutHC4(resolvedUrl);
            put.setEntity(getAsEntity(req.getParameters()));
            commonsRequest = put;
        } else
            throw new TwitterException("Unsupported request method " + method);
        final HttpParams httpParams = commonsRequest.getParams();
        HttpClientParams.setRedirecting(httpParams, false);
        final Map<String, String> headers = req.getRequestHeaders();
        for (final String headerName : headers.keySet()) {
            commonsRequest.addHeader(headerName, headers.get(headerName));
        }
        final Authorization authorization = req.getAuthorization();
        final String authorizationHeader = authorization != null ? authorization.getAuthorizationHeader(req)
                : null;
        if (authorizationHeader != null) {
            commonsRequest.addHeader(HttpHeaders.AUTHORIZATION, authorizationHeader);
        }
        if (resolvedHost != null && !resolvedHost.isEmpty() && !resolvedHost.equals(host)) {
            commonsRequest.addHeader(HttpHeaders.HOST, authority);
        }

        final ApacheHttpClientHttpResponseImpl res;
        try {
            final HttpContext httpContext = new BasicHttpContextHC4();
            httpContext.setAttribute(HostResolvedSSLConnectionSocketFactory.HTTP_CONTEXT_KEY_ORIGINAL_HOST,
                    host);
            res = new ApacheHttpClientHttpResponseImpl(client.execute(commonsRequest, httpContext), conf);
        } catch (final IllegalStateException e) {
            throw new TwitterException("Please check your API settings.", e);
        } catch (final NullPointerException e) {
            // Bug http://code.google.com/p/android/issues/detail?id=5255
            throw new TwitterException("Please check your APN settings, make sure not to use WAP APNs.", e);
        } catch (final OutOfMemoryError e) {
            // I don't know why OOM thown, but it should be catched.
            System.gc();
            throw new TwitterException("Unknown error", e);
        }
        final int statusCode = res.getStatusCode();
        if (statusCode < OK || statusCode > ACCEPTED)
            throw new TwitterException(res.asString(), req, res);
        return res;
    } catch (final IOException e) {
        // TODO
        if (resolver instanceof TwidereHostAddressResolver) {
            final TwidereHostAddressResolver twidereResolver = (TwidereHostAddressResolver) resolver;
            twidereResolver.removeCachedHost(host);
        }
        throw new TwitterException(e);
    }
}

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

@Test
public void testBasicPreemptiveAuth() throws Exception {
    final HttpClientBuilder client = HttpClientBuilder.create();
    final CountDownLatch count = new CountDownLatch(1);
    client.setDefaultCredentialsProvider(new BasicCredentialsProvider() {
        @Override/*from w w  w.  j av  a2  s.co  m*/
        public Credentials getCredentials(AuthScope authscope) {
            // Set flag that credentials have been used indicating preemptive authentication
            count.countDown();
            return new Credentials() {
                public Principal getUserPrincipal() {
                    return new BasicUserPrincipal("anonymous");
                }

                public String getPassword() {
                    return "invalid";
                }
            };
        }
    });
    SardineImpl sardine = new SardineImpl(client);
    URI url = URI.create("http://sudo.ch/dav/basic/");
    //Send basic authentication header in initial request
    sardine.enablePreemptiveAuthentication(url.getHost());
    try {
        sardine.list(url.toString());
        fail("Expected authorization failure");
    } catch (SardineException e) {
        // Expect Authorization Failed
        assertEquals(401, e.getStatusCode());
        // Make sure credentials have been queried
        assertEquals("No preemptive authentication attempt", 0, count.getCount());
    }
}

From source file:org.fcrepo.mint.HttpPidMinter.java

/**
 * Setup authentication in httpclient./*from  w ww  . j a va  2  s.  c  o m*/
 * @return the setup of authentication
**/
protected HttpClient buildClient() {
    HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties()
            .setConnectionManager(connManager);
    if (!isBlank(username) && !isBlank(password)) {
        final URI uri = URI.create(url);
        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
                new UsernamePasswordCredentials(username, password));
        builder = builder.setDefaultCredentialsProvider(credsProvider);
    }
    return builder.build();
}

From source file:org.coffeebreaks.validators.nu.NuValidator.java

ValidationResult validateUri(URL url, ValidationRequest request) throws IOException {
    String parser = request.getValue("parser", null);
    HttpRequestBase method;//from   w  w  w .  j a v a  2  s  . co m
    List<NameValuePair> qParams = new ArrayList<NameValuePair>();
    qParams.add(new BasicNameValuePair("out", "json"));
    if (parser != null) {
        qParams.add(new BasicNameValuePair("parser", parser));
    }
    qParams.add(new BasicNameValuePair("doc", url.toString()));

    try {
        URI uri = new URI(baseUrl);
        URI uri2 = URIUtils.createURI(uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath(),
                URLEncodedUtils.format(qParams, "UTF-8"), null);
        method = new HttpGet(uri2);
        return validate(method);
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("invalid uri. Check your baseUrl " + baseUrl, e);
    }
}

From source file:li.klass.fhem.fhem.FHEMWEBConnection.java

private RequestResult<InputStream> executeRequest(String urlSuffix, DefaultHttpClient client, String command) {
    String url = null;/*  ww w.  j av  a2 s .com*/
    if (client == null) {
        client = createNewHTTPClient(getConnectionTimeoutMilliSeconds(), SOCKET_TIMEOUT);
    }
    try {
        HttpGet request = new HttpGet();
        request.addHeader("Accept-Encoding", "gzip");

        url = serverSpec.getUrl() + urlSuffix;

        Log.i(TAG, "accessing URL " + url);
        URI uri = new URI(url);

        client.getCredentialsProvider().setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
                new UsernamePasswordCredentials(serverSpec.getUsername(), getPassword()));

        request.setURI(uri);

        HttpResponse response = client.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        Log.d(TAG, "response status code is " + statusCode);

        RequestResult<InputStream> errorResult = handleHttpStatusCode(statusCode);
        if (errorResult != null) {
            String msg = "found error " + errorResult.error.getClass().getSimpleName() + " for "
                    + "status code " + statusCode;
            Log.d(TAG, msg);
            ErrorHolder.setError(null, msg);
            return errorResult;
        }

        InputStream contentStream = response.getEntity().getContent();
        Header contentEncoding = response.getFirstHeader("Content-Encoding");
        if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
            contentStream = new GZIPInputStream(contentStream);
        }
        return new RequestResult<InputStream>(contentStream);
    } catch (ConnectTimeoutException e) {
        Log.i(TAG, "connection timed out", e);
        setErrorInErrorHolderFor(e, url, command);
        return new RequestResult<InputStream>(RequestResultError.CONNECTION_TIMEOUT);
    } catch (ClientProtocolException e) {
        String errorText = "cannot connect, invalid URL? (" + url + ")";
        setErrorInErrorHolderFor(e, url, command);
        ErrorHolder.setError(e, errorText);
        return new RequestResult<InputStream>(RequestResultError.HOST_CONNECTION_ERROR);
    } catch (IOException e) {
        Log.i(TAG, "cannot connect to host", e);
        setErrorInErrorHolderFor(e, url, command);
        return new RequestResult<InputStream>(RequestResultError.HOST_CONNECTION_ERROR);
    } catch (URISyntaxException e) {
        Log.i(TAG, "invalid URL syntax", e);
        setErrorInErrorHolderFor(e, url, command);
        throw new IllegalStateException("cannot parse URL " + urlSuffix, e);
    }
}

From source file:fusion.Fusion.java

public static String getHostFromUri(final String uri) throws URISyntaxException {
    // par exemple http://localhost/rdf/val1234 -> localhost
    URI u = new URI(uri);
    return u.getHost();
}