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.SubscribeContextRequestTest.java

@Test
public void subscribeContextRequestOK() throws Exception {
    // Ensure host is not registering (will use JSON)
    ngsiClient.protocolRegistry.unregisterHost(baseUrl);

    String responseBody = json(jsonConverter, createSubscribeContextResponseTemperature());

    this.mockServer.expect(requestTo(baseUrl + "/ngsi10/subscribeContext")).andExpect(method(HttpMethod.POST))
            .andExpect(header("Content-Type", MediaType.APPLICATION_JSON_VALUE))
            .andExpect(header("Accept", MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.entities[*]", hasSize(1)))
            .andExpect(jsonPath("$.entities[0].id").value("Room1"))
            .andExpect(jsonPath("$.entities[0].type").value("Room"))
            .andExpect(jsonPath("$.entities[0].isPattern").value("false"))
            .andExpect(jsonPath("$.attributes[*]", hasSize(1)))
            .andExpect(jsonPath("$.attributes[0]").value("temperature"))
            .andExpect(jsonPath("$.reference").value("http://localhost:1028/accumulate"))
            .andExpect(jsonPath("$.duration").value("P1M")).andExpect(jsonPath("$.throttling").value("PT1S"))
            .andExpect(jsonPath("$.restriction.attributeExpression").value("xpath/expression"))
            .andExpect(jsonPath("$.restriction.scopes[0].type").value("type"))
            .andExpect(jsonPath("$.restriction.scopes[0].value").value("value"))
            .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON));

    SubscribeContextResponse response = ngsiClient
            .subscribeContext(baseUrl, null, createSubscribeContextTemperature()).get();
    this.mockServer.verify();

    Assert.assertNull(response.getSubscribeError());
    Assert.assertEquals("12345678", response.getSubscribeResponse().getSubscriptionId());
    Assert.assertEquals("P1M", response.getSubscribeResponse().getDuration());
}

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

@Test
public void unsubscribeContextRequestOK() throws Exception {

    ngsiClient.protocolRegistry.unregisterHost(baseUrl);
    String responseBody = json(jsonConverter,
            createUnsubscribeContextResponse(CodeEnum.CODE_200, subscriptionID));

    this.mockServer.expect(requestTo(baseUrl + "/ngsi10/unsubscribeContext")).andExpect(method(HttpMethod.POST))
            .andExpect(header("Content-Type", MediaType.APPLICATION_JSON_VALUE))
            .andExpect(header("Accept", MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.subscriptionId", hasToString(subscriptionID)))
            .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON));

    UnsubscribeContextResponse response = ngsiClient.unsubscribeContext(baseUrl, null, subscriptionID).get();

    this.mockServer.verify();

    Assert.assertEquals(subscriptionID, response.getSubscriptionId());
    Assert.assertEquals(CodeEnum.CODE_200.getLabel(), response.getStatusCode().getCode());
}

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

@Test
public void updateContextSubscriptionRequestOK() throws Exception {

    ngsiClient.protocolRegistry.unregisterHost(baseUrl);
    String responseBody = json(jsonConverter, createUpdateContextSubscriptionResponseTemperature());

    this.mockServer.expect(requestTo(baseUrl + "/ngsi10/updateContextSubscription"))
            .andExpect(method(HttpMethod.POST))
            .andExpect(header("Content-Type", MediaType.APPLICATION_JSON_VALUE))
            .andExpect(header("Accept", MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.subscriptionId").value("12345678"))
            .andExpect(jsonPath("$.duration").value("P1M")).andExpect(jsonPath("$.throttling").value("PT1S"))
            .andExpect(jsonPath("$.restriction.attributeExpression").value("xpath/expression"))
            .andExpect(jsonPath("$.restriction.scopes[0].type").value("type"))
            .andExpect(jsonPath("$.restriction.scopes[0].value").value("value"))
            .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON));

    UpdateContextSubscriptionResponse response = ngsiClient
            .updateContextSubscription(baseUrl, null, createUpdateContextSubscriptionTemperature()).get();
    this.mockServer.verify();

    Assert.assertNull(response.getSubscribeError());
    Assert.assertEquals("12345678", response.getSubscribeResponse().getSubscriptionId());
    Assert.assertEquals("P1M", response.getSubscribeResponse().getDuration());
}

