Example usage for org.apache.http.client.fluent Request Post

List of usage examples for org.apache.http.client.fluent Request Post

Introduction

In this page you can find the example usage for org.apache.http.client.fluent Request Post.

Prototype

public static Request Post(final String uri) 

Source Link

Usage

From source file:streamflow.service.LogService.java

public TopologyLogPage getTopologyLogCluster(Topology topology, Cluster cluster, TopologyLogCriteria criteria) {
    TopologyLogPage logPage = new TopologyLogPage();
    logPage.setTopology(topology.getId());
    logPage.setCriteria(criteria);//www.ja v a 2  s  . c  o m

    BoolQueryBuilder query = QueryBuilders.boolQuery();
    query.must(QueryBuilders.termQuery("topology.raw", topology.getId()));

    if (criteria.getQuery() != null && !criteria.getQuery().trim().isEmpty()) {
        query.must(QueryBuilders.queryString(criteria.getQuery()));
    }
    if (criteria.getLevel() != null) {
        query.must(QueryBuilders.termQuery("level.raw", criteria.getLevel()));
    }
    if (criteria.getComponent() != null) {
        query.must(QueryBuilders.termQuery("component.raw", criteria.getComponent()));
    }
    if (criteria.getCategory() != null) {
        query.must(QueryBuilders.termQuery("category.raw", criteria.getCategory()));
    }
    if (!criteria.getShowHistoric()) {
        query.must(QueryBuilders.termQuery("project.raw", topology.getProjectId()));
    }

    // TODO: HANDLE THE AGE CRITERIA

    SortOrder sortOrder = SortOrder.DESC;
    if (criteria.getSortOrder() != null) {
        if (criteria.getSortOrder() == TopologyLogCriteria.SortOrder.ASC) {
            sortOrder = SortOrder.ASC;
        }
    }

    SearchSourceBuilder searchBuilder = SearchSourceBuilder.searchSource().query(query)
            .from((criteria.getPageNum() - 1) * criteria.getPageSize()).size(criteria.getPageSize())
            .sort("@timestamp", sortOrder).facet(FacetBuilders.termsFacet("levels").field("level.raw"))
            .facet(FacetBuilders.termsFacet("components").field("component.raw"))
            .facet(FacetBuilders.termsFacet("categories").field("category.raw"));

    try {
        Response searchResponse = Request
                .Post(String.format("http://%s:%d/_all/topology/_search", cluster.getLogServerHost(),
                        cluster.getLogServerPort()))
                .bodyString(searchBuilder.toString(), ContentType.APPLICATION_JSON).execute();

        logPage = parseSearchResponse(logPage, criteria, searchResponse.returnContent().asString());

    } catch (IOException ex) {
        //LOG.error("Unable to parse log search response: ", ex);

        throw new ServiceException("Unable to parse log search response: " + ex.getMessage());
    }

    return logPage;
}

From source file:org.restheart.test.integration.JsonPathConditionsCheckerIT.java

