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:org.trustedanalytics.h2oscoringengine.publisher.steps.CreatingPlanVisibilityStepTest.java

License:asdf

@Test
public void addServicePlanVisibility_allCloduFoundryCallsOccured() throws Exception {
    // given//from   w ww. j ava  2s  . c o m
    CreatingPlanVisibilityStep step = new CreatingPlanVisibilityStep(testCfApi, restTemplateMock);

    // when
    when(serviceGuidResponseMock.getBody()).thenReturn(serviceGuidResponse);
    when(servicePlanResponseMock.getBody()).thenReturn(planGuidResponse);
    step.addServicePlanVisibility(testOrgGuid, testServiceName);

    // then
    verify(restTemplateMock).exchange(testCfServiceGuidEndpoint, HttpMethod.GET,
            HttpCommunication.simpleJsonRequest(), String.class, testServiceName);
    verify(restTemplateMock).exchange(testCfServicePlanEndpoint, HttpMethod.GET,
            HttpCommunication.simpleJsonRequest(), String.class, testServiceGuid);
    verify(restTemplateMock).exchange(testCfPlanVisibilityEndpoint, HttpMethod.POST,
            HttpCommunication.postRequest(setVisibilityRequestBody), String.class);

}

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

@Test
public void performPostWith200_XML() throws Exception {

    protocolRegistry.registerHost(brokerUrl);

    HttpHeaders httpHeaders = ngsiClient.getRequestHeaders(brokerUrl);
    Assert.assertEquals("application/xml", httpHeaders.getFirst("Content-Type"));
    Assert.assertEquals("application/xml", httpHeaders.getFirst("Accept"));

    httpHeaders.add("Fiware-Service", serviceName);
    httpHeaders.add("Fiware-ServicePath", servicePath);

    String responseBody = xml(xmlConverter, createUpdateContextResponseTempSensor());

    this.mockServer.expect(requestTo(brokerUrl + "/ngsi10/updateContext")).andExpect(method(HttpMethod.POST))
            .andExpect(header("Content-Type", MediaType.APPLICATION_XML_VALUE))
            .andExpect(header("Accept", MediaType.APPLICATION_XML_VALUE))
            .andExpect(header("Fiware-Service", serviceName))
            .andExpect(header("Fiware-ServicePath", servicePath))
            .andExpect(xpath("updateContextRequest/updateAction").string(UpdateAction.UPDATE.getLabel()))
            .andExpect(xpath("updateContextRequest/contextElementList/contextElement/entityId/id").string("S1"))
            .andExpect(xpath(//from w w w . j  av a2s  .co  m
                    "updateContextRequest/contextElementList/contextElement/contextAttributeList/contextAttribute/name")
                            .string("temp"))
            .andExpect(xpath(
                    "updateContextRequest/contextElementList/contextElement/contextAttributeList/contextAttribute/type")
                            .string("float"))
            .andExpect(xpath(
                    "updateContextRequest/contextElementList/contextElement/contextAttributeList/contextAttribute/contextValue")
                            .string("15.5"))
            .andRespond(withSuccess(responseBody, MediaType.APPLICATION_XML));

    ngsiClient.updateContext(brokerUrl, httpHeaders, createUpdateContextTempSensor(0)).get();

    this.mockServer.verify();
}

From source file:com.appglu.impl.SavedQueriesTemplateTest.java

@Test
public void runQueryEmptyQueryParams() {
    mockServer.expect(requestTo("http://localhost/appglu/v1/queries/queryName/run"))
            .andExpect(method(HttpMethod.POST)).andExpect(header("Content-Type", jsonMediaType.toString()))
            .andExpect(content().string(compactedJson("data/saved_queries_params_empty")))
            .andRespond(withSuccess().body(compactedJson("data/saved_queries_update_result"))
                    .headers(responseHeaders));

    savedQueriesOperations.runQuery("queryName", new QueryParams());

    mockServer.verify();/*from   w  ww.  j  av  a2  s  .  c  o  m*/
}

From source file:com.tikinou.schedulesdirect.ClientUtils.java

