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

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

Introduction

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

Prototype

public URIBuilder() 

Source Link

Document

Constructs an empty instance.

Usage

From source file:cf.randers.scd.CommandLineInterface.java

private void run() {
    if (params == null)
        return;//from  w w w  .j  av a2  s  .  c o  m
    LOGGER.info("Making temp dir...");
    File tmpDir = new File("tmp/");
    File outDir = new File(outputDirectory);
    //noinspection ResultOfMethodCallIgnored
    tmpDir.mkdirs();
    //noinspection ResultOfMethodCallIgnored
    outDir.mkdirs();
    BlockingQueue<Runnable> tasks = new ArrayBlockingQueue<>(params.size());
    maximumConcurrentConnections = Math.min(params.size(),
            maximumConcurrentConnections > params.size() ? params.size() : maximumConcurrentConnections);
    ThreadPoolExecutor executor = new ThreadPoolExecutor(maximumConcurrentConnections,
            maximumConcurrentConnections, 0, TimeUnit.NANOSECONDS, tasks);
    LOGGER.info("Starting to execute " + params.size() + " thread(s)...");
    for (String param : params) {
        executor.execute(() -> {
            LOGGER.info("Started thread for " + param);
            Map json;
            byte[] artworkBytes = new byte[0];
            List<Track> toProcess = new ArrayList<>();
            LOGGER.info("Resolving and querying track info...");
            try (CloseableHttpClient client = HttpClients.createDefault();
                    CloseableHttpResponse response = client.execute(new HttpGet(new URIBuilder()
                            .setScheme("https").setHost("api.soundcloud.com").setPath("/resolve")
                            .addParameter("url", param).addParameter("client_id", clientID).build()));
                    InputStreamReader inputStreamReader = new InputStreamReader(
                            response.getEntity().getContent())) {

                final int bufferSize = 1024;
                final char[] buffer = new char[bufferSize];
                final StringBuilder out = new StringBuilder();
                for (;;) {
                    int rsz = inputStreamReader.read(buffer, 0, buffer.length);
                    if (rsz < 0)
                        break;
                    out.append(buffer, 0, rsz);
                }
                String rawJson = out.toString();
                Album a = new Gson().fromJson(rawJson, Album.class);

                if (a.getTrackCount() == null) {
                    Track tr = new Gson().fromJson(rawJson, Track.class);
                    toProcess.add(tr);
                }
                toProcess.addAll(a.getTracks());
                EntityUtils.consumeQuietly(response.getEntity());
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
            for (Track track : toProcess) {
                System.out.println(track.getId());
                System.out.println(track.getTitle());
            }
            for (Track track : toProcess) {
                LOGGER.info("Downloading mp3 to file...");
                File tmpFile = new File("tmp/" + String.format("%d", track.getId()) + ".mp3");

                try (CloseableHttpClient client = HttpClients.createDefault();
                        CloseableHttpResponse response = client
                                .execute(new HttpGet(track.getStreamUrl() + "?client_id=" + clientID))) {
                    IOUtils.copy(response.getEntity().getContent(), new FileOutputStream(tmpFile));
                    EntityUtils.consumeQuietly(response.getEntity());
                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                }

                boolean hasArtwork = track.getArtworkUrl() != null;

                if (hasArtwork) {
                    LOGGER.info("Downloading artwork jpg into memory...");
                    try (CloseableHttpClient client = HttpClients.createDefault();
                            CloseableHttpResponse response = client.execute(
                                    new HttpGet(track.getArtworkUrl().replace("-large.jpg", "-t500x500.jpg")
                                            + "?client_id=" + clientID))) {
                        artworkBytes = IOUtils.toByteArray(response.getEntity().getContent());
                        EntityUtils.consumeQuietly(response.getEntity());
                    } catch (Exception e) {
                        e.printStackTrace();
                        return;
                    }
                }

                try {
                    LOGGER.info("Reading temp file into AudioFile object...");
                    // Read audio file from tmp directory
                    AudioFile audioFile = AudioFileIO.read(tmpFile);

                    // Set Artwork
                    Tag tag = audioFile.getTagAndConvertOrCreateAndSetDefault();
                    if (hasArtwork) {
                        StandardArtwork artwork = new StandardArtwork();
                        artwork.setBinaryData(artworkBytes);
                        artwork.setImageFromData();
                        tag.addField(artwork);
                    }
                    tag.addField(FieldKey.TITLE, track.getTitle());
                    tag.addField(FieldKey.ARTIST, track.getUser().getUsername());
                    LOGGER.info("Saving audio file...");
                    System.out.println(
                            outDir.getAbsolutePath() + "/" + String.format(outputformat, track.getId()));
                    new AudioFileIO().writeFile(audioFile,
                            outDir.getAbsolutePath() + "/" + String.format(outputformat, track.getId()));
                    tmpFile.deleteOnExit();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            File[] listFiles = tmpDir.listFiles();
            if (listFiles == null) {
                return;
            }
            for (File file : listFiles) {
                file.delete();
            }
        });
    }
    executor.shutdown();
}

From source file:org.wuspba.ctams.ws.ITSoloContestController.java

@Test
public void testListVenue() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
            .setParameter("venue", TestFixture.INSTANCE.venue.getId())
            .setParameter("season", Integer.toString(TestFixture.INSTANCE.soloContest.getSeason())).build();

    HttpGet httpGet = new HttpGet(uri);

    try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
        assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING);

        HttpEntity entity = response.getEntity();

        CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity);

        assertEquals(doc.getSoloContests().size(), 1);
        testEquality(doc.getSoloContests().get(0), TestFixture.INSTANCE.soloContest);

        EntityUtils.consume(entity);/* w ww  .j a  va  2  s. c om*/
    }

    uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
            .setParameter("venue", "garbage")
            .setParameter("season", Integer.toString(TestFixture.INSTANCE.soloContest.getSeason())).build();

    httpGet = new HttpGet(uri);

    try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
        assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING);

        HttpEntity entity = response.getEntity();

        CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity);

        assertEquals(doc.getSoloContests().size(), 0);

        EntityUtils.consume(entity);
    }
}