@Test
public void testPatchData() throws Exception {
    Response resp;/*from   w  w w  .j  a va  2 s  .  c  om*/

    // *** test create valid data
    final String VALID_USER = getResourceFile("data/jsonpath-testuser.json");

    resp = adminExecutor.execute(Request.Post(collectionTmpUri).bodyString(VALID_USER, halCT)
            .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));

    check("check post valid data", resp, HttpStatus.SC_CREATED);

    // *** test patch valid data with dot notation
    final String VALID_USER_DN = getResourceFile("data/jsonpath-testuser-dotnot.json");

    resp = adminExecutor.execute(Request.Patch(userURI).bodyString(VALID_USER_DN, halCT)
            .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));

    check("check patch valid data with dot notation", resp, HttpStatus.SC_OK);

    // *** test patch invalid key
    final String INVALID_KEY = "{\"notexist\": 1}";

    resp = adminExecutor.execute(Request.Patch(userURI).bodyString(INVALID_KEY, halCT)
            .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));

    check("check patch invalid key with dot notation", resp, HttpStatus.SC_BAD_REQUEST);

    // *** test patch invalid key
    final String INVALID_KEY_DN = "{\"details.notexists\": 1}";

    resp = adminExecutor.execute(Request.Patch(userURI).bodyString(INVALID_KEY_DN, halCT)
            .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));

    check("check patch invalid key with dot notation", resp, HttpStatus.SC_BAD_REQUEST);

    // *** test patch wrong type object data
    final String INVALID_OBJ = "{\"details.city\": 1}";

    resp = adminExecutor.execute(Request.Patch(userURI).bodyString(INVALID_OBJ, halCT)
            .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));

    check("check patch wrong type object data with dot notation", resp, HttpStatus.SC_BAD_REQUEST);

    // *** test patch invalid array data
    final String INVALID_ARRAY = "{\"roles.0\": 1}";

    resp = adminExecutor.execute(Request.Patch(userURI).bodyString(INVALID_ARRAY, halCT)
            .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));

    check("check patch invalid array data with dot notation", resp, HttpStatus.SC_BAD_REQUEST);
}

From source file:org.biopax.validator.BiopaxValidatorClient.java

/**
 * Checks a BioPAX OWL file(s) or resource 
 * using the online BioPAX Validator //from  w w w  . j av  a 2  s . c  om
 * and prints the results to the output stream.
 * 
 * @param autofix true/false (experimental)
 * @param profile validation profile name
 * @param retFormat xml, html, or owl (no errors, just modified owl, if autofix=true)
 * @param biopaxUrl check the BioPAX at the URL
 * @param biopaxFiles an array of BioPAX files to validate
 * @param out
 * @throws IOException
 */
public void validate(boolean autofix, String profile, RetFormat retFormat, Behavior filterBy, Integer maxErrs,
        String biopaxUrl, File[] biopaxFiles, OutputStream out) throws IOException {
    MultipartEntityBuilder meb = MultipartEntityBuilder.create();
    meb.setCharset(Charset.forName("UTF-8"));

    if (autofix)
        meb.addTextBody("autofix", "true");

    //TODO add extra options (normalizer.fixDisplayName, normalizer.xmlBase)?

    if (profile != null && !profile.isEmpty())
        meb.addTextBody("profile", profile);
    if (retFormat != null)
        meb.addTextBody("retDesired", retFormat.toString().toLowerCase());
    if (filterBy != null)
        meb.addTextBody("filter", filterBy.toString());
    if (maxErrs != null && maxErrs > 0)
        meb.addTextBody("maxErrors", maxErrs.toString());
    if (biopaxFiles != null && biopaxFiles.length > 0)
        for (File f : biopaxFiles) //important: use MULTIPART_FORM_DATA content-type
            meb.addBinaryBody("file", f, ContentType.MULTIPART_FORM_DATA, f.getName());
    else if (biopaxUrl != null) {
        meb.addTextBody("url", biopaxUrl);
    } else {
        log.error("Nothing to do (no BioPAX data specified)!");
        return;
    }

    HttpEntity httpEntity = meb.build();
    //       if(log.isDebugEnabled()) httpEntity.writeTo(System.err);
    String content = Executor.newInstance().execute(Request.Post(url).body(httpEntity)).returnContent()
            .asString();

    //save: append to the output stream (file)
    BufferedReader res = new BufferedReader(new StringReader(content));
    String line;
    PrintWriter writer = new PrintWriter(out);
    while ((line = res.readLine()) != null) {
        writer.println(line);
    }
    writer.flush();
    res.close();
}

From source file:biz.dfch.j.clickatell.ClickatellClient.java