public <R_IMPL extends R, P extends BaseCommandParameter, R extends CommandResult, C extends ParameterizedCommand<P, R>, R_OVER> R_OVER executeRequest(
        SchedulesDirectClient client, C command, Class<R_IMPL> resultType, Class<R_OVER> resulTypetOverride) {
    StringBuilder url = new StringBuilder(client.getUrl());
    url.append("/").append(command.getEndPoint());
    String token = null;//from w w  w.  ja  v  a 2s .  co  m
    if (command.getParameters() instanceof AuthenticatedBaseCommandParameter)
        token = ((AuthenticatedBaseCommandParameter) command.getParameters()).getToken();

    org.springframework.http.HttpMethod httpMethod = null;
    switch (command.getMethod()) {
    case GET:
        Map<String, String> reqParams = command.getParameters().toRequestParameters();
        if (reqParams != null) {
            url.append("?");
            int i = 0;
            for (Map.Entry<String, String> entry : reqParams.entrySet()) {
                if (i > 0)
                    url.append("&");
                url.append(entry.getKey()).append("=").append(entry.getValue());
                i++;
            }
        }
        httpMethod = org.springframework.http.HttpMethod.GET;
        break;
    case POST: {
        httpMethod = org.springframework.http.HttpMethod.POST;
        break;
    }
    case PUT: {
        httpMethod = org.springframework.http.HttpMethod.PUT;
        break;
    }
    case DELETE: {
        httpMethod = org.springframework.http.HttpMethod.DELETE;
        break;
    }
    }

    if (resulTypetOverride == null) {
        ResponseEntity<R_IMPL> res = restTemplate.exchange(url.toString(), httpMethod,
                getRequestEntity(client.getUserAgent(), command.getParameters(), token), resultType);
        if (res.getStatusCode() == HttpStatus.OK) {
            R result = res.getBody();
            command.setResults(result);
            command.setStatus(CommandStatus.SUCCESS);
        } else {
            command.setStatus(CommandStatus.FAILURE);
        }
    } else {
        ResponseEntity<R_OVER> res = restTemplate.exchange(url.toString(), httpMethod,
                getRequestEntity(client.getUserAgent(), command.getParameters(), token), resulTypetOverride);
        if (res.getStatusCode() == HttpStatus.OK) {
            command.setStatus(CommandStatus.SUCCESS);
        } else {
            command.setStatus(CommandStatus.FAILURE);
        }
        return res.getBody();
    }
    return null;
}

From source file:com.taxamo.example.ec.ApplicationController.java

/**
 * This method initializes Express Checkout token with PayPal and then redirects to Taxamo checkout form.
 *
 * Please note that only Express Checkout token is provided to Taxamo - and Taxamo will use
 * provided PayPal credentials to get order details from it and render the checkout form.
 *
 *
 * @param model//from w w w  .j ava  2  s  . c  om
 * @return
 */
@RequestMapping("/express-checkout")
public String expressCheckout(Model model) {

    RestTemplate template = new RestTemplate();

    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    map.add("USER", ppUser);
    map.add("PWD", ppPass);
    map.add("SIGNATURE", ppSign);
    map.add("VERSION", "117");
    map.add("METHOD", "SetExpressCheckout");
    map.add("returnUrl", properties.getProperty(PropertiesConstants.STORE)
            + properties.getProperty(PropertiesConstants.CONFIRM_LINK));
    map.add("cancelUrl", properties.getProperty(PropertiesConstants.STORE)
            + properties.getProperty(PropertiesConstants.CANCEL_LINK));

    //shopping item(s)
    map.add("PAYMENTREQUEST_0_AMT", "20.00"); // total amount
    map.add("PAYMENTREQUEST_0_PAYMENTACTION", "Sale");
    map.add("PAYMENTREQUEST_0_CURRENCYCODE", "EUR");

    map.add("L_PAYMENTREQUEST_0_NAME0", "ProdName");
    map.add("L_PAYMENTREQUEST_0_DESC0", "ProdName desc");
    map.add("L_PAYMENTREQUEST_0_AMT0", "20.00");
    map.add("L_PAYMENTREQUEST_0_QTY0", "1");
    map.add("L_PAYMENTREQUEST_0_ITEMCATEGORY0", "Digital");

    List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
    messageConverters.add(new FormHttpMessageConverter());
    messageConverters.add(new StringHttpMessageConverter());
    template.setMessageConverters(messageConverters);

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map,
            requestHeaders);
    ResponseEntity<String> res = template.exchange(
            URI.create(properties.get(PropertiesConstants.PAYPAL_NVP).toString()), HttpMethod.POST, request,
            String.class);

    Map<String, List<String>> params = parseQueryParams(res.getBody());

    String ack = params.get("ACK").get(0);
    if (!ack.equals("Success")) {
        model.addAttribute("error", params.get("L_LONGMESSAGE0").get(0));
        return "error";
    } else {
        String token = params.get("TOKEN").get(0);
        return "redirect:" + properties.get(PropertiesConstants.TAXAMO) + "/checkout/index.html?" + "token="
                + token + "&public_token=" + publicToken + "&cancel_url="
                + new String(
                        Base64.encodeBase64((properties.getProperty(PropertiesConstants.STORE)
                                + properties.getProperty(PropertiesConstants.CANCEL_LINK)).getBytes()))
                + "&return_url="
                + new String(Base64.encodeBase64((properties.getProperty(PropertiesConstants.STORE)
                        + properties.getProperty(PropertiesConstants.CONFIRM_LINK)).getBytes()))
                + "#/paypal_express_checkout";
    }
}

