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.soyatec.windowsazure.authenticate.SharedKeyCredentialsWrapper.java

/**
 * Append the signedString to the uri.// ww  w  .j  av  a2  s.  co m
 * 
 * @param uri
 * @param signedString
 * @return The uri after be appended with signedString.
 */
private URI appendSignString(URI uri, String signedString) {
    try {
        return URIUtils.createURI(uri.getScheme(), uri.getHost(), uri.getPort(),
                HttpUtilities.getNormalizePath(uri),
                (uri.getQuery() == null ? Utilities.emptyString() : uri.getQuery()) + "&" + signedString,
                uri.getFragment());
    } catch (URISyntaxException e) {
        Logger.error("", e);
    }
    return uri;
}

From source file:com.seajas.search.profiler.wsdl.FeedTesting.java

/**
 * {@inheritDoc}//from   ww w. ja  v  a 2 s .  c  om
 */
@Override
public FeedResult isValidFeedUrl(final String url, final Boolean ignoreExisting) {
    FeedResult result = new FeedResult();

    if (!Boolean.TRUE.equals(ignoreExisting)) {
        List<Feed> existingFeeds = profilerService.getFeedsByUrl(url);

        if (existingFeeds != null && existingFeeds.size() > 0) {
            if (logger.isInfoEnabled())
                logger.info("The given feed URL already exists");

            result.setStatus(Status.ALREADY_EXISTS);

            return result;
        }
    }

    // Validate the URL first

    URI validatedUri;

    try {
        validatedUri = new URI(url);

        if (!StringUtils.hasText(validatedUri.getScheme()) || !StringUtils.hasText(validatedUri.getHost()))
            throw new URISyntaxException("", "No scheme and/or host provided");
    } catch (URISyntaxException e) {
        if (logger.isInfoEnabled())
            logger.info("The given feed URL is not valid", e);

        result.setStatus(Status.UNKNOWN);

        return result;
    }

    // Then run it through the testing service for exploration

    try {
        Map<String, Boolean> testingResult = testingService.exploreUri(validatedUri);

        if (logger.isInfoEnabled())
            logger.info("Exploration resulted in " + testingResult.size() + " result URL(s)");

        List<String> validUrls = new ArrayList<String>();

        for (Entry<String, Boolean> testingResultEntry : testingResult.entrySet()) {
            validUrls.add(testingResultEntry.getKey());

            if (testingResultEntry.getValue()) {
                if (logger.isInfoEnabled())
                    logger.info("The given URL '" + url + "' is a direct RSS feed");

                result.setStatus(Status.VALID);

                break;
            } else
                result.setStatus(Status.INDIRECTLY_VALID);
        }

        result.setValidUrls(validUrls);
    } catch (TestingException e) {
        if (logger.isInfoEnabled())
            logger.info("URL exploration was unsuccessful", e);

        result.setStatus(Status.UNKNOWN);
    }

    return result;
}

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

