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:io.github.microcks.util.test.HttpTestRunner.java

/**
 * Build the HttpMethod corresponding to string. Default to POST
 * if unknown or unrecognized.// w  ww  .ja v a 2s . c  o  m
 */
@Override
public HttpMethod buildMethod(String method) {
    if (method != null) {
        if ("GET".equals(method.toUpperCase().trim())) {
            return HttpMethod.GET;
        } else if ("PUT".equals(method.toUpperCase().trim())) {
            return HttpMethod.PUT;
        } else if ("DELETE".equals(method.toUpperCase().trim())) {
            return HttpMethod.DELETE;
        }
    }
    return HttpMethod.POST;
}

From source file:org.client.one.service.OAuthAuthenticationService.java

public boolean registerUserWS(String token, Profile profile)
        throws JsonGenerationException, JsonMappingException, IOException, JSONException {
    RestOperations rest = new RestTemplate();

    HttpHeaders headersA = new HttpHeaders();
    headersA.set("Authorization", "Bearer " + token);
    headersA.setContentType(MediaType.TEXT_PLAIN);

    ObjectMapper mapper = new ObjectMapper();
    HttpEntity<String> request = new HttpEntity<String>(
            mapper.writeValueAsString(new RequestProfile(token, profile)), headersA);

    ResponseEntity<String> responseUpdate = rest.exchange(
            appThreeServicesBaseURL + "/resources/profile/registerUser", HttpMethod.POST, request,
            String.class);

    JSONObject responseUpdateJSON = new JSONObject(responseUpdate.getBody());

    return responseUpdateJSON.getBoolean("success");
}

From source file:com.artivisi.belajar.restful.ui.controller.ApplicationConfigControllerTestIT.java

@SuppressWarnings("unchecked")
@Test//from   ww w. j  a v a 2 s . c o  m
public void testUploadPakaiRestTemplate() {
    RestTemplate rest = new RestTemplate();

    String jsessionid = rest.execute(login, HttpMethod.POST, new RequestCallback() {
        @Override
        public void doWithRequest(ClientHttpRequest request) throws IOException {
            request.getBody().write(("j_username=" + username + "&j_password=" + password).getBytes());
        }
    }, new ResponseExtractor<String>() {
        @Override
        public String extractData(ClientHttpResponse response) throws IOException {
            List<String> cookies = response.getHeaders().get("Cookie");

            // assuming only one cookie with jsessionid as the only value
            if (cookies == null) {
                cookies = response.getHeaders().get("Set-Cookie");
            }

            String cookie = cookies.get(cookies.size() - 1);

            int start = cookie.indexOf('=');
            int end = cookie.indexOf(';');

            return cookie.substring(start + 1, end);
        }
    });

    MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
    form.add("foto", new FileSystemResource("src/test/resources/foto-endy.jpg"));
    form.add("Filename", "cv-endy.pdf");
    form.add("cv", new FileSystemResource("src/test/resources/resume-endy-en.pdf"));
    form.add("keterangan", "File Endy");
    Map<String, String> result = rest.postForObject(target + "/abc123/files;jsessionid=" + jsessionid, form,
            Map.class);

    assertEquals("success", result.get("cv"));
    assertEquals("success", result.get("foto"));
    assertEquals("success", result.get("keterangan"));
}

From source file:net.slkdev.swagger.confluence.service.impl.XHtmlToConfluenceServiceImplTest.java

@Test
public void testCreatePageWithPaginationModeCategory() {
    final SwaggerConfluenceConfig swaggerConfluenceConfig = getTestSwaggerConfluenceConfig();
    swaggerConfluenceConfig.setPaginationMode(PaginationMode.CATEGORY_PAGES);

    final String xhtml = IOUtils.readFull(
            AsciiDocToXHtmlServiceImplTest.class.getResourceAsStream("/swagger-petstore-xhtml-example.html"));

    for (int i = 0; i < 5; i++) {
        when(restTemplate.exchange(any(URI.class), eq(HttpMethod.GET), any(RequestEntity.class),
                eq(String.class))).thenReturn(responseEntity);
        when(responseEntity.getBody()).thenReturn(GET_RESPONSE_NOT_FOUND);
        when(restTemplate.exchange(any(URI.class), eq(HttpMethod.POST), any(HttpEntity.class),
                eq(String.class))).thenReturn(responseEntity);
        when(responseEntity.getBody()).thenReturn(POST_RESPONSE);
    }//from   w  ww  . ja va 2s .c om

    final ArgumentCaptor<HttpEntity> httpEntityCaptor = ArgumentCaptor.forClass(HttpEntity.class);

    xHtmlToConfluenceService.postXHtmlToConfluence(swaggerConfluenceConfig, xhtml);

    verify(restTemplate, times(5)).exchange(any(URI.class), eq(HttpMethod.GET), any(RequestEntity.class),
            eq(String.class));
    verify(restTemplate, times(5)).exchange(any(URI.class), eq(HttpMethod.POST), httpEntityCaptor.capture(),
            eq(String.class));

    final HttpEntity<String> capturedHttpEntity = httpEntityCaptor.getAllValues().get(3);

    final String expectedPostBody = IOUtils.readFull(AsciiDocToXHtmlServiceImplTest.class
            .getResourceAsStream("/swagger-confluence-create-json-body-definitions-example.json"));

    assertNotNull("Failed to Capture RequeestEntity for POST", capturedHttpEntity);
    // We'll do a full check on the last page versus a resource; not doing all of them as it
    // would be a pain to maintain, but this should give us a nod of confidence.
    assertEquals("Unexpected JSON Post Body", expectedPostBody, capturedHttpEntity.getBody());
}

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

