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

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

Introduction

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

Prototype

public URIBuilder addParameter(final String param, final String value) 

Source Link

Document

Adds parameter to URI query.

Usage

From source file:com.linemetrics.monk.api.RestClient.java

public URI buildURI(String path, Map<String, String> params) throws URISyntaxException {
    URIBuilder ub = new URIBuilder(uri);
    ub.setPath(ub.getPath() + path);/*from  w  ww.j  a v a  2s.c o m*/

    if (params != null) {
        for (Map.Entry<String, String> ent : params.entrySet())
            ub.addParameter(ent.getKey(), ent.getValue());
    }

    return ub.build();
}

From source file:com.activiti.service.activiti.ProcessInstanceService.java

public JsonNode getTasks(ServerConfig serverConfig, String processInstanceId) {
    URIBuilder builder = clientUtil.createUriBuilder(HISTORIC_TASK_LIST_URL);
    builder.addParameter("processInstanceId", processInstanceId);
    builder.addParameter("size", DEFAULT_SUBTASK_RESULT_SIZE);

    HttpGet get = new HttpGet(clientUtil.getServerUrl(serverConfig, builder));
    return clientUtil.executeRequest(get, serverConfig);
}

From source file:com.zazuko.wikidata.municipalities.SparqlClient.java

List<Map<String, RDFTerm>> queryResultSet(final String query) throws IOException, URISyntaxException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    URIBuilder builder = new URIBuilder(endpoint);
    builder.addParameter("query", query);
    HttpGet httpGet = new HttpGet(builder.build());
    /*List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("query", query));
    httpGet.setEntity(new UrlEncodedFormEntity(nvps));*/
    CloseableHttpResponse response2 = httpclient.execute(httpGet);

    try {/*from   w w w  .java  2s  .  c o  m*/
        HttpEntity entity2 = response2.getEntity();
        InputStream in = entity2.getContent();
        if (debug) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            for (int ch = in.read(); ch != -1; ch = in.read()) {
                System.out.print((char) ch);
                baos.write(ch);
            }
            in = new ByteArrayInputStream(baos.toByteArray());
        }
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        SAXParser saxParser = spf.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        final SparqlsResultsHandler sparqlsResultsHandler = new SparqlsResultsHandler();
        xmlReader.setContentHandler(sparqlsResultsHandler);
        xmlReader.parse(new InputSource(in));
        /*
         for (int ch = in.read(); ch != -1; ch = in.read()) {
         System.out.print((char)ch);
         }
         */
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity2);
        return sparqlsResultsHandler.getResults();
    } catch (ParserConfigurationException ex) {
        throw new RuntimeException(ex);
    } catch (SAXException ex) {
        throw new RuntimeException(ex);
    } finally {
        response2.close();
    }

}

From source file:com.linagora.james.mailets.GuessClassificationMailet.java

private URI serviceUrlWithQueryParameters(Collection<MailAddress> recipients) throws URISyntaxException {
    URIBuilder uriBuilder = new URIBuilder(serviceUrl);
    recipients.forEach(address -> uriBuilder.addParameter("recipients", address.asString()));
    return uriBuilder.build();
}

From source file:nl.eveoh.mytimetable.apiclient.service.MyTimetableServiceImpl.java

/**
 * Creates a request for each MyTimetable API endpoint defined in the configuration.
 *
 * @param username Username the fetch the upcoming events for.
 * @return List of {@link HttpUriRequest} objects, which should be executed in order, until a result is acquired.
 *//*from w w w.j av a2  s  .  com*/
