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:com.movilizer.mds.webservice.services.UploadFileService.java

private UploadResponse uploadSync(HttpEntity entity, Integer connectionTimeoutInMillis) {
    try {/* w ww  .j ava 2 s  . c  o  m*/
        HttpResponse response = Request.Post(documentUploadAddress.toURI())
                .addHeader(USER_AGENT_HEADER_KEY, DefaultValues.USER_AGENT)
                .connectTimeout(connectionTimeoutInMillis).body(entity).execute().returnResponse();
        int statusCode = response.getStatusLine().getStatusCode();
        if (!(HttpStatus.SC_OK <= statusCode && statusCode < HttpStatus.SC_MULTIPLE_CHOICES)) {
            String errorMessage = response.getStatusLine().getReasonPhrase();
            if (statusCode == POSSIBLE_BAD_CREDENTIALS) {
                errorMessage = errorMessage + Messages.FAILED_FILE_UPLOAD_CREDENTIALS;
            }
            throw new MovilizerWebServiceException(
                    String.format(Messages.FAILED_FILE_UPLOAD, statusCode, errorMessage));
        }
        return new UploadResponse(response.getStatusLine().getStatusCode(),
                response.getStatusLine().getReasonPhrase());
    } catch (IOException | URISyntaxException e) {
        if (logger.isErrorEnabled()) {
            logger.error(String.format(Messages.UPLOAD_ERROR, e.getMessage()));
        }
        throw new MovilizerWebServiceException(e);
    }
}

From source file:com.enitalk.opentok.CheckAvailabilityRunnable.java