@Test
public void testBasicPreemptiveAuth() throws Exception {
    final DefaultHttpClient client = new DefaultHttpClient();
    final CountDownLatch count = new CountDownLatch(1);
    client.setCredentialsProvider(new BasicCredentialsProvider() {
        @Override//from   www  . j  a  v a 2 s .  c o 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.sonatype.nexus.client.rest.jersey.NexusClientFactoryImpl.java

/**
 * NXCM-4547 JERSEY-1293 Enforce proxy setting on httpclient
 * <p/>/*from w  w w .ja  v a2 s .c  o  m*/
 * Revisit for jersey 1.13.
 */
private void enforceProxyUri(final ApacheHttpClient4Config config, final ApacheHttpClient4 client) {
    final Object proxyProperty = config.getProperties().get(PROPERTY_PROXY_URI);
    if (proxyProperty != null) {
        final URI uri = getProxyUri(proxyProperty);
        final HttpHost proxy = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
        client.getClientHandler().getHttpClient().getParams().setParameter(DEFAULT_PROXY, proxy);
    }
}

From source file:org.dspace.identifier.ezid.EZIDRequest.java

/**
 * Prepare a context for requests concerning a specific identifier or
 * authority prefix./*www .  j a v a2s  . c  o  m*/
 *
 * @param scheme URL scheme for access to the EZID service.
 * @param host Host name for access to the EZID service.
 * @param authority DOI authority prefix, e.g. "10.5072/FK2".
 * @param username an EZID user identity.
 * @param password user's password, or {@code null} for none.
 * @throws URISyntaxException if host or authority is bad.
 */
EZIDRequest(String scheme, String host, String authority, String username, String password)
        throws URISyntaxException {
    this.scheme = scheme;

    this.host = host;

    if (authority.charAt(authority.length() - 1) == '/') {
        this.authority = authority.substring(0, authority.length() - 1);
    } else {
        this.authority = authority;
    }

    client = new DefaultHttpClient();
    if (null != username) {
        URI uri = new URI(scheme, host, null, null);
        client.getCredentialsProvider().setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
                new UsernamePasswordCredentials(username, password));
    }
}

From source file:com.smartitengineering.util.rest.client.jersey.cache.CustomApacheHttpClientResponseResolver.java

/**
 * Determines the HttpClient's request method from the HTTPMethod enum.
 *
 * @param method     the HTTPCache enum that determines
 * @param requestURI the request URI.//from   w  w w.  j  av a2  s.  com
 * @return a new HttpMethod subclass.
 */
protected HttpMethod getMethod(HTTPMethod method, URI requestURI) {
    if (CONNECT.equals(method)) {
        HostConfiguration config = new HostConfiguration();
        config.setHost(requestURI.getHost(), requestURI.getPort(), requestURI.getScheme());
        return new ConnectMethod(config);
    } else if (DELETE.equals(method)) {
        return new CustomHttpMethod(HTTPMethod.DELETE.name(), requestURI.toString());
    } else if (GET.equals(method)) {
        return new GetMethod(requestURI.toString());
    } else if (HEAD.equals(method)) {
        return new HeadMethod(requestURI.toString());
    } else if (OPTIONS.equals(method)) {
        return new OptionsMethod(requestURI.toString());
    } else if (POST.equals(method)) {
        return new PostMethod(requestURI.toString());
    } else if (PUT.equals(method)) {
        return new PutMethod(requestURI.toString());
    } else if (TRACE.equals(method)) {
        return new TraceMethod(requestURI.toString());
    } else {
        return new CustomHttpMethod(method.name(), requestURI.toString());
    }
}

From source file:org.mcxiaoke.commons.http.util.URIUtilsEx.java

/**
 * Extracts target host from the given {@link URI}.
 * //from w  w w .  ja  v  a  2s  .c  o m
 * @param uri
 * @return the target host if the URI is absolute or
 *         <code>null</null> if the URI is
 * relative or does not contain a valid host name.
 * 
 * @since 4.1
 */
public static HttpHost extractHost(final URI uri) {
    if (uri == null) {
        return null;
    }
    HttpHost target = null;
    if (uri.isAbsolute()) {
        int port = uri.getPort(); // may be overridden later
        String host = uri.getHost();
        if (host == null) { // normal parse failed; let's do it ourselves
            // authority does not seem to care about the valid character-set
            // for host names
            host = uri.getAuthority();
            if (host != null) {
                // Strip off any leading user credentials
                int at = host.indexOf('@');
                if (at >= 0) {
                    if (host.length() > at + 1) {
                        host = host.substring(at + 1);
                    } else {
                        host = null; // @ on its own
                    }
                }
                // Extract the port suffix, if present
                if (host != null) {
                    int colon = host.indexOf(':');
                    if (colon >= 0) {
                        int pos = colon + 1;
                        int len = 0;
                        for (int i = pos; i < host.length(); i++) {
                            if (Character.isDigit(host.charAt(i))) {
                                len++;
                            } else {
                                break;
                            }
                        }
                        if (len > 0) {
                            try {
                                port = Integer.parseInt(host.substring(pos, pos + len));
                            } catch (NumberFormatException ex) {
                            }
                        }
                        host = host.substring(0, colon);
                    }
                }
            }
        }
        String scheme = uri.getScheme();
        if (host != null) {
            target = new HttpHost(host, port, scheme);
        }
    }
    return target;
}

From source file:io.seldon.external.ExternalItemRecommendationAlgorithm.java

@Override
public ItemRecommendationResultSet recommend(String client, Long user, Set<Integer> dimensions,
        int maxRecsCount, RecommendationContext ctxt, List<Long> recentItemInteractions) {
    long timeNow = System.currentTimeMillis();
    String recommenderName = ctxt.getOptsHolder().getStringOption(ALG_NAME_PROPERTY_NAME);
    String baseUrl = ctxt.getOptsHolder().getStringOption(URL_PROPERTY_NAME);
    if (ctxt.getInclusionKeys().isEmpty()) {
        logger.warn("Cannot get external recommendations are no includers were used. Returning 0 results");
        return new ItemRecommendationResultSet(recommenderName);
    }//from  w  w  w.  j a v a 2 s. c om
    URI uri = URI.create(baseUrl);
    try {
        URIBuilder builder = new URIBuilder().setScheme("http").setHost(uri.getHost()).setPort(uri.getPort())
                .setPath(uri.getPath()).setParameter("client", client).setParameter("user_id", user.toString())
                .setParameter("recent_interactions", StringUtils.join(recentItemInteractions, ","))
                .setParameter("dimensions", StringUtils.join(dimensions, ","))
                .setParameter("exclusion_items", StringUtils.join(ctxt.getExclusionItems(), ","))
                .setParameter("data_key", StringUtils.join(ctxt.getInclusionKeys(), ","))
                .setParameter("limit", String.valueOf(maxRecsCount));
        if (ctxt.getCurrentItem() != null)
            builder.setParameter("item_id", ctxt.getCurrentItem().toString());
        uri = builder.build();
    } catch (URISyntaxException e) {
        logger.error("Couldn't create URI for external recommender with name " + recommenderName, e);
        return new ItemRecommendationResultSet(recommenderName);
    }
    HttpContext context = HttpClientContext.create();
    HttpGet httpGet = new HttpGet(uri);
    try {
        if (logger.isDebugEnabled())
            logger.debug("Requesting " + httpGet.getURI().toString());
        CloseableHttpResponse resp = httpClient.execute(httpGet, context);
        try {
            if (resp.getStatusLine().getStatusCode() == 200) {
                ConsumerBean c = new ConsumerBean(client);
                ObjectReader reader = mapper.reader(AlgsResult.class);
                AlgsResult recs = reader.readValue(resp.getEntity().getContent());
                List<ItemRecommendationResultSet.ItemRecommendationResult> results = new ArrayList<>(
                        recs.recommended.size());
                for (AlgResult rec : recs.recommended) {
                    Map<String, Integer> attrDimsCandidate = itemService.getDimensionIdsForItem(c, rec.item);
                    if (CollectionUtils.containsAny(dimensions, attrDimsCandidate.values())
                            || dimensions.contains(Constants.DEFAULT_DIMENSION)) {
                        if (logger.isDebugEnabled())
                            logger.debug("Adding item " + rec.item);
                        results.add(
                                new ItemRecommendationResultSet.ItemRecommendationResult(rec.item, rec.score));
                    } else {
                        if (logger.isDebugEnabled())
                            logger.debug("Rejecting item " + rec.item + " as not in dimensions " + dimensions);
                    }
                }
                if (logger.isDebugEnabled())
                    logger.debug("External recommender took " + (System.currentTimeMillis() - timeNow) + "ms");
                return new ItemRecommendationResultSet(results, recommenderName);
            } else {
                logger.error(
                        "Couldn't retrieve recommendations from external recommender -- bad http return code: "
                                + resp.getStatusLine().getStatusCode());
            }
        } finally {
            if (resp != null)
                resp.close();
        }
    } catch (IOException e) {
        logger.error("Couldn't retrieve recommendations from external recommender - ", e);
    } catch (Exception e) {
        logger.error("Couldn't retrieve recommendations from external recommender - ", e);
    }
    return new ItemRecommendationResultSet(recommenderName);
}

From source file:com.snowplowanalytics.refererparser.Parser.java

public Referer parse(String refererUri, URI pageUri) throws URISyntaxException {
    return parse(refererUri, pageUri.getHost());
}

From source file:org.apache.droids.protocol.http.HttpProtocol.java

@Override
public boolean isAllowed(URI uri) throws IOException {
    if (forceAllow) {
        return forceAllow;
    }//w w w. j a va 2  s. c  om

    URI baseURI;
    try {
        baseURI = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), "/", null, null);
    } catch (URISyntaxException ex) {
        LOG.error("Unable to determine base URI for " + uri);
        return false;
    }

    NoRobotClient nrc = new NoRobotClient(contentLoader, userAgent);
    try {
        nrc.parse(baseURI);
    } catch (NoRobotException ex) {
        LOG.error("Failure parsing robots.txt: " + ex.getMessage());
        return false;
    }
    boolean test = nrc.isUrlAllowed(uri);
    if (LOG.isInfoEnabled()) {
        LOG.info(uri + " is " + (test ? "allowed" : "denied"));
    }
    return test;
}