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:org.restheart.test.integration.JsonPathConditionsCheckerIT.java

@Test
public void testPostIncompleteDataDotNotation() throws Exception {
    Response resp;/*w w w.jav a  2 s.  com*/

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

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

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

From source file:net.bluemix.droneselfie.UploadPictureServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String id = request.getParameter("id");
    if (id == null)
        return;//www .  j  a  va  2s .  c  o m
    if (id.equals(""))
        return;

    InputStream inputStream = null;
    Part filePart = request.getPart("my_file");
    if (filePart != null) {
        inputStream = filePart.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        org.apache.commons.io.IOUtils.copy(inputStream, baos);
        byte[] bytes = baos.toByteArray();
        ByteArrayInputStream bistream = new ByteArrayInputStream(bytes);
        String contentType = "image/png";

        java.util.Date date = new java.util.Date();
        String uniqueId = String.valueOf(date.getTime());
        AttachmentDoc document = new AttachmentDoc(id, AttachmentDoc.TYPE_FULL_PICTURE, date);
        DatabaseUtilities.getSingleton().getDB().create(document.getId(), document);
        document = DatabaseUtilities.getSingleton().getDB().get(AttachmentDoc.class, id);
        AttachmentInputStream ais = new AttachmentInputStream(id, bistream, contentType);
        DatabaseUtilities.getSingleton().getDB().createAttachment(id, document.getRevision(), ais);

        javax.websocket.Session ssession;
        ssession = net.bluemix.droneselfie.SocketEndpoint.currentSession;
        if (ssession != null) {
            for (Session session : ssession.getOpenSessions()) {
                try {
                    if (session.isOpen()) {
                        session.getBasicRemote().sendText("fpic?id=" + id);
                    }
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }

        String alchemyUrl = "";
        String apiKey = ConfigUtilities.getSingleton().getAlchemyAPIKey();
        String bluemixAppName = ConfigUtilities.getSingleton().getBluemixAppName();

        /*
        if (bluemixAppName == null) {
           String host = request.getServerName();
           alchemyUrl = "http://access.alchemyapi.com/calls/url/URLGetRankedImageFaceTags?url=http://" + host +"/pic?id="
          + id + "&apikey=" + apiKey + "&outputMode=json";
        }
        else {
           alchemyUrl = "http://access.alchemyapi.com/calls/url/URLGetRankedImageFaceTags?url=http://" + bluemixAppName +".mybluemix.net/pic?id="
          + id + "&apikey=" + apiKey + "&outputMode=json";
        }*/

        alchemyUrl = "http://access.alchemyapi.com/calls/url/URLGetRankedImageFaceTags?url=http://ar-drone-selfie.mybluemix.net/pic?id="
                + id + "&apikey=1657f33d25d39ff6d226c5547db6190ea8d5af76&outputMode=json";
        System.out.println("alchemyURL: " + alchemyUrl);
        org.apache.http.client.fluent.Request req = Request.Post(alchemyUrl);
        org.apache.http.client.fluent.Response res = req.execute();

        String output = res.returnContent().asString();
        Gson gson = new Gson();

        AlchemyResponse alchemyResponse = gson.fromJson(output, AlchemyResponse.class);

        if (alchemyResponse != null) {
            List<ImageFace> faces = alchemyResponse.getImageFaces();
            if (faces != null) {
                for (int i = 0; i < faces.size(); i++) {
                    ImageFace face = faces.get(i);
                    String sH = face.getHeight();
                    String sPX = face.getPositionX();
                    String sPY = face.getPositionY();
                    String sW = face.getWidth();
                    int height = Integer.parseInt(sH);
                    int positionX = Integer.parseInt(sPX);
                    int positionY = Integer.parseInt(sPY);
                    int width = Integer.parseInt(sW);

                    int fullPictureWidth = 640;
                    int fullPictureHeight = 360;
                    positionX = positionX - width / 2;
                    positionY = positionY - height / 2;
                    height = height * 2;
                    width = width * 2;
                    if (positionX < 0)
                        positionX = 0;
                    if (positionY < 0)
                        positionY = 0;
                    if (positionX + width > fullPictureWidth)
                        width = width - (fullPictureWidth - positionX);
                    if (positionY + height > fullPictureHeight)
                        height = height - (fullPictureHeight - positionY);

                    bistream = new ByteArrayInputStream(bytes);
                    javaxt.io.Image image = new javaxt.io.Image(bistream);
                    image.crop(positionX, positionY, width, height);
                    byte[] croppedImage = image.getByteArray();

                    ByteArrayInputStream bis = new ByteArrayInputStream(croppedImage);

                    date = new java.util.Date();
                    uniqueId = String.valueOf(date.getTime());
                    document = new AttachmentDoc(uniqueId, AttachmentDoc.TYPE_PORTRAIT, date);
                    DatabaseUtilities.getSingleton().getDB().create(document.getId(), document);
                    document = DatabaseUtilities.getSingleton().getDB().get(AttachmentDoc.class, uniqueId);

                    ais = new AttachmentInputStream(uniqueId, bis, contentType);
                    DatabaseUtilities.getSingleton().getDB().createAttachment(uniqueId, document.getRevision(),
                            ais);

                    ssession = net.bluemix.droneselfie.SocketEndpoint.currentSession;
                    if (ssession != null) {
                        for (Session session : ssession.getOpenSessions()) {
                            try {
                                if (session.isOpen()) {
                                    /*
                                     * In addition to portrait url why don't we send a few meta back to client
                                     */
                                    ImageTag tag = face.getImageTag();
                                    tag.setUrl("pic?id=" + uniqueId);
                                    session.getBasicRemote().sendText(tag.toString());
                                }
                            } catch (IOException ioe) {
                                ioe.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:com.cognifide.aet.common.TestSuiteRunner.java

private SuiteExecutionResult startSuiteExecution(File testSuite) throws IOException {
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().addBinaryBody("suite", testSuite,
            ContentType.APPLICATION_XML, testSuite.getName());
    if (domain != null) {
        entityBuilder.addTextBody("domain", domain);
    }/*from   w ww .  j  a  va  2 s . c o m*/
    HttpEntity entity = entityBuilder.build();
    return Request.Post(getSuiteUrl()).body(entity).connectTimeout(timeout).socketTimeout(timeout).execute()
            .handleResponse(suiteExecutionResponseHandler);
}

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

/**
 * gets an access token based on the code
 * /*from   w w  w.java 2  s .  c om*/
 * @param code
 *            - the >254 character code representing temporary credentials
 * @return the OAuth 20 configuration for the user requesting
 * @throws IOException
 */
public OAuth20Data getAccessToken(String code) throws IOException {
    logger.info("getAccessToken activated");
    OAuth20Data oData = null;

    Configuration config = Configuration.getInstance(null);
    String body = this.generateAccessTokenRequestBody(config.getValue(Configuration.CLIENTID),
            config.getValue(Configuration.CLIENTSECRET), config.getValue(Configuration.CALLBACKURL), code);

    // 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:com.ctrip.infosec.rule.resource.DataProxy.java

/**
 *
 * @param key tag?//from  ww w .  j a v a 2s.c  o m
 * @param values tag??tag?map example:key:uid-123
 * values:RECENT_IP-112.23.32.36 RECENT_IPAREA-
 * -------------------------------------
 *
 * ? temp = new
 * HashMap();temp.put("RECENT_IP","112.23.32.36");temp.put("RECENT_IPAREA","");
 * addTagData("123",temp)
 * @return ?true?false
 */
public static boolean addTagData(String key, Map<String, String> values) {
    boolean flag = false;
    check();
    beforeInvoke("DataProxy.addTagData");
    try {
        List<DataProxyRequest> requests = new ArrayList<>();
        DataProxyRequest request = new DataProxyRequest();
        request.setServiceName("CommonService");
        request.setOperationName("addData");

        Map params = new HashMap<String, String>();
        params.put("tableName", "UserProfileInfo");
        params.put("pkValue", key.trim());
        params.put("storageType", "1");
        params.put("values", values);
        request.setParams(params);
        requests.add(request);
        String requestText = JSON.toPrettyJSONString(requests);
        String responseText = Request.Post(urlPrefix + "/rest/dataproxy/dataprocess")
                .bodyString(requestText, ContentType.APPLICATION_JSON).execute().returnContent().asString();
        Map result = JSON.parseObject(responseText, Map.class);
        if (result.get("rtnCode").equals("0")) {
            flag = true;
        } else {
            flag = false;
            logger.warn("?:" + JSON.toPrettyJSONString(values) + "\t" + "userProfile!");
        }
    } catch (Exception ex) {
        fault("DataProxy.addTagData");
        logger.error(Contexts.getLogPrefix() + "invoke DataProxy.addTagData fault.", ex);
    } finally {
        afterInvoke("DataProxy.addTagData");
    }
    return flag;
}

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

@Test
public void test110PutVisitNodes() throws IOException {
    for (int i = 0; i < VISIT_NUMBER; i += 100) {
        Map<String, GraphNode> nodeMap = new LinkedHashMap<String, GraphNode>();
        for (int k = 0; k < 100; k++) {
            GraphNode node = new GraphNode();
            node.properties = new HashMap<String, Object>();
            node.properties.put("type", "visit");
            node.properties.put("user", "user" + RandomUtils.nextInt(0, 100));
            node.properties.put("date", "201501" + RandomUtils.nextInt(10, 31));
            node.edges = new HashMap<String, Set<Object>>();
            int seePages = RandomUtils.nextInt(3, 12);
            Set<Object> set = new TreeSet<Object>();
            for (int j = 0; j < seePages; j++)
                set.add("p" + RandomUtils.nextInt(0, PRODUCT_NUMBER / 2));
            node.edges.put("see", set);
            if (RandomUtils.nextInt(0, 10) == 0) {
                int buyItems = RandomUtils.nextInt(1, 5);
                set = new TreeSet<Object>();
                for (int j = 0; j < buyItems; j++)
                    set.add("p" + RandomUtils.nextInt(0, PRODUCT_NUMBER / 2));
                node.edges.put("buy", set);
            }//from ww  w .  ja  v a2  s.  c o m
            nodeMap.put("v" + (i + k), node);
        }
        HttpResponse response = Request.Post(BASE_URL + '/' + TEST_BASE + "/node")
                .bodyString(JsonMapper.MAPPER.writeValueAsString(nodeMap), ContentType.APPLICATION_JSON)
                .connectTimeout(60000).socketTimeout(60000).execute().returnResponse();
        Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    }
}

From source file:com.github.piotrkot.resources.CompilerResourceTest.java

/**
 * Appending logs should add them on the server.
 * @throws Exception If something fails.
 *//* w ww. ja v  a  2 s. c  o m*/
@Test
public void testAppendLogs() throws Exception {
    final String req = "log";
    final String mesg = "message";
    final String uri = String.format("http://localhost:%d/compiler/logs/0",
            CompilerResourceTest.APP_RULE.getLocalPort());
    Assert.assertTrue(HTTP_RESP_OK.contains(
            Request.Delete(uri).setHeader(OK_AUTH).execute().returnResponse().getStatusLine().getStatusCode()));
    Assert.assertTrue(HTTP_RESP_OK
            .contains(Request.Post(uri).setHeader(OK_AUTH).bodyForm(Form.form().add(req, mesg).build())
                    .execute().returnResponse().getStatusLine().getStatusCode()));
    Assert.assertTrue(HTTP_RESP_OK
            .contains(Request.Post(uri).setHeader(OK_AUTH).bodyForm(Form.form().add(req, mesg).build())
                    .execute().returnResponse().getStatusLine().getStatusCode()));
    Assert.assertEquals(Joiner.on(System.lineSeparator()).join(mesg, mesg),
            Request.Get(uri).setHeader(OK_AUTH).execute().returnContent().asString());
}

From source file:com.movilizer.mds.webservice.services.MafManagementService.java

private HttpEntity performRequest(MafRequest request) {
    try {//  w  w w . j a v a 2s. co  m
        HttpResponse response = Request.Post(request.getResourceURI(mafBaseAddress.toURI()))
                .addHeader(USER_AGENT_HEADER_KEY, DefaultValues.USER_AGENT)
                .connectTimeout(defaultConnectionTimeoutInMillis)
                .body(new StringEntity(gson.toJson(request), ContentType.APPLICATION_JSON)).execute()
                .returnResponse();
        int statusCode = response.getStatusLine().getStatusCode();
        if (!(HttpStatus.SC_OK <= statusCode && statusCode < HttpStatus.SC_MULTIPLE_CHOICES)) {
            String errorMessage = response.getStatusLine().getReasonPhrase();
            throw new MovilizerWebServiceException(
                    String.format(Messages.MAF_UPLOAD_FAILED_WITH_CODE, statusCode, errorMessage));
        }
        return response.getEntity();
    } catch (IOException | URISyntaxException e) {
        throw new MovilizerWebServiceException(e);
    }
}

From source file:org.mule.module.http.functional.proxy.HttpProxyTemplateTestCase.java

@Test
public void proxyMethod() throws Exception {
    handlerExtender = new EchoRequestHandlerExtender() {
        @Override/*w w  w  .  java 2 s .c  o m*/
        protected String selectRequestPartToReturn(org.eclipse.jetty.server.Request baseRequest) {
            return baseRequest.getMethod();
        }
    };
    assertRequestOk(getProxyUrl("test?parameterName=parameterValue"), "GET");

    Response response = Request.Post(getProxyUrl("test?parameterName=parameterValue"))
            .bodyString("Some Text", ContentType.DEFAULT_TEXT).connectTimeout(RECEIVE_TIMEOUT).execute();
    HttpResponse httpResponse = response.returnResponse();
    assertThat(httpResponse.getStatusLine().getStatusCode(), is(200));
    assertThat(IOUtils.toString(httpResponse.getEntity().getContent()), is("POST"));
}

From source file:org.mule.module.http.functional.listener.HttpListenerWorkerThreadingProfileTestCase.java

@Test
public void hitDifferentRequestConfigAndRun() throws Exception {
    String url = String.format("http://localhost:%s", listenPort1.getNumber());
    sendRequestUntilNoMoreWorkers("maxActiveThreadsConfigFlow", url, CUSTOM_MAX_THREADS_ACTIVE);
    try {//from www.  java 2  s  .  c  o m
        url = String.format("http://localhost:%s", listenPort3.getNumber());
        final Response response = httpClientExecutor.execute(Request.Post(url)
                .bodyByteArray(TEST_MESSAGE.getBytes()).connectTimeout(100).socketTimeout(100));
        final HttpResponse httpResponse = response.returnResponse();
        assertThat(httpResponse.getStatusLine().getStatusCode(), is(OK.getStatusCode()));
        assertThat(IOUtils.toString(httpResponse.getEntity().getContent()), is(TEST_MESSAGE));
    } finally {
        waitingLatch.release();
    }
}