@Override
@RabbitListener(queues = "youtube_check")
public void onMessage(Message msg) {
    try {/* www .  j ava  2  s.  com*/
        JsonNode event = jackson.readTree(msg.getBody());
        String ii = event.path("ii").asText();
        logger.info("Check youtube came {}", ii);

        List<String> videos = jackson.convertValue(event.path("yt"), List.class);
        List<String> parts = new ArrayList<>();
        videos.stream().forEach((String link) -> {
            parts.add(StringUtils.substringAfterLast(link, "/"));
        });

        Credential credential = flow.loadCredential("yt");
        YouTube youtube = new YouTube.Builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance(),
                credential).setApplicationName("enitalk").build();
        boolean refreshed = credential.refreshToken();
        logger.info("Yt refreshed {}", refreshed);

        HttpResponse rs = youtube.videos().list("processingDetails").setId(StringUtils.join(parts, ','))
                .executeUnparsed();
        InputStream is = rs.getContent();
        byte[] b = IOUtils.toByteArray(is);
        IOUtils.closeQuietly(is);

        JsonNode listTree = jackson.readTree(b);
        logger.info("List tree {}", listTree);

        List<JsonNode> items = listTree.path("items").findParents("id");
        long finished = items.stream().filter((JsonNode j) -> {
            return j.at("/processingDetails/processingStatus").asText().equals("succeeded");
        }).count();

        Query q = Query.query(Criteria.where("ii").is(ii));
        if (finished == parts.size()) {
            logger.info("Processing finished {}", ii);

            //send notification and email
            ObjectNode tree = (ObjectNode) jackson
                    .readTree(new ClassPathResource("emails/videoUploaded.json").getInputStream());
            tree.put("To", event.at("/student/email").asText());
            //                String text = tree.path("HtmlBody").asText() + StringUtils.join(videos, "\n");

            StringWriter writer = new StringWriter(29 * 1024);
            Template t = engine.getTemplate("video.html");
            VelocityContext context = new VelocityContext();
            context.put("video", videos.iterator().next());
            t.merge(context, writer);

            tree.put("HtmlBody", writer.toString());

            //make chat and attach it
            String chatTxt = makeChat(event);
            if (StringUtils.isNotBlank(chatTxt)) {
                ArrayNode attachments = jackson.createArrayNode();
                ObjectNode a = attachments.addObject();
                a.put("Name", "chat.txt");
                a.put("ContentType", "text/plain");
                a.put("Content", chatTxt.getBytes("UTF-8"));

                tree.set("Attachments", attachments);
            } else {
                logger.info("No chat available for {}", event.path("ii").asText());
            }

            logger.info("Sending video and chat {} to student", ii);

            org.apache.http.HttpResponse response = Request.Post("https://api.postmarkapp.com/email")
                    .addHeader("X-Postmark-Server-Token", env.getProperty("postmark.token"))
                    .bodyByteArray(jackson.writeValueAsBytes(tree), ContentType.APPLICATION_JSON).execute()
                    .returnResponse();
            byte[] r = EntityUtils.toByteArray(response.getEntity());
            JsonNode emailResp = jackson.readTree(r);

            Update u = new Update().set("video", 4);
            if (StringUtils.isNotBlank(chatTxt)) {
                u.set("chat", chatTxt);
            }

            u.set("student.uploader.rq", jackson.convertValue(tree, HashMap.class));
            u.set("student.uploader.rs", jackson.convertValue(emailResp, HashMap.class));

            tree.put("To", event.at("/teacher/email").asText());
            logger.info("Sending video and chat {} to teacher", ii);

            org.apache.http.HttpResponse response2 = Request.Post("https://api.postmarkapp.com/email")
                    .addHeader("X-Postmark-Server-Token", env.getProperty("postmark.token"))
                    .bodyByteArray(jackson.writeValueAsBytes(tree), ContentType.APPLICATION_JSON).execute()
                    .returnResponse();
            byte[] r2 = EntityUtils.toByteArray(response2.getEntity());
            JsonNode emailResp2 = jackson.readTree(r2);

            u.set("teacher.uploader.rq", jackson.convertValue(tree, HashMap.class));
            u.set("teacher.uploader.rs", jackson.convertValue(emailResp2, HashMap.class));
            u.set("f", 1);

            mongo.updateFirst(q, u, "events");

            //                JsonNode dest = event.at("/student/dest");
            //
            //                ArrayNode msgs = jackson.createArrayNode();
            //                ObjectNode o = msgs.addObject();
            //                o.set("dest", dest);
            //                ObjectNode m = jackson.createObjectNode();
            //                o.set("message", m);
            //                m.put("text", "0x1f3a5 We have uploaded your lesson to Youtube. It is available to you and the teacher only. \n"
            //                        + "Please, do not share it with anyone\n Also, we sent the video link and the text chat to your email.");
            //
            //                ArrayNode buttons = jackson.createArrayNode();
            //                m.set("buttons", buttons);
            //                m.put("buttonsPerRow", 1);
            //
            //                if (videos.size() == 1) {
            //                    botController.makeButtonHref(buttons, "Watch on Youtube", videos.get(0));
            //                } else {
            //                    AtomicInteger cc = new AtomicInteger(1);
            //                    videos.stream().forEach((String y) -> {
            //                        botController.makeButtonHref(buttons, "Watch on Youtube, part " + cc.getAndIncrement(), y);
            //                    });
            //                }
            //
            //                botController.sendMessages(msgs);
            //
            //                sendFeedback(dest, event);

        } else {
            logger.info("{} parts only finished for {}", finished, ii);
            mongo.updateFirst(q,
                    new Update().inc("check", 1).set("checkDate", new DateTime().plusMinutes(12).toDate()),
                    "events");
        }

    } catch (Exception e) {
        logger.error(ExceptionUtils.getFullStackTrace(e));
    }
}

From source file:photosharing.api.oauth.OAuth20Handler.java

/**
 * renews an access token with the user's data
 * //  w w w  .  j a  v  a  2  s.co m
 * @param oData
 *            the current OAuth 2.0 data.
 * @return {OAuth20Data} or null
 * @throws IOException
 */