From source file:org.cloudfoundry.identity.uaa.login.test.TestClient.java

private void restfulCreate(String adminAccessToken, String json, String url) {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Bearer " + adminAccessToken);
    headers.add("Accept", "application/json");
    headers.add("Content-Type", "application/json");

    HttpEntity<String> requestEntity = new HttpEntity<String>(json, headers);
    ResponseEntity<Void> exchange = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Void.class);
    Assert.assertEquals(HttpStatus.CREATED, exchange.getStatusCode());
}

From source file:org.appverse.web.framework.backend.test.util.frontfacade.mvc.tests.predefined.BasicAuthEndPointsDisabledPredefinedTests.java

@Test
public void basicAuthenticationServiceTest() throws Exception {
    int port = context.getEmbeddedServletContainer().getPort();

    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization",
            "Basic " + new String(Base64.encode((getUsername() + ":" + getPassword()).getBytes("UTF-8"))));
    HttpEntity<String> entity = new HttpEntity<String>("headers", headers);

    ResponseEntity<AuthorizationData> responseEntity = restTemplate.exchange(
            "http://localhost:" + port + baseApiPath + basicAuthenticationEndpointPath, HttpMethod.POST, entity,
            AuthorizationData.class);
    // When an enpoint is disabled, "405 - METHOD NOT ALLOWED" is returned
    assertEquals(HttpStatus.METHOD_NOT_ALLOWED, responseEntity.getStatusCode());
}

From source file:com.marklogic.mgmt.admin.AdminManager.java

public void installAdmin(String username, String password) {
    final URI uri = adminConfig.buildUri("/admin/v1/instance-admin");

    String json = null;/*  w  ww . j a v  a  2 s.  co  m*/
    if (username != null && password != null) {
        json = format("{\"admin-username\":\"%s\", \"admin-password\":\"%s\", \"realm\":\"public\"}", username,
                password);
    } else {
        json = "{}";
    }
    final String payload = json;

    logger.info("Installing admin user at: " + uri);
    invokeActionRequiringRestart(new ActionRequiringRestart() {
        @Override
        public boolean execute() {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> entity = new HttpEntity<String>(payload, headers);
            try {
                ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.POST, entity,
                        String.class);
                logger.info("Admin installation response: " + response);
                // According to http://docs.marklogic.com/REST/POST/admin/v1/init, a 202 is sent back in the event a
                // restart is needed. A 400 or 401 will be thrown as an error by RestTemplate.
                return HttpStatus.ACCEPTED.equals(response.getStatusCode());
            } catch (HttpClientErrorException hcee) {
                if (HttpStatus.BAD_REQUEST.equals(hcee.getStatusCode())) {
                    logger.warn("Caught 400 error, assuming admin user already installed; response body: "
                            + hcee.getResponseBodyAsString());
                    return false;
                }
                throw hcee;
            }
        }
    });
}

From source file:io.syndesis.runtime.action.DynamicActionSqlStoredITCase.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/io.syndesis:sql-stored-connector:latest", null,
            ActionDefinition.class, tokenRule.validToken(), headers, HttpStatus.OK);

    ConfigurationProperty procedureNames = firstResponse.getBody().getPropertyDefinitionSteps().iterator()
            .next().getProperties().get("procedureName");
    assertThat(procedureNames.getEnum().size() == 2);
    assertThat(procedureNames.getEnum().iterator().next().getLabel().startsWith("DEMO_ADD"));

    final ResponseEntity<ActionDefinition> secondResponse = http(HttpMethod.POST,
            "/api/v1/connections/" + connectionId + "/actions/io.syndesis:sql-stored-connector:latest",
            Collections.singletonMap("procedureName", "DEMO_ADD"), ActionDefinition.class,
            tokenRule.validToken(), headers, HttpStatus.OK);

    final Map<String, ConfigurationProperty> secondRequestProperties = secondResponse.getBody()
            .getPropertyDefinitionSteps().get(0).getProperties();
    assertThat(secondRequestProperties.get("template").getDefaultValue())
            .isEqualTo("DEMO_ADD(INTEGER ${body[A]}, INTEGER ${body[B]}, INTEGER ${body[C]})");
}

