Example usage for org.apache.http.client.utils URIBuilder setHost

List of usage examples for org.apache.http.client.utils URIBuilder setHost

Introduction

In this page you can find the example usage for org.apache.http.client.utils URIBuilder setHost.

Prototype

public URIBuilder setHost(final String host) 

Source Link

Document

Sets URI host.

Usage

From source file:pt.meocloud.sdk.MeoCloudImpl.java

@Override
public MeoCloudResponse<File> downloadFile(String path, String revision) {
    try {//from   www  . ja  v  a2  s .  c om
        String builderPath = String.format("/%s/%s/%s%s", MEOCLOUD_API_VERSION, MEOCLOUD_API_METHOD_FILES,
                apiMode.getCode(), path);
        URIBuilder builder = new URIBuilder();
        builder.setScheme(MEOCLOUD_SCHEME);
        builder.setHost(MEOCLOUD_API_CONTENT_ENDPOINT);
        builder.setPath(builderPath);
        List<NameValuePair> parameters = new LinkedList<>();
        if (revision != null) {
            builder.addParameter(REV_PARAM, revision);
            parameters.add(new BasicNameValuePair(REV_PARAM, revision));
        }
        String apiCall = builder.build().toString();
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet getRequest = new HttpGet(apiCall);
        signHttpRequest(getRequest, "GET", apiCall, parameters);
        HttpResponse httpResponse = client.execute(getRequest);
        Integer statusCode = httpResponse.getStatusLine().getStatusCode();
        MeoCloudResponse<File> meoCloudResponse = new MeoCloudResponse<>();
        meoCloudResponse.setCode(statusCode);
        if (statusCode == HttpStatus.SC_OK) {
            InputStream is = httpResponse.getEntity().getContent();
            File tempFile = new File(UUID.randomUUID().toString());
            FileOutputStream fos = new FileOutputStream(tempFile);
            byte[] buffer = new byte[1024 * 100];
            int nBytes = -1;
            while ((nBytes = is.read(buffer)) != -1) {
                fos.write(buffer, 0, nBytes);
                fos.flush();
            }
            is.close();
            fos.close();
            meoCloudResponse.setResponse(tempFile);
        } else
            process(meoCloudResponse, statusCode);
        return meoCloudResponse;
    } catch (Exception e) {
        log.error("Exception caught downloading file.", e);
    }
    return null;
}

From source file:com.buffalokiwi.api.API.java

/**
 * Convert a string representing a URI into a URI object.
 * This combines url with the host, port and scheme from the defined host
 * in the constructor.//from w ww  .  j  a va 2  s .  c  o m
 * @param uri The URI (path/fragment/querystring)
 * @return The URI object representing the full address
 * @throws APIException If there is a problem building the URI
 */
private URI stringToURI(final String url) throws APIException {
    try {
        final URIBuilder b = new URIBuilder(url.replace(" ", "%20"));

        //..Overwrite the host if necessary 
        if (lockHost && client.getHost().getHost() != null && !client.getHost().getHost().isEmpty()
        //..Kind of stupid, but I didn't think ahead on this one.
                && !url.startsWith("http://") && !url.startsWith("https://")) {
            b.setHost(client.getHost().getHost()).setPort(client.getHost().getPort())
                    .setScheme(client.getHost().getScheme());

            if (client.getHost().getPath() != null && !client.getHost().getPath().isEmpty()) {
                b.setPath(client.getHost().getPath() + b.getPath());
            }
        }

        //...done 
        final URI out = b.build();

        APILog.debug(LOG, "Query:", out.toString());

        return out;
    } catch (Exception e) {
        throw new APIException("Could not build url: " + url, e);
    }
}

From source file:com.pennassurancesoftware.tutum.client.TutumClient.java

private URI createUri(ApiRequest request) {
    URIBuilder ub = new URIBuilder();
    ub.setScheme(Constants.HTTPS_SCHEME);
    ub.setHost(apiHost);/*from w ww .  ja  va 2s  . c om*/
    ub.setPath(createPath(request));

    for (String paramName : request.getQueryParams().keySet()) {
        final List<String> values = request.getQueryParams().get(paramName);
        for (String value : values) {
            ub.setParameter(paramName, value);
        }
    }

    URI uri = null;
    try {
        uri = ub.build();
    } catch (URISyntaxException use) {
        LOG.error(use.getMessage(), use);
    }

    return uri;
}

From source file:com.cisco.oss.foundation.http.apache.ApacheHttpClient.java