public MessageResponse sendMessage(String recipient, String message, int maxCredits, int maxParts)
        throws IOException, HttpResponseException {
    class ClickatellMessage {
        public ArrayList<String> to = new ArrayList<String>();
        public String text;
        public String maxCredits;
        public String maxMessageParts;
    }//from  w w  w  .  j av  a2s  .  c  o m
    try {
        ClickatellMessage clickatellMessage = new ClickatellMessage();
        clickatellMessage.to.add(recipient);
        clickatellMessage.text = message;
        clickatellMessage.maxCredits = (0 == maxCredits) ? null : Integer.toString(maxCredits);
        clickatellMessage.maxMessageParts = (0 == maxParts) ? null : Integer.toString(maxParts);

        ObjectMapper om = new ObjectMapper();
        om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        om.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        String request = om.writeValueAsString(clickatellMessage);
        String response = Request.Post(uriMessage.toString()).setHeader(headerApiVersion)
                .setHeader(headerContentType).setHeader(headerAccept).setHeader("Authorization", bearerToken)
                .bodyString(request, ContentType.APPLICATION_JSON).execute().returnContent().asString();
        MessageResponse messageResponse = om.readValue(response, MessageResponse.class);
        return messageResponse;
    } catch (HttpResponseException ex) {
        int statusCode = ex.getStatusCode();
        switch (statusCode) {
        case 410:
            LOG.error(String.format("Sending message to '%s' FAILED with HTTP %d. No coverage of recipient.",
                    recipient, statusCode));
            break;
        default:
            break;
        }
        throw ex;
    }
}

From source file:org.jodconverter.task.OnlineConversionTask.java

@Override
public void execute(final OfficeContext context) throws OfficeException {

    LOGGER.info("Executing online conversion task...");
    final OnlineOfficeContext onlineContext = (OnlineOfficeContext) context;

    // Obtain a source file that can be loaded by office. If the source
    // is an input stream, then a temporary file will be created from the
    // stream. The temporary file will be deleted once the task is done.
    final File sourceFile = source.getFile();
    try {//from   ww w.j  av a  2 s .  c o m

        // Get the target file (which is a temporary file if the
        // output target is an output stream).
        final File targetFile = target.getFile();

        try {
            // TODO: Add the ability to pass on a custom charset to FileBody

            // See https://github.com/LibreOffice/online/blob/master/wsd/reference.txt
            final HttpEntity entity = MultipartEntityBuilder.create().addPart("data", new FileBody(sourceFile))
                    .build();

            // Use the fluent API to post the file and
            // save the response into the target file.
            final RequestConfig requestConfig = onlineContext.getRequestConfig();
            final URIBuilder uriBuilder = new URIBuilder(buildUrl(requestConfig.getUrl()));

            // We suppose that the server supports custom load properties,
            // but LibreOffice does not support custom load properties,
            // only the sample web service do.
            addPropertiesToBuilder(uriBuilder, target.getFormat().getLoadProperties(),
                    LOAD_PROPERTIES_PREFIX_PARAM);

            // We suppose that the server supports custom store properties,
            // but LibreOffice does not support custom store properties,
            // only the sample web service do.
            addPropertiesToBuilder(uriBuilder,
                    target.getFormat().getStoreProperties(source.getFormat().getInputFamily()),
                    STORE_PROPERTIES_PREFIX_PARAM);

            Executor.newInstance(onlineContext.getHttpClient()).execute(
                    // Request.Post(buildUrl(requestConfig.getUrl()))
                    Request.Post(uriBuilder.build()).connectTimeout(requestConfig.getConnectTimeout())
                            .socketTimeout(requestConfig.getSocketTimeout()).body(entity))
                    .saveContent(targetFile);

            // onComplete on target will copy the temp file to
            // the OutputStream and then delete the temp file
            // if the output is an OutputStream
            target.onComplete(targetFile);

        } catch (Exception ex) {
            LOGGER.error("Online conversion failed.", ex);
            final OfficeException officeEx = new OfficeException("Online conversion failed", ex);
            target.onFailure(targetFile, officeEx);
            throw officeEx;
        }

    } finally {

        // Here the source file is no longer required so we can delete
        // any temporary file that has been created if required.
        source.onConsumed(sourceFile);
    }
}

From source file:eu.esdihumboldt.hale.io.wfs.AbstractWFSWriter.java