From source file:org.echocat.marquardt.example.ServiceLoginIntegrationTest.java

private void whenAccessingAdminResourceOnService() throws IOException {
    getClient().sendSignedPayloadTo(baseUriOfApp() + "/exampleservice/adminResource", HttpMethod.POST.name(),
            null, Void.class, _certificate);
}

From source file:com.pepaproch.gtswsdlclient.AddresCheckImplTest.java

/**
 * Test of checkAddres method, of class AddresCheckImpl.
 *//*from  w w  w  .  j a v  a  2  s .com*/
@Test
public void testCheckAddresAuthenticated() {

    System.out.println("checkAddres");
    AddressQuery addrQuery = new AddressQuery();

    RestTemplate restTemplate = getRestTemplate();
    RestTemplate authRestTemplate = getRestTemplate();
    AuthTokenProviderImpl authTokenProvider = new AuthTokenProviderImpl(BASE_URL, "test", "test",
            authRestTemplate, 1);
    AuthHeaderInterceptor securityTokenInterceptor = new AuthHeaderInterceptor(authTokenProvider);
    List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
    if (interceptors == null) {
        interceptors = new ArrayList<>();
        restTemplate.setInterceptors(interceptors);
    }
    interceptors.add(securityTokenInterceptor);
    RestContext restContext = Mockito.mock(RestContext.class);
    when(restContext.getRestTemplate()).thenReturn(restTemplate);
    when(restContext.getBASE_URL()).thenReturn(BASE_URL);

    //first request
    AddressResponse expResult = null;
    mockServer = MockRestServiceServer.createServer(restTemplate);
    this.mockServer.expect(requestTo(BASE_URL + AddresCheckImpl.ADDR_CHECK_PATH))
            .andExpect(method(HttpMethod.GET))
            .andRespond(withSuccess(CHECK_ADDR_RESPONSE_BODY, MediaType.APPLICATION_JSON));

    //auth token is not set so it will call remote for acces token
    mockServerAuthProvider = MockRestServiceServer.createServer(authRestTemplate);
    String authResponseBody = "{\"accessToken\" : \"testtoken\" }";
    mockServerAuthProvider.expect(requestTo(BASE_URL + AUTH_PATH)).andExpect(method(HttpMethod.POST))
            .andRespond(withSuccess(authResponseBody, MediaType.APPLICATION_JSON));
    //token is set with no valid time so token should be renewed
    String authResponseBody1 = "{\"accessToken\" : \"testtoken-1\" }";
    mockServerAuthProvider.expect(requestTo(BASE_URL + AUTH_PATH)).andExpect(method(HttpMethod.POST))
            .andRespond(withSuccess(authResponseBody1, MediaType.APPLICATION_JSON));

    //second call with no valid auth token
    this.mockServer.expect(requestTo(BASE_URL + AddresCheckImpl.ADDR_CHECK_PATH))
            .andExpect(method(HttpMethod.GET))
            .andRespond(withSuccess(CHECK_ADDR_RESPONSE_BODY, MediaType.APPLICATION_JSON));

    AddresCheckImpl instance = new AddresCheckImpl(restContext);
    AddressResponse result = instance.checkAddres(addrQuery);
    String authToken1 = authTokenProvider.getAuthorisationToken().toString();
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    AddressResponse result1 = instance.checkAddres(addrQuery);
    String authToken2 = authTokenProvider.getAuthorisationToken().toString();

    Integer expectedTotal = new Integer(3);
    assertEquals(result.getTotal(), expectedTotal);

    mockServer.verify();

    mockServerAuthProvider.verify();

}

