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.logaritex.hadoop.configuration.manager.SimpleHttpService.java

@Override
public <R> R post(String url, Object request, Class<R> responseType, Object... uriVariables) {

    R response = restTemplate.exchange(baseUrl + url, HttpMethod.POST,
            new HttpEntity<Object>(request, httpHeaders), responseType, uriVariables).getBody();

    return response;
}

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

public T query(String url, String method, String accept, Class<T> rc, Map<String, String> parameters) {

    try {//w  w w .  j  a  v a  2s. co  m
        URI uri = new URL(url).toURI();
        long timestamp = new Date().getTime();

        HttpMethod httpMethod;
        if (method.equalsIgnoreCase("post")) {
            httpMethod = HttpMethod.POST;
        } else {
            httpMethod = HttpMethod.GET;
        }

        String stringToSign = getStringToSign(uri, httpMethod.name(), timestamp, parameters);

        // logger.info("String to sign: " + stringToSign);
        String authorization = generate_HMAC_SHA1_Signature(stringToSign, password + license);
        // logger.info("Authorization string: " + authorization);

        // Setting Headers
        HttpHeaders headers = new HttpHeaders();
        if (accept.equalsIgnoreCase("json")) {
            headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        } else {
            headers.setAccept(Arrays.asList(MediaType.TEXT_XML));
        }

        headers.add("Authorization", authorization);
        headers.add("OB_DATE", "" + timestamp);
        headers.add("OB_Terminal", terminal);
        headers.add("OB_User", user);
        headers.add("OB_Channel", channel);
        headers.add("OB_POS", pos);
        headers.add("Content-Type", "application/x-www-form-urlencoded");

        HttpEntity<String> entity;

        if (httpMethod == HttpMethod.POST) {
            // Adding post parameters to POST body
            String parameterStringBody = getParametersAsString(parameters);
            entity = new HttpEntity<String>(parameterStringBody, headers);
            // logger.info("POST Body: " + parameterStringBody);
        } else {
            entity = new HttpEntity<String>(headers);
        }

        RestTemplate restTemplate = new RestTemplate(
                new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
        interceptors.add(new LoggingRequestInterceptor());
        restTemplate.setInterceptors(interceptors);

        // Converting to UTF-8. OB Rest replies in windows charset.
        //restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName(UTF_8)));

        if (accept.equalsIgnoreCase("json")) {
            restTemplate.getMessageConverters().add(0,
                    new org.springframework.http.converter.json.MappingJackson2HttpMessageConverter());
        } else {
            restTemplate.getMessageConverters().add(0,
                    new org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter());
        }

        ResponseEntity<T> response = restTemplate.exchange(uri, httpMethod, entity, rc);

        if (!response.getStatusCode().is2xxSuccessful())
            throw new HttpClientErrorException(response.getStatusCode());

        return response.getBody();
    } catch (HttpClientErrorException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (MalformedURLException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (SignatureException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (URISyntaxException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }
    return null;
}

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

/**
 * Test of getAuthorisationToken method, of class AuthTokenProviderImpl.
 *//*from  w  w  w.j  ava 2 s. co  m*/
@Test
public void testGetAuthorisationTokenExpired() {
    AuthTokenProvider instance = new AuthTokenProviderImpl(BASE_URL, "test", "test", restTemplate, 0);
    mockServer = MockRestServiceServer.createServer(restTemplate);
    this.mockServer.expect(requestTo(BASE_URL + AUTH_PATH)).andExpect(method(HttpMethod.POST))
            .andRespond(withSuccess("{\"accessToken\" : \"testtoken\" }", MediaType.APPLICATION_JSON));
    this.mockServer.expect(requestTo(BASE_URL + AUTH_PATH)).andExpect(method(HttpMethod.POST))
            .andRespond(withSuccess("{\"accessToken\" : \"testtoken-1\" }", MediaType.APPLICATION_JSON));
    String authorisationToken = instance.getAuthorisationToken().getToken();
    String authorisationToken2 = instance.getAuthorisationToken().getToken();
    this.mockServer.verify();
    assertNotSame(authorisationToken, authorisationToken2);
}

From source file:com.hillert.botanic.config.SecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    SessionRepositoryFilter<ExpiringSession> sessionRepositoryFilter = new SessionRepositoryFilter(
            sessionRepository);//from  w w w.  j  a  v a 2  s.  co  m
    sessionRepositoryFilter.setHttpSessionStrategy(new HeaderHttpSessionStrategy());
    http.addFilterBefore(sessionRepositoryFilter, ChannelProcessingFilter.class).csrf().disable();

    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    http.authorizeRequests().antMatchers(HttpMethod.POST, "/api/plants/**")
            .hasRole(DefaultUserDetailsService.ROLE_ADMIN);

}

From source file:cz.cvut.jirutjak.fastimport.droid.oauth2.DefaultAccessTokenProvider.java

protected OAuth2AccessToken retreiveAccessToken(OAuth2ResourceDetails resource, String authCode) {
    MultiValueMap<String, String> form = AccessTokenUtils.createAccessTokenRequestForm(authCode, resource);
    OAuth2AccessToken token = null;//  ww w  .  j av a 2 s . co  m

    Log.d(TAG, "Request new access token for resource: " + resource.getId());
    try {
        ResponseEntity<OAuth2AccessToken> response = AccessTokenUtils.createRestTemplate().exchange(
                resource.getAccessTokenEndpoint(), HttpMethod.POST, createAccessTokenRequestEntity(form),
                OAuth2AccessToken.class);

        token = response.getBody();
        Log.d(TAG, "Retreived access token: " + token.toString());

    } catch (RestClientException ex) {
        throw new InvalidTokenException("Invalid token", ex);
    }

    if (token == null || token.getAccessToken() == null) {
        throw new InvalidTokenException("Invalid token");
    }

    return token;
}

From source file:org.trustedanalytics.h2oscoringengine.publisher.steps.CreatingPlanVisibilityStep.java

public void addServicePlanVisibility(String orgGuid, String serviceName) throws EnginePublicationException {
    LOGGER.info("Setting plan visibility for " + serviceName + " in " + orgGuid + " organization");

    try {/*w w w.  ja  va2 s  . c om*/
        String serviceGuid = getServiceGuidByName(serviceName);
        String planGuid = getServicePlanGuid(serviceGuid);

        String requestBody = prepareServiceVisibilityJsonRequest(planGuid, orgGuid);
        String cfPlanVisibilityUrl = cfApiUrl + SERVICE_PLAN_VISIBILITIES_ENDPOINT;

        cfRestTemplate.exchange(cfPlanVisibilityUrl, HttpMethod.POST,
                HttpCommunication.postRequest(requestBody), String.class);
    } catch (IOException e) {
        throw new EnginePublicationException("Unable to set service plan visibility for " + serviceName, e);
    }
}

From source file:io.spring.initializr.actuate.stat.ProjectGenerationStatPublisherTests.java

@Test
public void publishSimpleDocument() {
    ProjectRequest request = createProjectRequest();
    request.setGroupId("com.example.foo");
    request.setArtifactId("my-project");

    this.mockServer.expect(requestTo("http://example.com/elastic/initializr/request"))
            .andExpect(method(HttpMethod.POST)).andExpect(jsonPath("$.groupId").value("com.example.foo"))
            .andExpect(jsonPath("$.artifactId").value("my-project"))
            .andRespond(withStatus(HttpStatus.CREATED).body(mockResponse(UUID.randomUUID().toString(), true))
                    .contentType(MediaType.APPLICATION_JSON));

    this.statPublisher.handleEvent(new ProjectGeneratedEvent(request));
    this.mockServer.verify();
}

From source file:org.surfnet.oaaas.consent.FormUserConsentHandler.java

private boolean isUserConsentPost(HttpServletRequest request) {
    String oauthApproval = request.getParameter(USER_OAUTH_APPROVAL);
    return request.getMethod().equals(HttpMethod.POST.toString()) && StringUtils.isNotBlank(oauthApproval);
}

From source file:org.starfishrespect.myconsumption.android.tasks.GCMRegister.java

/**
 * Registers the application with GCM servers asynchronously.
 * <p>// w ww  .  j a v  a2s . c o m
 * Stores the registration ID and app versionCode in the application's
 * shared preferences.
 */
public void registerInBackground(final Context context) {
    AsyncTask<Void, List, String> task = new AsyncTask<Void, List, String>() {
        @Override
        protected String doInBackground(Void... params) {
            RestTemplate template = new RestTemplate();
            HttpHeaders httpHeaders = CryptoUtils.createHeadersCurrentUser();
            ResponseEntity<String> responseEnt;
            template.getMessageConverters().add(new FormHttpMessageConverter());
            template.getMessageConverters().add(new StringHttpMessageConverter());
            String msg = "";

            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                }
                String regid = gcm.register(Config.SENDER_ID);
                msg = "Device registered, registration ID=" + regid;

                // Send the registration ID to the server
                String url = SingleInstance.getServerUrl() + "notifs/"
                        + SingleInstance.getUserController().getUser().getName() + "/id/" + regid;

                responseEnt = template.exchange(url, HttpMethod.POST, new HttpEntity<>(httpHeaders),
                        String.class);
                SimpleResponseDTO response = new ObjectMapper().readValue(responseEnt.getBody(),
                        SimpleResponseDTO.class);

                if (response.getStatus() != SimpleResponseDTO.STATUS_SUCCESS) {
                    msg = "Error: " + response.getStatus() + " Cannot post register id on server side.";
                }

                // Persist the registration ID - no need to register again.
                PrefUtils.setRegistrationId(context, regid);
            } catch (IOException ex) {
                msg = "Error:" + ex.getMessage();
                // If there is an error, don't just keep trying to register.
                // Require the user to click a button again, or perform
                // exponential back-off.
            }
            return msg;
        }

        @Override
        protected void onPostExecute(String msg) {
            LOGI(TAG, msg);
        }
    };

    task.execute();
}

From source file:org.trustedanalytics.h2oscoringengine.publisher.steps.RegisteringInApplicationBrokerStepTest.java

@Test
public void register_callToAppBrokerOccured() throws Exception {
    // given/*from w ww . j a  va  2 s .c  om*/
    RegisteringInApplicationBrokerStep step = new RegisteringInApplicationBrokerStep(testAppGuid, testCfApi,
            cfRestTemplateMock);

    // when
    step.register(testCredentials, basicRestTemplateMock, testServiceName, testServiceDescription);
    ArgumentCaptor<HttpEntity> requestCaptor = ArgumentCaptor.forClass(HttpEntity.class);

    // then
    verify(basicRestTemplateMock).exchange(eq(appBrokerEndpoint), same(HttpMethod.POST),
            requestCaptor.capture(), same(String.class));
    HttpEntity<String> request = requestCaptor.getValue();
    assertThat(request.getHeaders(), equalTo(expectedHeaders));
    String actualRequestBody = request.getBody();
    assertThat(JsonDataFetcher.getStringValue(actualRequestBody, "/app/metadata/guid"), equalTo(testAppGuid));
    assertThat(JsonDataFetcher.getStringValue(actualRequestBody, "/description"),
            equalTo(testServiceDescription));
    assertThat(JsonDataFetcher.getStringValue(actualRequestBody, "/name"), equalTo(testServiceName));

}