public OAuth20Data renewAccessToken(OAuth20Data oData) throws IOException {
    logger.finest("renewAccessToken activated");

    Configuration config = Configuration.getInstance(null);
    String body = this.generateRenewAccessTokenRequestBody(oData.getAccessToken(), oData.getRefreshToken(),
            oData.getIssuedOn(), oData.getExpiresIn());

    // Builds the URL in a StringBuilder
    StringBuilder builder = new StringBuilder();
    builder.append(config.getValue(Configuration.BASEURL));
    builder.append(TOKENURL);

    Request post = Request.Post(builder.toString());
    post.addHeader("Content-Type", ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
    post.body(new StringEntity(body));

    /**
     * Block is executed if there is a trace
     */
    logger.info("URL Encoded body is " + body);
    logger.info("Token URL is " + builder.toString());

    /**
     * Executes with a wrapped executor
     */
    Executor exec = ExecutorUtil.getExecutor();
    Response apiResponse = exec.execute(post);
    HttpResponse hr = apiResponse.returnResponse();

    /**
     * Check the status codes and if 200, convert to String and process the
     * response body
     */
    int statusCode = hr.getStatusLine().getStatusCode();

    if (statusCode == 200) {
        InputStream in = hr.getEntity().getContent();
        String x = IOUtils.toString(in);
        oData = OAuth20Data.createInstance(x);
    } else {
        logger.warning("OAuth20Data status code " + statusCode);
    }

    return oData;
}

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

/**
 * see bug https://softinstigate.atlassian.net/browse/RH-160
 * /*from ww w  .j  a va  2  s.  co m*/
 * @throws Exception 
 */
@Test
public void testPatchIncompleteObject() throws Exception {
    Response resp;

    // *** 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

    // an incomplete details object. address and country are nullable but mandatory
    final String INCOMPLETE_OBJ = "{\"details\": {\"city\": \"a city\"}}";

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

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

From source file:org.biopax.paxtools.client.BiopaxValidatorClient.java

private String location(final String url) throws IOException {
    String location = url; //initially the same
    // discover actual location, avoid going in circles:
    int i = 0;//from  w  w  w  .ja v  a 2s . c  om
    for (String loc = url; loc != null && i < 5; i++) {
        //do POST for location (Location header present if there's a 301/302/307 redirect on the way)
        loc = Request.Post(loc).execute().handleResponse(new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse httpResponse)
                    throws ClientProtocolException, IOException {
                Header header = httpResponse.getLastHeader("Location");
                //                     System.out.println("header=" + header);
                return (header != null) ? header.getValue().trim() : null;
            }
        });

        if (loc != null) {
            location = loc;
            log.info("BioPAX Validator location: " + loc);
        }
    }

    return location;
}

From source file:org.mule.test.construct.FlowRefTestCase.java

@Test
public void nonBlockingFlowRefToQueuedAsyncFlow() throws Exception {
    Response response = Request
            .Post(String.format("http://localhost:%s/%s", port.getNumber(),
                    "nonBlockingFlowRefToQueuedAsyncFlow"))
            .connectTimeout(RECEIVE_TIMEOUT).bodyString(TEST_MESSAGE, ContentType.TEXT_PLAIN).execute();
    HttpResponse httpResponse = response.returnResponse();
    assertThat(httpResponse.getStatusLine().getStatusCode(), is(500));
    assertThat(IOUtils.toString(httpResponse.getEntity().getContent()),
            is("Unable to process a synchronous event asynchronously."));
}

From source file:com.ctrip.infosec.rule.resource.DataProxyTest.java

@Test
public void testRestUerProfile() {
    String serviceName = "UserProfileService";
    String operationName = "DataQuery";
    Map params = new HashMap();
    List tagContents = new ArrayList();
    tagContents.add("QIANBAO_AUTH_STATUS");
    params.put("uid", "3004975915");
    params.put("tagNames", tagContents);

    String urlPrefix = "http://ws.userprofile.infosec.ctripcorp.com/userprofilews";
    int queryTimeout = 500;
    DataProxyRequest request = new DataProxyRequest();
    request.setServiceName(serviceName);
    request.setOperationName(operationName);
    request.setParams(params);/*w w  w. ja v  a2 s .  c o m*/
    String responseTxt = null;
    try {
        responseTxt = Request.Post(urlPrefix + "/rest/dataproxy/query")
                .body(new StringEntity(Utils.JSON.toJSONString(request), ContentType.APPLICATION_JSON))
                .connectTimeout(queryTimeout).socketTimeout(queryTimeout).execute().returnContent().asString();
    } catch (IOException e) {
        e.printStackTrace();
    }
    DataProxyResponse response = Utils.JSON.parseObject(responseTxt, DataProxyResponse.class);

    Map newResult = null;
    if (request.getServiceName().equals("UserProfileService")) {
        newResult = parseProfileResult(response.getResult());
    } else {
        newResult = response.getResult();
    }
    System.out.println(JSON.toJSONString(newResult));
}