private ArrayList<HttpUriRequest> getApiRequests(String username) {
    if (StringUtils.isBlank(username)) {
        log.error("Username cannot be empty.");
        throw new LocalizableException("Username cannot be empty.", "notLoggedIn");
    }

    if (StringUtils.isBlank(configuration.getApiKey())) {
        log.error("API key cannot be empty.");
        throw new LocalizableException("API key cannot be empty.");
    }

    // Prefix the username, for example when MyTimetable is used in a domain.
    String domainPrefix = configuration.getUsernameDomainPrefix();
    if (domainPrefix != null && !domainPrefix.isEmpty()) {
        username = domainPrefix + '\\' + username;
    }

    // build request URI
    Date currentTime = new Date();

    ArrayList<HttpUriRequest> requests = new ArrayList<HttpUriRequest>();

    for (String uri : configuration.getApiEndpointUris()) {
        String baseUrl;

        if (uri.endsWith("/")) {
            baseUrl = uri + "timetable";
        } else {
            baseUrl = uri + "/timetable";
        }

        try {
            URIBuilder uriBuilder = new URIBuilder(baseUrl);
            uriBuilder.addParameter("startDate", Long.toString(currentTime.getTime()));
            uriBuilder.addParameter("limit", Integer.toString(configuration.getNumberOfEvents()));

            URI apiUri = uriBuilder.build();

            HttpGet request = new HttpGet(apiUri);
            request.addHeader("apiToken", configuration.getApiKey());
            request.addHeader("requestedAuth", username);

            // Configure request timeouts.
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(configuration.getApiSocketTimeout())
                    .setConnectTimeout(configuration.getApiConnectTimeout()).build();

            request.setConfig(requestConfig);

            requests.add(request);
        } catch (URISyntaxException e) {
            log.error("Incorrect MyTimetable API url syntax.", e);
        }
    }

    if (requests.isEmpty()) {
        log.error("No usable MyTimetable API url.");
        throw new LocalizableException("No usable MyTimetable API url.");
    }

    return requests;
}

From source file:org.eclipse.packagedrone.testing.server.channel.UploadApiV3Test.java

@Test
public void upload1Plain() throws URISyntaxException, IOException {
    final ChannelTester tester = ChannelTester.create(getWebContext(), "uploadapi2a");
    tester.assignDeployGroup("m1");
    final String deployKey = tester.getDeployKeys().iterator().next();

    final File file = getAbsolutePath(CommonResources.BUNDLE_1_RESOURCE);

    final URIBuilder b = new URIBuilder(
            resolve("/api/v3/upload/plain/channel/%s/%s", tester.getId(), file.getName()));
    b.setUserInfo("deploy", deployKey);
    b.addParameter("foo:bar", "baz");

    System.out.println("Request: " + b.build());

    try (final CloseableHttpResponse response = upload(b, file)) {
        final String result = CharStreams
                .toString(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
        System.out.println("Result: " + response.getStatusLine());
        System.out.println(result);
        Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    }//from   ww  w.j av a 2 s  .  c  o m

    final Set<String> arts = tester.getAllArtifactIds();

    Assert.assertEquals(1, arts.size());
}

From source file:org.dspace.submit.lookup.CrossRefService.java

public List<Record> search(Context context, Set<String> dois, String apiKey)
        throws HttpException, IOException, JDOMException, ParserConfigurationException, SAXException {
    List<Record> results = new ArrayList<Record>();
    if (dois != null && dois.size() > 0) {
        for (String record : dois) {
            try {
                HttpGet method = null;// ww w  .j  av a  2s  . c  o  m
                try {
                    HttpClient client = new DefaultHttpClient();
                    client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);

                    try {
                        URIBuilder uriBuilder = new URIBuilder("http://www.crossref.org/openurl/");
                        uriBuilder.addParameter("pid", apiKey);
                        uriBuilder.addParameter("noredirect", "true");
                        uriBuilder.addParameter("id", record);
                        method = new HttpGet(uriBuilder.build());
                    } catch (URISyntaxException ex) {
                        throw new HttpException("Request not sent", ex);
                    }

                    // Execute the method.
                    HttpResponse response = client.execute(method);
                    StatusLine statusLine = response.getStatusLine();
                    int statusCode = statusLine.getStatusCode();

                    if (statusCode != HttpStatus.SC_OK) {
                        throw new RuntimeException("Http call failed: " + statusLine);
                    }

                    Record crossitem;
                    try {
                        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                        factory.setValidating(false);
                        factory.setIgnoringComments(true);
                        factory.setIgnoringElementContentWhitespace(true);

                        DocumentBuilder db = factory.newDocumentBuilder();
                        Document inDoc = db.parse(response.getEntity().getContent());

                        Element xmlRoot = inDoc.getDocumentElement();
                        Element queryResult = XMLUtils.getSingleElement(xmlRoot, "query_result");
                        Element body = XMLUtils.getSingleElement(queryResult, "body");
                        Element dataRoot = XMLUtils.getSingleElement(body, "query");

                        crossitem = CrossRefUtils.convertCrossRefDomToRecord(dataRoot);
                        results.add(crossitem);
                    } catch (Exception e) {
                        log.warn(LogManager.getHeader(context, "retrieveRecordDOI",
                                record + " DOI is not valid or not exist: " + e.getMessage()));
                    }
                } finally {
                    if (method != null) {
                        method.releaseConnection();
                    }
                }
            } catch (RuntimeException rt) {
                log.error(rt.getMessage(), rt);
            }
        }
    }
    return results;
}