@Override
public IOReport execute(ProgressIndicator progress) throws IOProviderConfigurationException, IOException {
    progress.begin("WFS Transaction", ProgressIndicator.UNKNOWN);

    // configure internal provider
    internalProvider.setDocumentWrapper(createTransaction());

    final PipedInputStream pIn = new PipedInputStream();
    PipedOutputStream pOut = new PipedOutputStream(pIn);
    currentExecuteStream = pOut;/*from  w ww  .j a  va  2  s  . co  m*/

    Future<Response> futureResponse = null;
    IOReporter reporter = createReporter();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    try {
        // read the stream (in another thread)
        futureResponse = executor.submit(new Callable<Response>() {

            @Override
            public Response call() throws Exception {

                Proxy proxy = ProxyUtil.findProxy(targetWfs.getLocation());
                Request request = Request.Post(targetWfs.getLocation()).bodyStream(pIn,
                        ContentType.APPLICATION_XML);
                Executor executor = FluentProxyUtil.setProxy(request, proxy);

                // authentication
                String user = getParameter(PARAM_USER).as(String.class);
                String password = getParameter(PARAM_PASSWORD).as(String.class);

                if (user != null) {
                    // target host
                    int port = targetWfs.getLocation().getPort();
                    String hostName = targetWfs.getLocation().getHost();
                    String scheme = targetWfs.getLocation().getScheme();
                    HttpHost host = new HttpHost(hostName, port, scheme);

                    // add credentials
                    Credentials cred = ClientProxyUtil.createCredentials(user, password);
                    executor.auth(new AuthScope(host), cred);
                    executor.authPreemptive(host);
                }

                try {
                    return executor.execute(request);
                } finally {
                    pIn.close();
                }
            }
        });

        // write the stream
        SubtaskProgressIndicator subprogress = new SubtaskProgressIndicator(progress);
        reporter = (IOReporter) super.execute(subprogress);
    } finally {
        executor.shutdown();
    }

    try {
        Response response = futureResponse.get();
        HttpResponse res = response.returnResponse();
        int statusCode = res.getStatusLine().getStatusCode();
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        if (statusCode >= 200 && statusCode < 300) {
            // success
            reporter.setSuccess(reporter.isSuccess());

            // construct summary from response
            try {
                Document responseDoc = parseResponse(res.getEntity());

                // totalInserted
                String inserted = xpath.compile("//TransactionSummary/totalInserted").evaluate(responseDoc);
                // XXX totalUpdated
                // XXX totalReplaced
                // XXX totalDeleted
                reporter.setSummary("Inserted " + inserted + " features.");
            } catch (XPathExpressionException e) {
                log.error("Error in XPath used to evaluate service response");
            } catch (ParserConfigurationException | SAXException e) {
                reporter.error(new IOMessageImpl(MessageFormat.format(
                        "Server returned status code {0}, but could not parse server response", statusCode),
                        e));
                reporter.setSuccess(false);
            }
        } else {
            // failure
            reporter.error(
                    new IOMessageImpl("Server reported failure with code " + res.getStatusLine().getStatusCode()
                            + ": " + res.getStatusLine().getReasonPhrase(), null));
            reporter.setSuccess(false);

            try {
                Document responseDoc = parseResponse(res.getEntity());
                String errorText = xpath.compile("//ExceptionText/text()").evaluate(responseDoc);
                reporter.setSummary("Request failed: " + errorText);
            } catch (XPathExpressionException e) {
                log.error("Error in XPath used to evaluate service response");
            } catch (ParserConfigurationException | SAXException e) {
                reporter.error(new IOMessageImpl("Could not parse server response", e));
                reporter.setSuccess(false);
            }
        }
    } catch (ExecutionException | InterruptedException e) {
        reporter.error(new IOMessageImpl("Failed to execute WFS-T request", e));
        reporter.setSuccess(false);
    }

    progress.end();

    return reporter;
}

From source file:org.apache.james.jmap.methods.integration.cucumber.SetMailboxesMethodStepdefs.java