From source file:com.github.dziga.orest.client.HttpRestClient.java

int Put(String body) throws IOException, URISyntaxException {
    URIBuilder b = new URIBuilder().setScheme(scheme).setHost(host).setPath(path);
    addQueryParams(b);/*from  www.java 2 s .co  m*/
    URI fullUri = b.build();
    HttpPut putMethod = new HttpPut(fullUri);
    HttpEntity entity = new StringEntity(body);
    putMethod.setEntity(entity);
    putMethod = (HttpPut) addHeadersToMethod(putMethod);

    processResponse(httpClient.execute(putMethod));

    return getResponseCode();
}

From source file:fr.treeptik.cloudunit.docker.core.SimpleDockerDriver.java

@Override
public DockerResponse findAll() throws FatalDockerJSONException {
    URI uri = null;//from   w w  w .  j av a  2  s . c o  m
    String body = new String();
    DockerResponse dockerResponse = null;
    try {
        uri = new URIBuilder().setScheme(protocol).setHost(host).setPath("/containers/json").build();
        dockerResponse = client.sendGet(uri);
    } catch (URISyntaxException | JSONClientException e) {
        StringBuilder contextError = new StringBuilder(256);
        contextError.append("uri : " + uri + " - ");
        contextError.append("request body : " + body + " - ");
        contextError.append("server response : " + dockerResponse);
        logger.error(contextError.toString());
        throw new FatalDockerJSONException(
                "An error has occurred for find all containers request due to " + e.getMessage(), e);
    }

    return dockerResponse;
}

From source file:com.freedomotic.plugins.devices.push.Push.java