From source file:fragment.web.AuthenticationControllerTest.java

@Test
public void testLandingRouting() throws Exception {
    logger.debug("Testing routing....");
    DispatcherTestServlet servlet = getServletInstance();
    Method expected = locateMethod(controller.getClass(), "login",
            new Class[] { HttpServletRequest.class, ModelMap.class, HttpSession.class });
    Method handler = servlet.recognize(getRequestTemplate(HttpMethod.GET, "/login"));
    Assert.assertEquals(expected, handler);

    expected = locateMethod(controller.getClass(), "loggedout", new Class[] { java.lang.String.class,
            ModelMap.class, HttpSession.class, HttpServletResponse.class, HttpServletRequest.class });
    handler = servlet.recognize(getRequestTemplate(HttpMethod.GET, "/userParam/loggedout"));
    Assert.assertEquals(expected, handler);

    MockHttpServletRequest request = getRequestTemplate(HttpMethod.GET, "/reset_password");

    expected = locateMethod(controller.getClass(), "requestReset", new Class[] { ModelMap.class, });
    handler = servlet.recognize(request);
    Assert.assertEquals(expected, handler);

    request.removeAllParameters();// w w  w.  j a v a 2 s. c  o  m
    request.addParameter("username", "value");
    request.setMethod(HttpMethod.POST.name());
    expected = locateMethod(controller.getClass(), "requestReset",
            new Class[] { String.class, HttpServletRequest.class, ModelMap.class });
    handler = servlet.recognize(request);
    Assert.assertEquals(expected, handler);

    request.removeAllParameters();
    request.setMethod(HttpMethod.GET.name());
    request.addParameter("a", "value");
    request.addParameter("t", "0");
    request.addParameter("i", "value");
    expected = locateMethod(controller.getClass(), "reset",
            new Class[] { String.class, Long.TYPE, String.class, HttpSession.class, ModelMap.class });
    handler = servlet.recognize(request);
    Assert.assertEquals(expected, handler);

    request.removeAllParameters();
    request.addParameter("password", "password");
    request.setMethod(HttpMethod.POST.name());
    expected = locateMethod(controller.getClass(), "reset",
            new Class[] { String.class, HttpSession.class, HttpServletRequest.class });
    handler = servlet.recognize(request);
    Assert.assertEquals(expected, handler);

    request.removeAllParameters();
    expected = locateMethod(controller.getClass(), "requestCall",
            new Class[] { String.class, String.class, HttpServletRequest.class });
    handler = servlet.recognize(getRequestTemplate(HttpMethod.POST, "/request_call_by_user"));
    Assert.assertEquals(expected, handler);

    request.removeAllParameters();
    expected = locateMethod(controller.getClass(), "requestSMS",
            new Class[] { String.class, String.class, HttpServletRequest.class });
    handler = servlet.recognize(getRequestTemplate(HttpMethod.POST, "/request_sms_by_user"));
    Assert.assertEquals(expected, handler);

    request.removeAllParameters();
    expected = locateMethod(controller.getClass(), "verifyAdditionalEmail", new Class[] { String.class,
            String.class, String.class, HttpServletRequest.class, ModelMap.class, HttpSession.class });
    handler = servlet.recognize(getRequestTemplate(HttpMethod.GET, "/verify_additional_email"));
    Assert.assertEquals(expected, handler);

    request.removeAllParameters();
    expected = locateMethod(controller.getClass(), "getGoogleAnalytics", new Class[] {});
    handler = servlet.recognize(getRequestTemplate(HttpMethod.GET, "/getGoogleAnalytics"));
    Assert.assertEquals(expected, handler);

}