@Then("^mailbox \"([^\"]*)\" contains (\\d+) messages$")
public void mailboxContainsMessages(String mailboxName, int messageCount) throws Throwable {
    String username = userStepdefs.lastConnectedUser;
    Mailbox mailbox = mainStepdefs.jmapServer.serverProbe().getMailbox("#private", username, mailboxName);
    String mailboxId = mailbox.getMailboxId().serialize();
    HttpResponse response = Request.Post(mainStepdefs.baseUri().setPath("/jmap").build())
            .addHeader("Authorization", userStepdefs.tokenByUser.get(username).serialize())
            .bodyString(/*from w w w.  ja  va 2  s .  com*/
                    "[[\"getMessageList\", {\"filter\":{\"inMailboxes\":[\"" + mailboxId + "\"]}}, \"#0\"]]",
                    ContentType.APPLICATION_JSON)
            .execute().returnResponse();

    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
    DocumentContext jsonPath = JsonPath.parse(response.getEntity().getContent());
    assertThat(jsonPath.<String>read(NAME)).isEqualTo("messageList");
    assertThat(jsonPath.<List<String>>read(ARGUMENTS + ".messageIds")).hasSize(messageCount);
}

From source file:com.qwazr.graph.test.FullTest.java

@Test
public void test200PutRandomEdges() throws IOException {
    for (int i = 0; i < VISIT_NUMBER / 100; i++) {
        int visitNodeId = RandomUtils.nextInt(VISIT_NUMBER / 2, VISIT_NUMBER);
        if (!nodeExists(visitNodeId))
            continue;
        int productNodeId = RandomUtils.nextInt(PRODUCT_NUMBER / 2, PRODUCT_NUMBER);
        HttpResponse response = Request
                .Post(BASE_URL + '/' + TEST_BASE + "/node/v" + visitNodeId + "/edge/see/p" + productNodeId)
                .connectTimeout(60000).socketTimeout(60000).execute().returnResponse();
        if (response.getStatusLine().getStatusCode() == 500)
            System.out.println(IOUtils.toString(response.getEntity().getContent()));
        Assert.assertThat(response.getStatusLine().getStatusCode(), AnyOf.anyOf(Is.is(200), Is.is(404)));
        Assert.assertThat(response.getEntity().getContentType().getValue(),
                Is.is(ContentType.APPLICATION_JSON.toString()));
    }/*from   ww  w . ja  va 2  s. co  m*/
}

From source file:com.mywork.framework.util.RemoteHttpUtil.java

/**
 * ?getpost????//from  www  .  ja v a2s .c om
 */
public static String fetchSimpleHttpResponse(String method, String contentUrl, Map<String, String> headerMap,
        Map<String, String> bodyMap) throws IOException {
    Executor executor = Executor.newInstance(httpClient);
    if (HttpGet.METHOD_NAME.equalsIgnoreCase(method)) {
        String result = contentUrl;
        StringBuilder sb = new StringBuilder();
        sb.append(contentUrl);
        if (bodyMap != null && !bodyMap.isEmpty()) {
            if (contentUrl.indexOf("?") > 0) {
                sb.append("&");
            } else {
                sb.append("?");
            }
            result = Joiner.on("&").appendTo(sb, bodyMap.entrySet()).toString();
        }

        return executor.execute(Request.Get(result)).returnContent().asString();
    }
    if (HttpPost.METHOD_NAME.equalsIgnoreCase(method)) {
        Request request = Request.Post(contentUrl);
        if (headerMap != null && !headerMap.isEmpty()) {
            for (Map.Entry<String, String> m : headerMap.entrySet()) {
                request.addHeader(m.getKey(), m.getValue());
            }
        }
        if (bodyMap != null && !bodyMap.isEmpty()) {
            Form form = Form.form();
            for (Map.Entry<String, String> m : bodyMap.entrySet()) {
                form.add(m.getKey(), m.getValue());
            }
            request.bodyForm(form.build());
        }
        return executor.execute(request).returnContent().asString();
    }
    return null;

}