From source file:org.drugis.addis.config.SecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    String[] whitelist = { "/", "/trialverse", "/trialverse/**", "/patavi", // allow POST mcda models anonymously
            "/favicon.ico", "/favicon.png", "/app/**", "/auth/**", "/signin", "/signup", "/**/modal/*.html",
            "/manual.html" };
    // Disable CSFR protection on the following urls:
    List<AntPathRequestMatcher> requestMatchers = Arrays.asList(whitelist).stream()
            .map(AntPathRequestMatcher::new).collect(Collectors.toList());
    CookieCsrfTokenRepository csrfTokenRepository = new CookieCsrfTokenRepository();
    csrfTokenRepository.setCookieHttpOnly(false);
    http.formLogin().loginPage("/signin").loginProcessingUrl("/signin/authenticate")
            .failureUrl("/signin?param.error=bad_credentials").and().authorizeRequests().antMatchers(whitelist)
            .permitAll().antMatchers(HttpMethod.GET, "/**").permitAll().antMatchers(HttpMethod.POST, "/**")
            .authenticated().antMatchers(HttpMethod.PUT, "/**").authenticated()
            .antMatchers(HttpMethod.DELETE, "/**").authenticated().and().rememberMe().and().exceptionHandling()
            .authenticationEntryPoint(new Http403ForbiddenEntryPoint()).and()
            .apply(new SpringSocialConfigurer().alwaysUsePostLoginUrl(false)).and().csrf()
            .csrfTokenRepository(csrfTokenRepository)
            .requireCsrfProtectionMatcher(
                    request -> !(requestMatchers.stream().anyMatch(matcher -> matcher.matches(request))
                            || Optional.fromNullable(request.getHeader("X-Auth-Application-Key")).isPresent()
                            || HttpMethod.GET.toString().equals(request.getMethod())))
            .and().setSharedObject(ApplicationContext.class, context);

    http.addFilterBefore(new AuthenticationFilter(authenticationManager()), BasicAuthenticationFilter.class);

}

From source file:org.openmhealth.shim.OAuth1Utils.java

public static HttpRequestBase getSignedRequest(String unsignedUrl, String clientId, String clientSecret,
        String token, String tokenSecret, Map<String, String> oAuthParameters) throws ShimException {
    return getSignedRequest(HttpMethod.POST, unsignedUrl, clientId, clientSecret, token, tokenSecret,
            oAuthParameters);//from  w  ww. j av a 2 s . co m
}

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

/**
 * Append an attribute to a context element
 * @param url the URL of the broker/*from   w ww .j  a v  a  2s.  co  m*/
 * @param httpHeaders the HTTP header to use, or null for default
 * @param entityID the ID of the entity
 * @param attributeName the name of the attribute
 * @param updateContextAttribute attribute to append
 * @return a future for a StatusCode
 */
public ListenableFuture<StatusCode> appendContextAttribute(String url, HttpHeaders httpHeaders, String entityID,
        String attributeName, UpdateContextAttribute updateContextAttribute) {
    return request(HttpMethod.POST, url + entitiesPath + entityID + attributesPath + attributeName, httpHeaders,
            updateContextAttribute, StatusCode.class);
}

From source file:org.zaizi.AuthServerApplicationTests.java

@Test
public void loginSucceeds() {
    ResponseEntity<String> response = template.getForEntity("http://localhost:" + port + contextPath + "/login",
            String.class);
    String csrf = getCsrf(response.getBody());
    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    form.set("username", "admin");
    form.set("password", "ulibraxi");
    form.set("_csrf", csrf);
    HttpHeaders headers = new HttpHeaders();
    headers.put("COOKIE", response.getHeaders().get("Set-Cookie"));
    RequestEntity<MultiValueMap<String, String>> request = new RequestEntity<MultiValueMap<String, String>>(
            form, headers, HttpMethod.POST, URI.create("http://localhost:" + port + contextPath + "/login"));
    ResponseEntity<Void> location = template.exchange(request, Void.class);
    assertEquals("http://localhost:" + port + contextPath + "/", location.getHeaders().getFirst("Location"));
}

From source file:fragment.web.HomeControllerTest.java

@Test
public void testHomeRouting() throws Exception {
    logger.debug("Testing routing....");
    DispatcherTestServlet servlet = this.getServletInstance();
    Method expected = locateMethod(controller.getClass(), "home", new Class[] { Tenant.class, String.class,
            Boolean.TYPE, ModelMap.class, HttpSession.class, HttpServletRequest.class });
    Method handler = servlet.recognize(getRequestTemplate(HttpMethod.GET, "/home"));
    Assert.assertEquals(expected, handler);
    expected = locateMethod(controller.getClass(), "forum",
            new Class[] { HttpServletResponse.class, ModelMap.class });
    handler = servlet.recognize(getRequestTemplate(HttpMethod.GET, "/forum"));
    Assert.assertEquals(expected, handler);

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

}