Example usage for org.springframework.http HttpMethod POST

List of usage examples for org.springframework.http HttpMethod POST

Introduction

In this page you can find the example usage for org.springframework.http HttpMethod POST.

Prototype

HttpMethod POST

To view the source code for org.springframework.http HttpMethod POST.

Click Source Link

Usage

From source file:com.orange.ngsi.client.UpdateContextRequestTest.java

@Test(expected = HttpServerErrorException.class)
public void dperformPostWith500() throws Exception {

    protocolRegistry.unregisterHost(brokerUrl);

    this.mockServer.expect(requestTo(brokerUrl + "/ngsi10/updateContext")).andExpect(method(HttpMethod.POST))
            .andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR));

    ngsiClient.updateContext(brokerUrl, null, createUpdateContextTempSensor(0)).get();
}

From source file:com.orange.ngsi2.client.Ngsi2ClientTest.java

@Test
public void testAddEntity_OK() throws Exception {

    mockServer.expect(requestTo(baseURL + "/v2/entities")).andExpect(method(HttpMethod.POST))
            .andExpect(header("Content-Type", MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.id").value("DC_S1-D41")).andExpect(jsonPath("$.type").value("Room"))
            .andExpect(jsonPath("$.temperature.value").value(35.6)).andRespond(withNoContent());

    Entity e = new Entity("DC_S1-D41", "Room", Collections.singletonMap("temperature", new Attribute(35.6)));

    ngsiClient.addEntity(e).get();//  ww w  .  j a  v a  2 s  .c  om
}

From source file:com.epl.ticketws.services.QueryService.java

/**
 * This method generates the string to be signed based on the following rules:
 *
 *  - Add the request method + \n//from w w  w. j  a  va 2s .co m
 *  - Add the timestamp + \n
 *  - Add the request URI
 *  - For each request parameter ordered alphabetically:
 *    - First parameter delimiter ?
 *    - Other parameters separated by &
 *    - Name of the parameter
 *    - Add = sign
 *    - value of the parameter
 *
 * For example:
 *
 *   Given a GET request with timestamp = 1316430943576 and uri = /uri_path/ejemplo with parameters,
 *     Bc = 'Prueba1'
 *     Aa = 'Prueba2'
 *     bc = 'aPrueba3'
 *     z1 = 'prueba4'
 *
 *   The String to sign is:
 *
 *     GET\n1316430943576\n/uri_path/ejemplo?amp;Aa=Prueba2&bc=aPrueba3&Bc=Prueba1&z1=prueba4
 *
 * @param uri
 * @param method
 * @param timestamp
 * @return
 * @throws SignatureException
 */
private String getStringToSign(URI uri, String method, long timestamp, Map<String, String> params)
        throws SignatureException {

    SortedMap<String, String> sortedMap = new TreeMap<String, String>();

    // Assuming GET. It actually processes URL parameters for all Method types
    if (uri.getRawQuery() != null) {

        StringTokenizer tokenizer = null;
        try {
            tokenizer = new StringTokenizer(URLDecoder.decode(uri.getRawQuery(), UTF_8), PARAMETERS_SEPARATOR);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        while (tokenizer.hasMoreElements()) {
            String token = tokenizer.nextToken();
            sortedMap.put(token.split(PARAM_NAME_VALUE_SEPARATOR)[0].toLowerCase()
                    + token.split(PARAM_NAME_VALUE_SEPARATOR)[1], token);
        }
    }

    // If POST process parameter map
    if (method.equals(HttpMethod.POST.name())) {
        for (String key : params.keySet()) {
            String valor = params.get(key);
            sortedMap.put(key.toLowerCase() + PARAM_NAME_VALUE_SEPARATOR + valor,
                    key + PARAM_NAME_VALUE_SEPARATOR + valor);
        }

    }
    // Generating String to sign
    StringBuilder stringToSign = new StringBuilder();
    stringToSign.append(method);
    stringToSign.append(HMAC_FIELD_SEPARATOR).append(timestamp);
    stringToSign.append(HMAC_FIELD_SEPARATOR).append(uri.getPath());

    boolean firstParam = true;

    for (String param : sortedMap.values()) {
        if (firstParam) {
            stringToSign.append(URI_PARAMETERS_SEPARATOR).append(param);
            firstParam = false;
        } else {
            stringToSign.append(PARAMETERS_SEPARATOR).append(param);
        }
    }

    return stringToSign.toString();
}

From source file:com.greglturnquist.spring.social.ecobee.api.impl.ThermostatTemplateTest.java

@Test
public void testSendMessage() throws Exception {

    final HashMap<String, String> params = new HashMap<String, String>();
    params.put("text", "Greetings mate!");

    ThermostatFunction function = new ThermostatFunction(Selection.thermostats("161775386723"),
            new Function("sendMessage", params));
    final String functionStr = this.getObjectMapper().writeValueAsString(function);
    mockServer.expect(requestTo("https://api.ecobee.com/1/thermostat")).andExpect(method(HttpMethod.POST))
            .andExpect(content().string(functionStr)).andRespond(withSuccess().body(new byte[0]));

    ecobee.thermostatOperations().sendMessage("161775386723", "Greetings mate!");

    mockServer.verify();/* w w w  .  ja  v  a 2  s  .  c  om*/
}

From source file:com.embedler.moon.graphql.boot.sample.test.GenericTodoSchemaParserTest.java

@Test
public void restUploadFileUrlEncodedTest() throws IOException {

    LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    map.add("query",
            "mutation AddTodoMutationMutation{addTodoMutation(input: {clientMutationId:\"m-123\", addTodoInput:{text: \"text\"}}){ clientMutationId, todoEdge {cursor, node {text, complete}} }}");
    map.add("variables", "{}");
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);

    ResponseEntity<GraphQLServerResult> responseEntity = restTemplate.exchange(
            "http://localhost:" + port + "/graphql", HttpMethod.POST, requestEntity, GraphQLServerResult.class);

    GraphQLServerResult result = responseEntity.getBody();
    Assert.assertTrue(CollectionUtils.isEmpty(result.getErrors()));
    Assert.assertFalse(CollectionUtils.isEmpty(result.getData()));
    LOGGER.info(objectMapper.writeValueAsString(result.getData()));
}

From source file:uta.ak.CollectTweets.java

public void collectTweetsByFileList(String sinceDate, String untilDate, String tag) {
    try {//w w  w. ja  v  a2  s . c o  m
        // The factory instance is re-useable and thread safe.
        System.out.println("Start to collect tweets from :");
        Set<String> mediaList = new HashSet<String>();
        Resource res = new ClassPathResource("new-social-meida-list.txt");
        //                File stopwords=res.getFile();
        //      File stopwords=new File("/Users/zhangcong/dev/corpus/StopWordTable2.txt");
        InputStreamReader isr = new InputStreamReader(res.getInputStream());
        //            File medias=new File(path);
        //            BufferedReader mdsreader = new BufferedReader(new FileReader(medias));
        BufferedReader mdsreader = new BufferedReader(isr);
        String tempString = mdsreader.readLine();
        while ((tempString = mdsreader.readLine()) != null) {
            System.out.println(tempString.toLowerCase());
            mediaList.add(tempString.toLowerCase());
        }

        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey("LuhVZOucqdHX6x0lcVgJO6QK3")
                .setOAuthConsumerSecret("6S7zbGLvHMXDMgRXq7jRIA6QmMpdI8i5IJNpnjlB55vpHpFMpj")
                .setOAuthAccessToken("861637891-kLunD37VRY8ipAK3TVOA0YKOKxeidliTqMtNb7wf")
                .setOAuthAccessTokenSecret("vcKDxs6qHnEE8fhIJr5ktDcTbPGql5o3cNtZuztZwPYl4");
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();

        /*
        Connection con = null; //MYSQL
        Class.forName("com.mysql.jdbc.Driver").newInstance(); //MYSQL
        con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/USTTMP", "root", "root.123"); //MYSQL
        System.out.println("connection yes");
                
        String insertSQL="INSERT INTO c_rawtext(mme_lastupdate, mme_updater, title, text, tag, text_createdate) "
                        + "VALUES (NOW(), \"AK\", ?, ?, ?, ?)";
        PreparedStatement insertPS = con.prepareStatement(insertSQL);
        */

        //?usttmp??
        String restUrl = "http://192.168.0.103:8991/usttmp_textreceiver/rest/addText";

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 1);
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for (String mediastr : mediaList) {
            Query query = new Query("from:" + mediastr);
            query.setSince(sinceDate);
            query.setUntil(untilDate);
            query.setCount(100);
            query.setLang("en");

            QueryResult result = twitter.search(query);
            for (Status status : result.getTweets()) {
                System.out.println("@" + status.getUser().getScreenName() + " | "
                        + status.getCreatedAt().toString() + ":" + status.getText());
                System.out.println("Inserting the record into the table...");

                String formattedDate = format1.format(status.getCreatedAt());
                /*
                insertPS.setString (1, status.getUser().getScreenName());
                insertPS.setString (2, status.getText());
                insertPS.setString (3, tag);
                insertPS.setString (4, formattedDate);
                insertPS.addBatch();*/

                //                    if(null!=status.getText()){
                //                        break;
                //                    }

                String interfaceMsg = "<message> " + "    <title> "
                        + ((null != status.getUser().getScreenName()) ? status.getUser().getScreenName()
                                : "NO TITLE")
                        + "    </title> " + "    <text> " + StringEscapeUtils.escapeXml10(status.getText())
                        + "    </text> " + "    <textCreatetime> " + formattedDate + "    </textCreatetime> "
                        + "    <tag> " + tag + "    </tag> " + "</message>";

                //                    String restUrl="http://127.0.0.1:8991/usttmp_textreceiver/rest/addText";

                RestTemplate restTemplate = new RestTemplate();

                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.TEXT_XML);
                headers.setAccept(Arrays.asList(MediaType.TEXT_XML));
                //            headers.setContentLength();
                HttpEntity<String> entity = new HttpEntity<String>(interfaceMsg, headers);

                ResponseEntity<String> resresult = restTemplate.exchange(restUrl, HttpMethod.POST, entity,
                        String.class);

                System.out.println(resresult.getBody());
                if (resresult.getBody().contains("<result>failed</result>")) {
                    throw new RuntimeException("response message error");
                }

            }
        }

        //            System.out.println("Start to insert records...");
        //            insertPS.clearParameters();
        //            int[] results = insertPS.executeBatch();

    } catch (Exception te) {
        te.printStackTrace();
        System.out.println("Failed: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:org.appverse.web.framework.backend.frontfacade.websocket.IntegrationWebsocketTest.java

private static void loginAndSaveJsessionIdCookie(final String user, final String password,
        final HttpHeaders headersToUpdate) {

    String url = "http://localhost:" + port + "/";

    new RestTemplate().execute(url, HttpMethod.POST,

            new RequestCallback() {
                @Override//from   w w  w  .  ja v  a2 s .  c  o  m
                public void doWithRequest(ClientHttpRequest request) throws IOException {
                    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
                    map.add("username", user);
                    map.add("password", password);
                    new FormHttpMessageConverter().write(map, MediaType.APPLICATION_FORM_URLENCODED, request);
                }
            },

            new ResponseExtractor<Object>() {
                @Override
                public Object extractData(ClientHttpResponse response) throws IOException {
                    headersToUpdate.add("Cookie", response.getHeaders().getFirst("Set-Cookie"));
                    return null;
                }
            });
}

From source file:fragment.web.WorkflowControllerTest.java

@SuppressWarnings("unchecked")
@Test// ww w.j a va  2 s  . c o m
public void testRouting() throws Exception {

    logger.debug("Testing routing....");
    DispatcherTestServlet servlet = this.getServletInstance();
    Class<WorkflowController> controllerClass = (Class<WorkflowController>) controller.getClass();

    Method expected = locateMethod(controllerClass, "show", new Class[] { String.class, ModelMap.class });
    Method handler = servlet.recognize(getRequestTemplate(HttpMethod.GET, "/workflow/abcuuid"));
    Assert.assertEquals(expected, handler);

    expected = locateMethod(controllerClass, "reset", new Class[] { String.class });
    handler = servlet.recognize(getRequestTemplate(HttpMethod.POST, "/workflow/abcuuid/reset"));
    Assert.assertEquals(expected, handler);

}

From source file:com.sitewhere.rest.service.SiteWhereClient.java

@Override
public DeviceAssignment createDeviceAssignment(IDeviceAssignmentCreateRequest request)
        throws SiteWhereException {
    Map<String, String> vars = new HashMap<String, String>();
    return sendRest(getBaseUrl() + "assignments", HttpMethod.POST, request, DeviceAssignment.class, vars);
}

From source file:io.syndesis.runtime.action.DynamicActionDefinitionITCase.java

@Test
public void shouldOfferDynamicActionPropertySuggestions() {
    final HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);

    final ResponseEntity<ActionDefinition> firstResponse = http(HttpMethod.POST,
            "/api/v1/connections/" + connectionId + "/actions/" + CREATE_OR_UPDATE_ACTION_ID, null,
            ActionDefinition.class, tokenRule.validToken(), headers, HttpStatus.OK);

    final ActionDefinition firstEnrichment = new ActionDefinition.Builder()//
            .inputDataShape(new DataShape.Builder().kind("json-schema").build())
            .outputDataShape(new DataShape.Builder().kind("java")
                    .type("org.apache.camel.component.salesforce.api.dto.CreateSObjectResult").build())
            .withActionDefinitionStep("Select Salesforce object", "Select Salesforce object type to create",
                    b -> b.putProperty("sObjectName", suggestedSalesforceObjectNames))
            .withActionDefinitionStep("Select Identifier property",
                    "Select Salesforce property that will hold the uniquely identifying value of this object",
                    b -> b.putProperty("sObjectIdName", _DEFAULT_SALESFORCE_IDENTIFIER))
            .build();// www  .j a  v  a  2 s.  c o  m
    assertThat(firstResponse.getBody()).isEqualTo(firstEnrichment);

    final ResponseEntity<ActionDefinition> secondResponse = http(HttpMethod.POST,
            "/api/v1/connections/" + connectionId + "/actions/" + CREATE_OR_UPDATE_ACTION_ID,
            Collections.singletonMap("sObjectName", "Contact"), ActionDefinition.class, tokenRule.validToken(),
            headers, HttpStatus.OK);

    final ActionDefinition secondEnrichment = new ActionDefinition.Builder()//
            .outputDataShape(new DataShape.Builder().kind("java")
                    .type("org.apache.camel.component.salesforce.api.dto.CreateSObjectResult").build())
            .withActionDefinitionStep("Select Salesforce object", "Select Salesforce object type to create",
                    b -> b.putProperty("sObjectName", contactSalesforceObjectName))
            .withActionDefinitionStep("Select Identifier property",
                    "Select Salesforce property that will hold the uniquely identifying value of this object",
                    b -> b.putProperty("sObjectIdName", suggestedSalesforceIdNames))
            .build();
    final ActionDefinition secondResponseBody = secondResponse.getBody();
    assertThat(secondResponseBody).isEqualToIgnoringGivenFields(secondEnrichment, "inputDataShape");
    assertThat(secondResponseBody.getInputDataShape()).hasValueSatisfying(input -> {
        assertThat(input.getKind()).isEqualTo("json-schema");
        assertThat(input.getType()).isEqualTo("Contact");
        assertThat(input.getSpecification()).isNotEmpty();
    });
}