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.apache.droids.protocol.http.HttpProtocol.java

@Override
public boolean isAllowed(URI uri) throws IOException {
    if (forceAllow) {
        return forceAllow;
    }/*from w  ww  .  j av a2s. c  o m*/

    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;
}

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  ww  . j a  v  a 2s  .  c om*/
 * @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: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  .jav a  2s. c  o m
    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:org.fcrepo.mint.HttpPidMinter.java

/**
 * Setup authentication in httpclient.// w  ww . j  ava 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:ddf.registry.server.rest.internal.RestRegistryServer.java

/**
 * Combines the URI and relative URL to form a full URL for external clients to use.
 *
 * @param registryUri URI from the calling context
 * @param relativeUrl URL Relative URL for a service
 * @return Absolute URL for the service//from   ww w .ja v a2  s .co  m
 */
private String combineUrl(URI registryUri, String relativeUrl) {
    StringBuilder serviceUrl = new StringBuilder();
    serviceUrl.append(registryUri.getScheme());
    serviceUrl.append("://");
    serviceUrl.append(registryUri.getHost());
    serviceUrl.append(":");
    serviceUrl.append(registryUri.getPort());
    serviceUrl.append(relativeUrl);
    return serviceUrl.toString();
}

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

/**
 * Heroku -palvelussa kytetn PostgreSQL -tietokantaa tiedon
 * tallentamiseen. Tm metodi hakee herokusta tietokantayhteyden
 * mahdollistavat ympristmuuttujat.//  w  ww .ja va  2s. c o  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:oauth.signpost.signature.SignatureBaseString.java

public String normalizeUrl(String url) throws URISyntaxException {
    URI uri = new URI(url);
    String scheme = uri.getScheme().toLowerCase();
    String authority = uri.getAuthority().toLowerCase();
    boolean dropPort = (scheme.equals("http") && uri.getPort() == 80)
            || (scheme.equals("https") && uri.getPort() == 443);
    if (dropPort) {
        // find the last : in the authority
        int index = authority.lastIndexOf(":");
        if (index >= 0) {
            authority = authority.substring(0, index);
        }/*  w w  w  .  j  a  v  a 2 s  .c  o m*/
    }
    String path = uri.getRawPath();
    if (path == null || path.length() <= 0) {
        path = "/"; // conforms to RFC 2616 section 3.2.2
    }
    // we know that there is no query and no fragment here.
    return scheme + "://" + authority + path;
}

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;// www.j a v a  2 s  .com
    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;//from  www.ja v  a  2 s . c  o  m
    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:com.jgoetsch.eventtrader.source.SocketIOWebSocketMsgSource.java

protected String getTokenUrl() throws IOException, URISyntaxException {
    URI base = new URI(getUrl());
    BufferedReader tokenReader = new BufferedReader(
            new InputStreamReader(new URI("http", base.getUserInfo(), base.getHost(), base.getPort(),
                    base.getPath(), base.getQuery(), base.getFragment()).toURL().openStream()));
    String token = tokenReader.readLine();
    tokenReader.close();/*from   ww  w .java2  s .c o  m*/

    String r[] = token.split(":");
    String comp[] = getUrl().split("\\?");
    if (!comp[0].endsWith("/"))
        comp[0] += '/';
    return comp[0] + "websocket/" + r[0] + (comp.length > 0 ? "?" + comp[1] : "");
}