private URI buildUri(HttpRequest request, Joiner joiner) {
    URI requestUri = request.getUri();

    Map<String, Collection<String>> queryParams = request.getQueryParams();
    if (queryParams != null && !queryParams.isEmpty()) {
        URIBuilder uriBuilder = new URIBuilder();
        StringBuilder queryStringBuilder = new StringBuilder();
        boolean hasQuery = !queryParams.isEmpty();
        for (Map.Entry<String, Collection<String>> stringCollectionEntry : queryParams.entrySet()) {
            String key = stringCollectionEntry.getKey();
            Collection<String> queryParamsValueList = stringCollectionEntry.getValue();
            if (request.isQueryParamsParseAsMultiValue()) {
                for (String queryParamsValue : queryParamsValueList) {
                    uriBuilder.addParameter(key, queryParamsValue);
                    queryStringBuilder.append(key).append("=").append(queryParamsValue).append("&");
                }//from ww  w .j  a  v  a 2 s . c  o m
            } else {
                String value = joiner.join(queryParamsValueList);
                uriBuilder.addParameter(key, value);
                queryStringBuilder.append(key).append("=").append(value).append("&");
            }
        }
        uriBuilder.setFragment(requestUri.getFragment());
        uriBuilder.setHost(requestUri.getHost());
        uriBuilder.setPath(requestUri.getPath());
        uriBuilder.setPort(requestUri.getPort());
        uriBuilder.setScheme(requestUri.getScheme());
        uriBuilder.setUserInfo(requestUri.getUserInfo());
        try {

            if (!autoEncodeUri) {
                String urlPath = "";
                if (requestUri.getRawPath() != null && requestUri.getRawPath().startsWith("/")) {
                    urlPath = requestUri.getRawPath();
                } else {
                    urlPath = "/" + requestUri.getRawPath();
                }

                if (hasQuery) {
                    String query = queryStringBuilder.substring(0, queryStringBuilder.length() - 1);
                    requestUri = new URI(requestUri.getScheme() + "://" + requestUri.getHost() + ":"
                            + requestUri.getPort() + urlPath + "?" + query);
                } else {
                    requestUri = new URI(requestUri.getScheme() + "://" + requestUri.getHost() + ":"
                            + requestUri.getPort() + urlPath);
                }
            } else {
                requestUri = uriBuilder.build();
            }
        } catch (URISyntaxException e) {
            LOGGER.warn("could not update uri: {}", requestUri);
        }
    }
    return requestUri;
}

From source file:org.apache.ambari.server.controller.AmbariManagementControllerImpl.java

@Override
public String getAmbariServerURI(String path) {
    if (masterProtocol == null || masterHostname == null || masterPort == null) {
        return null;
    }//from   w  ww . j  a v  a 2 s .c o  m

    URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.setScheme(masterProtocol);
    uriBuilder.setHost(masterHostname);
    uriBuilder.setPort(masterPort);
    uriBuilder.setPath(path);

    return uriBuilder.toString();
}

From source file:org.apache.ambari.server.controller.metrics.ganglia.GangliaPropertyProviderTest.java