@Test
public void testResume() throws Exception {

    ThermostatFunction function = new ThermostatFunction(Selection.thermostats("161775386723"),
            new Function("resumeProgram", new HashMap<String, String>()));
    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().resume("161775386723");

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

From source file:io.gravitee.management.security.config.basic.BasicSecurityConfigurerAdapter.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    final String jwtSecret = environment.getProperty("jwt.secret");
    if (jwtSecret == null || jwtSecret.isEmpty()) {
        throw new IllegalStateException("JWT secret is mandatory");
    }//  w ww  .  j  a  va2 s . c  o m

    http.httpBasic().realmName("Gravitee.io Management API").and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "**").permitAll().antMatchers(HttpMethod.GET, "/user/**")
            .permitAll()
            // API requests
            .antMatchers(HttpMethod.GET, "/apis/**").permitAll().antMatchers(HttpMethod.POST, "/apis/**")
            .hasAnyAuthority("ADMIN", "API_PUBLISHER").antMatchers(HttpMethod.PUT, "/apis/**")
            .hasAnyAuthority("ADMIN", "API_PUBLISHER").antMatchers(HttpMethod.DELETE, "/apis/**")
            .hasAnyAuthority("ADMIN", "API_PUBLISHER")
            // Application requests
            .antMatchers(HttpMethod.POST, "/applications/**").hasAnyAuthority("ADMIN", "API_CONSUMER")
            .antMatchers(HttpMethod.PUT, "/applications/**").hasAnyAuthority("ADMIN", "API_CONSUMER")
            .antMatchers(HttpMethod.DELETE, "/applications/**").hasAnyAuthority("ADMIN", "API_CONSUMER")
            // Instance requests
            .antMatchers(HttpMethod.GET, "/instances/**").hasAuthority("ADMIN").anyRequest().authenticated()
            .and().csrf().disable().addFilterAfter(corsFilter(), AbstractPreAuthenticatedProcessingFilter.class)
            .addFilterBefore(new JWTAuthenticationFilter(jwtCookieGenerator, jwtSecret),
                    BasicAuthenticationFilter.class)
            .addFilterAfter(
                    new AuthenticationSuccessFilter(jwtCookieGenerator, jwtSecret,
                            environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER), environment
                                    .getProperty("jwt.expire-after", Integer.class, DEFAULT_JWT_EXPIRE_AFTER)),
                    BasicAuthenticationFilter.class);
}

From source file:com.cisco.cta.taxii.adapter.AdapterTaskIT.java

private void requestStatusMessage(int count) throws IOException {
    when(httpResp.getRawStatusCode()).thenReturn(200);
    when(httpResp.getBody()).thenReturn(taxiiStatusMsgBody);
    task.run();// ww  w  .  j a v  a  2  s.c om
    verify(httpRequestFactory, times(count)).createRequest(pollServiceUri, HttpMethod.POST);
    verify(httpReq, times(count)).execute();
    assertThat(httpReqHeaders, hasAllTaxiiHeaders());
    assertThat(httpReqBody, is(nextPollRequest("123", "collection_name", "2000-12-24T01:02:03.004+01:00")));
    httpReqBody.reset();
}

From source file:org.openbaton.nse.beans.connectivitymanageragent.ConnectivityManagerRequestor.java

public RequestFlows setFlow(RequestFlows flow) {

    String url = configuration.getBaseUrl() + "/flow";
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> flowEntity = new HttpEntity<>(mapper.toJson(flow, RequestFlows.class), headers);
    logger.debug("SENDING FLOWS " + mapper.toJson(flow, RequestFlows.class));
    ResponseEntity<String> addFlow = template.exchange(url, HttpMethod.POST, flowEntity, String.class);

    logger.debug(/* w  w w  .j av a2  s.  co  m*/
            "FLOW RESPONSE: sent flow configuration " + flow.toString() + " and received " + addFlow.getBody());

    if (!addFlow.getStatusCode().is2xxSuccessful()) {
        logger.debug("Status code is " + addFlow.getStatusCode());
        return null;
    } else {
        return mapper.fromJson(addFlow.getBody(), RequestFlows.class);
    }
}

From source file:jp.go.aist.six.util.core.web.spring.Http.java

/**
 * HTTP POST: Reads the contents from the specified reader and sends them to the URL.
 *
 * @return/*from w w w .  j  av a  2s  . c  o m*/
 *  the location, as an URI,  where the resource is created.
 * @throws  HttpException
 *  when an exceptional condition occurred during the HTTP method execution.
 */
public static String postFrom(final URL to_url, final Reader from_reader, final MediaType media_type) {
    ReaderRequestCallback callback = new ReaderRequestCallback(from_reader, media_type);
    String location = _execute(to_url, HttpMethod.POST, callback, new LocationHeaderResponseExtractor());

    return location;
}

From source file:org.apigw.authserver.ServerRunning.java

public ResponseEntity<String> postForString(String path, MultiValueMap<String, String> formData) {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    return client.exchange(getUrl(path), HttpMethod.POST,
            new HttpEntity<MultiValueMap<String, String>>(formData, headers), String.class);
}