@Override
protected void onEvent(EventTemplate e) {
    try {/*from  w w w .  j a v  a2 s  .  c  om*/
        MessageEvent event = (MessageEvent) e;
        int t = tupleMap.get(event.getDefaultDestination());

        URIBuilder ub = new URIBuilder()
                .setScheme(configuration.getTuples().getStringProperty(t, "scheme", "http"))
                .setHost(configuration.getTuples().getStringProperty(t, "host", "localhost"))
                .setPort(configuration.getTuples().getIntProperty(t, "port",
                        configuration.getTuples().getStringProperty(t, "scheme", "http")
                                .equalsIgnoreCase("https") ? 443 : 80))
                .setPath(configuration.getTuples().getStringProperty(t, "path", "/"));

        // prepare substitution tokens
        HashMap<String, String> valuesMap = new HashMap<>();
        Iterator<Statement> it = event.getPayload().iterator();
        while (it.hasNext()) {
            Statement s = it.next();
            if (s.getOperand().equalsIgnoreCase(Statement.EQUALS)) {
                valuesMap.put(s.getAttribute(), s.getValue());
            }
        }
        StrSubstitutor sub = new StrSubstitutor(valuesMap);

        // add extra parameters
        for (String key : configuration.getTuples().getTuple(t).keySet()) {
            if (key.startsWith("param.")) {
                String toBeReplaced = configuration.getTuples().getStringProperty(t, key, "");
                // replace default string with the one provided into payload
                if (event.getPayload().getStatementValue(key) != null
                        && !event.getPayload().getStatementValue(key).isEmpty()) {
                    toBeReplaced = event.getPayload().getStatementValue(key);
                }
                // do substitutions
                String resolvedString = sub.replace(toBeReplaced);

                ub.setParameter(key.substring(6), resolvedString);
            }
        }

        // override default message (with variable substitution) if a new one is specified in MessageEvent.text
        if (event.getText() != null & !event.getText().isEmpty()) {
            ub.setParameter(configuration.getTuples().getStringProperty(t, "mapMessageToParam", "message"),
                    sub.replace(event.getText()));
        }

        LOG.info(ub.build().toString());

        HttpClientBuilder hcb = HttpClientBuilder.create();
        HttpClient client = hcb.build();

        // set http method to use
        HttpRequestBase request;
        if (configuration.getTuples().getStringProperty(t, "method", "get").equalsIgnoreCase("POST")) {
            request = new HttpPost(ub.build());
        } else {
            request = new HttpGet(ub.build());
        }

        int responseCode = client.execute(request).getStatusLine().getStatusCode();
        LOG.info("Push request got code: " + responseCode);

    } catch (URISyntaxException | IOException ex) {
        LOG.log(Level.SEVERE, null, ex);
    }
}

From source file:com.snowplowanalytics.snowplow.tracker.emitter.Emitter.java

/**
 * Create an Emitter instance with a collector URL and HttpMethod to send requests.
 * @param URI The collector URL. Don't include "http://" - this is done automatically.
 * @param httpMethod The HTTP request method. If GET, <code>BufferOption</code> is set to <code>Instant</code>.
 * @param callback The callback function to handle success/failure cases when sending events.
 *///from w w  w.ja  v  a  2 s  .  c om
public Emitter(String URI, HttpMethod httpMethod, RequestCallback callback) {
    if (httpMethod == HttpMethod.GET) {
        uri = new URIBuilder().setScheme("http").setHost(URI).setPath("/i");
    } else { // POST
        uri = new URIBuilder().setScheme("http").setHost(URI)
                .setPath("/" + Constants.PROTOCOL_VENDOR + "/" + Constants.PROTOCOL_VERSION);
    }
    this.requestCallback = callback;
    this.httpMethod = httpMethod;
    this.httpClient = HttpClients.createDefault();

    if (httpMethod == HttpMethod.GET) {
        this.setBufferOption(BufferOption.Instant);
    }

}

From source file:com.att.voice.AttDigitalLife.java