@Test
public void testPopulateResources() throws Exception {
    TestStreamProvider streamProvider = new TestStreamProvider("temporal_ganglia_data.txt");
    TestGangliaHostProvider hostProvider = new TestGangliaHostProvider();

    Map<String, Map<String, PropertyInfo>> gangliaPropertyIds = PropertyHelper
            .getMetricPropertyIds(Resource.Type.HostComponent);
    GangliaPropertyProvider propertyProvider = new GangliaHostComponentPropertyProvider(gangliaPropertyIds,
            streamProvider, configuration, hostProvider, CLUSTER_NAME_PROPERTY_ID, HOST_NAME_PROPERTY_ID,
            COMPONENT_NAME_PROPERTY_ID);

    // namenode// w ww  .  ja v  a 2s.c  o m
    Resource resource = new ResourceImpl(Resource.Type.HostComponent);

    resource.setProperty(HOST_NAME_PROPERTY_ID, "domU-12-31-39-0E-34-E1.compute-1.internal");
    resource.setProperty(COMPONENT_NAME_PROPERTY_ID, "DATANODE");

    // only ask for one property
    Map<String, TemporalInfo> temporalInfoMap = new HashMap<String, TemporalInfo>();
    temporalInfoMap.put(PROPERTY_ID, new TemporalInfoImpl(10L, 20L, 1L));
    Request request = PropertyHelper.getReadRequest(Collections.singleton(PROPERTY_ID), temporalInfoMap);

    Assert.assertEquals(1,
            propertyProvider.populateResources(Collections.singleton(resource), request, null).size());

    String expected = (configuration.isGangliaSSL() ? "https" : "http")
            + "://domU-12-31-39-0E-34-E1.compute-1.internal/cgi-bin/rrd.py?c=HDPDataNode%2CHDPSlaves&h=domU-12-31-39-0E-34-E1.compute-1.internal&m=jvm.metrics.gcCount&s=10&e=20&r=1";
    Assert.assertEquals(expected, streamProvider.getLastSpec());

    Assert.assertEquals(3, PropertyHelper.getProperties(resource).size());
    Assert.assertNotNull(resource.getPropertyValue(PROPERTY_ID));

    // tasktracker
    resource = new ResourceImpl(Resource.Type.HostComponent);
    resource.setProperty(HOST_NAME_PROPERTY_ID, "domU-12-31-39-0E-34-E1.compute-1.internal");
    resource.setProperty(COMPONENT_NAME_PROPERTY_ID, "TASKTRACKER");

    // only ask for one property
    temporalInfoMap = new HashMap<String, TemporalInfo>();

    Set<String> properties = new HashSet<String>();
    String shuffle_exceptions_caught = PropertyHelper.getPropertyId("metrics/mapred/shuffleOutput",
            "shuffle_exceptions_caught");
    String shuffle_failed_outputs = PropertyHelper.getPropertyId("metrics/mapred/shuffleOutput",
            "shuffle_failed_outputs");
    String shuffle_output_bytes = PropertyHelper.getPropertyId("metrics/mapred/shuffleOutput",
            "shuffle_output_bytes");
    String shuffle_success_outputs = PropertyHelper.getPropertyId("metrics/mapred/shuffleOutput",
            "shuffle_success_outputs");

    properties.add(shuffle_exceptions_caught);
    properties.add(shuffle_failed_outputs);
    properties.add(shuffle_output_bytes);
    properties.add(shuffle_success_outputs);
    request = PropertyHelper.getReadRequest(properties, temporalInfoMap);

    temporalInfoMap.put(shuffle_exceptions_caught, new TemporalInfoImpl(10L, 20L, 1L));
    temporalInfoMap.put(shuffle_failed_outputs, new TemporalInfoImpl(10L, 20L, 1L));
    temporalInfoMap.put(shuffle_output_bytes, new TemporalInfoImpl(10L, 20L, 1L));
    temporalInfoMap.put(shuffle_success_outputs, new TemporalInfoImpl(10L, 20L, 1L));

    Assert.assertEquals(1,
            propertyProvider.populateResources(Collections.singleton(resource), request, null).size());

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

    metricsRegexes.add("metrics/mapred/shuffleOutput/shuffle_exceptions_caught");
    metricsRegexes.add("metrics/mapred/shuffleOutput/shuffle_failed_outputs");
    metricsRegexes.add("metrics/mapred/shuffleOutput/shuffle_output_bytes");
    metricsRegexes.add("metrics/mapred/shuffleOutput/shuffle_success_outputs");

    String metricsList = getMetricsRegexes(metricsRegexes, gangliaPropertyIds, "TASKTRACKER");

    URIBuilder expectedUri = new URIBuilder();

    expectedUri.setScheme((configuration.isGangliaSSL() ? "https" : "http"));
    expectedUri.setHost("domU-12-31-39-0E-34-E1.compute-1.internal");
    expectedUri.setPath("/cgi-bin/rrd.py");
    expectedUri.setParameter("c", "HDPTaskTracker,HDPSlaves");
    expectedUri.setParameter("h", "domU-12-31-39-0E-34-E1.compute-1.internal");
    expectedUri.setParameter("m", metricsList);
    expectedUri.setParameter("s", "10");
    expectedUri.setParameter("e", "20");
    expectedUri.setParameter("r", "1");

    URIBuilder actualUri = new URIBuilder(streamProvider.getLastSpec());

    Assert.assertEquals(expectedUri.getScheme(), actualUri.getScheme());
    Assert.assertEquals(expectedUri.getHost(), actualUri.getHost());
    Assert.assertEquals(expectedUri.getPath(), actualUri.getPath());

    Assert.assertTrue(isUrlParamsEquals(actualUri, expectedUri));

    Assert.assertEquals(6, PropertyHelper.getProperties(resource).size());

    Assert.assertNotNull(resource.getPropertyValue(shuffle_exceptions_caught));

    Number[][] dataPoints = (Number[][]) resource.getPropertyValue(shuffle_exceptions_caught);

    Assert.assertEquals(106, dataPoints.length);
    for (int i = 0; i < dataPoints.length; ++i) {
        Assert.assertEquals(i >= 10 && i < 20 ? 7 : 0.0, dataPoints[i][0]);
        Assert.assertEquals(360 * i + 1358434800, dataPoints[i][1]);
    }

    Assert.assertNotNull(resource.getPropertyValue(shuffle_failed_outputs));
    Assert.assertNotNull(resource.getPropertyValue(shuffle_output_bytes));
    Assert.assertNotNull(resource.getPropertyValue(shuffle_success_outputs));
}