From source file:org.obm.sync.client.impl.AbstractClientImpl.java

private Request getPostRequest(AccessToken at, String action) throws LocatorClientException {
    return Request.Post(getBackendUrl(at.getUserWithDomain()) + action);
}

From source file:org.kie.smoke.wb.util.RestUtil.java

public static <T> T postEntity(URL deploymentUrl, String relativeUrl, String mediaType, int status, String user,
        String password, Object entity, Class<T>... responseTypes) {
    String uriStr = createBaseUriString(deploymentUrl, relativeUrl);

    ResponseHandler<T> rh = createResponseHandler(mediaType, status, responseTypes);

    String entityStr = ((AbstractResponseHandler) rh).serialize(entity);
    HttpEntity bodyEntity = null;// ww  w .j  av  a2 s  .  c  om
    try {
        bodyEntity = new StringEntity(entityStr);
    } catch (UnsupportedEncodingException uee) {
        logAndFail("Unable to encode serialized " + entity.getClass().getSimpleName() + " entity", uee);
    }

    // @formatter:off
    Request request = Request.Post(uriStr).body(bodyEntity)
            .addHeader(HttpHeaders.CONTENT_TYPE, mediaType.toString())
            .addHeader(HttpHeaders.ACCEPT, mediaType.toString())
            .addHeader(HttpHeaders.AUTHORIZATION, basicAuthenticationHeader(user, password));
    // @formatter:on

    Response resp = null;
    try {
        logOp("POST", entity, uriStr);
        resp = request.execute();
    } catch (Exception e) {
        logAndFail("[GET] " + uriStr, e);
    }

    try {
        return resp.handleResponse(rh);
    } catch (Exception e) {
        logAndFail("Failed retrieving response from [GET] " + uriStr, e);
    }

    // never happens
    return null;
}

From source file:com.jaspersoft.ireport.jasperserver.ws.http.JSSCommonsHTTPSender.java

/**
 * invoke creates a socket connection, sends the request SOAP message and
 * then reads the response SOAP message back from the SOAP server
 *
 * @param msgContext//from  w  ww. j  a v a2s .  com
 *            the messsage context
 *
 * @throws AxisFault
 */