public String getDeviceGUID(String device, Map<String, String> authMap) {
    try {//w ww . j  a  v  a 2 s. c o  m
        URIBuilder builder = new URIBuilder();
        builder.setScheme("https").setHost(DIGITAL_LIFE_PATH)
                .setPath("/penguin/api/" + authMap.get("id") + "/devices");

        URI uri = builder.build();
        HttpGet httpget = new HttpGet(uri);
        httpget.setHeader("Authtoken", authMap.get("Authtoken"));
        httpget.setHeader("Requesttoken", authMap.get("Requesttoken"));
        httpget.setHeader("Appkey", authMap.get("Appkey"));

        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
            @Override
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }
        };
        String responseBody = httpclient.execute(httpget, responseHandler);

        String json = responseBody.trim();
        JSONObject jsonObject = new JSONObject(json);

        JSONArray array = jsonObject.getJSONArray("content");

        for (int i = 0; i <= array.length(); i++) {
            JSONObject d = array.getJSONObject(i);
            String type = d.getString("deviceType");
            if (type.equalsIgnoreCase(device)) {
                return d.getString("deviceGuid");
            }
        }
    } catch (URISyntaxException | IOException | JSONException ex) {
        System.err.println(ex.getMessage());
        return null;
    }
    return null;
}

From source file:net.datacrow.onlinesearch.bol.BolClient.java

/**
 * Searches./*from   w  ww .  ja v a  2  s  .  c o m*/
 * 
 * @param term The search term (required).
 * @param categoryID The category id and refinements, separated by spaces (optional).
 */
public String search(String term, String categoryID) throws IOException, URISyntaxException {
    List<NameValuePair> queryParams = new ArrayList<NameValuePair>();
    queryParams.add(new BasicNameValuePair("term", term));

    if (categoryID != null)
        queryParams.add(new BasicNameValuePair("categoryId", categoryID));

    queryParams.add(new BasicNameValuePair("nrProducts", "10"));
    queryParams.add(new BasicNameValuePair("includeProducts", "TRUE"));
    queryParams.add(new BasicNameValuePair("includeCategories", "TRUE"));
    queryParams.add(new BasicNameValuePair("includeRefinements", "FALSE"));

    URIBuilder builder = new URIBuilder();
    builder.setScheme("https");
    builder.setHost("openapi.bol.com");
    builder.setPath("/openapi/services/rest/catalog/v3/searchresults/");
    builder.setQuery(URLEncodedUtils.format(queryParams, "UTF-8"));

    HttpGet httpGet = new HttpGet(builder.build());

    HttpOAuthHelper au = new HttpOAuthHelper("application/xml");
    au.handleRequest(httpGet, accessKeyId, secretAccessKey, null, queryParams);

    HttpResponse httpResponse = httpClient.execute(httpGet);
    String xml = getXML(httpResponse);
    httpClient.getConnectionManager().shutdown();
    return xml;
}

From source file:org.jenkinsci.plugins.os_ci.repohandlers.OpenStackClient.java

public void generateToken() {
    GetToken gett = new GetToken();
    Auth auth = new Auth();
    PasswordCredentials pass = new PasswordCredentials();
    pass.setPassword(openstackPassword);
    pass.setUsername(openstackUser);//  ww w . j a va2 s.co m
    auth.setPasswordCredentials(pass);
    auth.setTenantName(openstackTenantName);
    gett.setAuth(auth);
    try {
        String body = JsonBuilder.createJson(gett);

        URI uri = new URIBuilder().setScheme("http").setHost(openstackHost).setPort(openstackPort)
                .setPath(openstackPath).build();
        HttpPost httpPost = new HttpPost(uri);
        httpPost.addHeader("Accept", "application/json");
        final StringEntity entity = new StringEntity(body, ContentType.APPLICATION_JSON);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            int status = response.getStatusLine().getStatusCode();

            if (status != 200) {
                throw new OsCiPluginException("Invalid OpenStack server response " + status);
            }
            this.entryPoints = JsonParser.parseGetTokenAndEntryPoints(response);
        } finally {
            response.close();
        }
    } catch (IOException e) {
        throw new OsCiPluginException("IOException in getToken " + e.getMessage());
    } catch (URISyntaxException e) {
        throw new OsCiPluginException("URISyntaxException in getToken " + e.getMessage());
    } catch (Exception e) {
        throw new OsCiPluginException("IOException in getToken " + e.getMessage());
    }
}