public void invoke(final MessageContext msgContext) throws AxisFault {
    if (log.isDebugEnabled())
        log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke"));
    Request req = null;
    Response response = null;
    try {
        if (exec == null) {
            targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));
            String userID = msgContext.getUsername();
            String passwd = msgContext.getPassword();
            // if UserID is not part of the context, but is in the URL, use
            // the one in the URL.
            if ((userID == null) && (targetURL.getUserInfo() != null)) {
                String info = targetURL.getUserInfo();
                int sep = info.indexOf(':');

                if ((sep >= 0) && (sep + 1 < info.length())) {
                    userID = info.substring(0, sep);
                    passwd = info.substring(sep + 1);
                } else
                    userID = info;
            }
            Credentials cred = new UsernamePasswordCredentials(userID, passwd);
            if (userID != null) {
                // if the username is in the form "user\domain"
                // then use NTCredentials instead.
                int domainIndex = userID.indexOf("\\");
                if (domainIndex > 0) {
                    String domain = userID.substring(0, domainIndex);
                    if (userID.length() > domainIndex + 1) {
                        String user = userID.substring(domainIndex + 1);
                        cred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain);
                    }
                }
            }
            HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy() {

                public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response,
                        final HttpContext context) throws ProtocolException {
                    URI uri = getLocationURI(request, response, context);
                    String method = request.getRequestLine().getMethod();
                    if (method.equalsIgnoreCase(HttpHead.METHOD_NAME))
                        return new HttpHead(uri);
                    else if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
                        HttpPost httpPost = new HttpPost(uri);
                        httpPost.addHeader(request.getFirstHeader("Authorization"));
                        httpPost.addHeader(request.getFirstHeader("SOAPAction"));
                        httpPost.addHeader(request.getFirstHeader("Content-Type"));
                        httpPost.addHeader(request.getFirstHeader("User-Agent"));
                        httpPost.addHeader(request.getFirstHeader("SOAPAction"));
                        if (request instanceof HttpEntityEnclosingRequest)
                            httpPost.setEntity(((HttpEntityEnclosingRequest) request).getEntity());
                        return httpPost;
                    } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
                        return new HttpGet(uri);
                    } else {
                        throw new IllegalStateException(
                                "Redirect called on un-redirectable http method: " + method);
                    }
                }
            }).build();

            exec = Executor.newInstance(httpClient);
            HttpHost host = new HttpHost(targetURL.getHost(), targetURL.getPort(), targetURL.getProtocol());
            exec.auth(host, cred);
            exec.authPreemptive(host);
            HttpUtils.setupProxy(exec, targetURL.toURI());
        }
        boolean posting = true;

        // If we're SOAP 1.2, allow the web method to be set from the
        // MessageContext.
        if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
            if (webMethod != null)
                posting = webMethod.equals(HTTPConstants.HEADER_POST);
        }
        HttpHost proxy = HttpUtils.getUnauthProxy(exec, targetURL.toURI());
        if (posting) {
            req = Request.Post(targetURL.toString());
            if (proxy != null)
                req.viaProxy(proxy);
            Message reqMessage = msgContext.getRequestMessage();

            addContextInfo(req, msgContext, targetURL);
            Iterator<?> it = reqMessage.getAttachments();
            if (it.hasNext()) {
                ByteArrayOutputStream bos = null;
                try {
                    bos = new ByteArrayOutputStream();
                    reqMessage.writeTo(bos);
                    req.body(new ByteArrayEntity(bos.toByteArray()));
                } finally {
                    FileUtils.closeStream(bos);
                }
            } else
                req.body(new StringEntity(reqMessage.getSOAPPartAsString()));

        } else {
            req = Request.Get(targetURL.toString());
            if (proxy != null)
                req.viaProxy(proxy);
            addContextInfo(req, msgContext, targetURL);
        }

        response = exec.execute(req);
        response.handleResponse(new ResponseHandler<String>() {

            public String handleResponse(final HttpResponse response) throws IOException {
                HttpEntity en = response.getEntity();
                InputStream in = null;
                try {
                    StatusLine statusLine = response.getStatusLine();
                    int returnCode = statusLine.getStatusCode();
                    String contentType = en.getContentType().getValue();

                    in = new BufferedHttpEntity(en).getContent();
                    // String str = IOUtils.toString(in);
                    if (returnCode > 199 && returnCode < 300) {
                        // SOAP return is OK - so fall through
                    } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
                        // For now, if we're SOAP 1.2, fall
                        // through, since the range of
                        // valid result codes is much greater
                    } else if (contentType != null && !contentType.equals("text/html")
                            && ((returnCode > 499) && (returnCode < 600))) {
                        // SOAP Fault should be in here - so
                        // fall through
                    } else {
                        String statusMessage = statusLine.getReasonPhrase();
                        AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null,
                                null);
                        fault.setFaultDetailString(
                                Messages.getMessage("return01", "" + returnCode, IOUtils.toString(in)));
                        fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE,
                                Integer.toString(returnCode));
                        throw fault;
                    }
                    Header contentEncoding = response.getFirstHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
                    if (contentEncoding != null) {
                        if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP))
                            in = new GZIPInputStream(in);
                        else {
                            AxisFault fault = new AxisFault("HTTP", "unsupported content-encoding of '"
                                    + contentEncoding.getValue() + "' found", null, null);
                            throw fault;
                        }

                    }

                    // Transfer HTTP headers of HTTP message
                    // to MIME headers of SOAP
                    // message
                    MimeHeaders mh = new MimeHeaders();
                    for (Header h : response.getAllHeaders())
                        mh.addHeader(h.getName(), h.getValue());
                    Message outMsg = new Message(in, false, mh);

                    outMsg.setMessageType(Message.RESPONSE);
                    msgContext.setResponseMessage(outMsg);
                    if (log.isDebugEnabled()) {
                        log.debug("\n" + Messages.getMessage("xmlRecd00"));
                        log.debug("-----------------------------------------------");
                        log.debug(outMsg.getSOAPPartAsString());
                    }
                } finally {
                    FileUtils.closeStream(in);
                }
                return "";
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
        log.debug(e);
        throw AxisFault.makeFault(e);
    }
    if (log.isDebugEnabled())
        log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke"));
}