List of usage examples for org.springframework.http HttpMethod POST
HttpMethod POST
To view the source code for org.springframework.http HttpMethod POST.
Click Source Link
From source file:net.slkdev.swagger.confluence.service.impl.XHtmlToConfluenceServiceImplTest.java
@Test public void testCreatePageWithPaginationModeIndividual() { final SwaggerConfluenceConfig swaggerConfluenceConfig = getTestSwaggerConfluenceConfig(); swaggerConfluenceConfig.setPaginationMode(PaginationMode.INDIVIDUAL_PAGES); final String xhtml = IOUtils.readFull( AsciiDocToXHtmlServiceImplTest.class.getResourceAsStream("/swagger-petstore-xhtml-example.html")); for (int i = 0; i < 31; 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); }/* w w w . j av a2 s . com*/ final ArgumentCaptor<HttpEntity> httpEntityCaptor = ArgumentCaptor.forClass(HttpEntity.class); xHtmlToConfluenceService.postXHtmlToConfluence(swaggerConfluenceConfig, xhtml); verify(restTemplate, times(34)).exchange(any(URI.class), eq(HttpMethod.GET), any(RequestEntity.class), eq(String.class)); verify(restTemplate, times(34)).exchange(any(URI.class), eq(HttpMethod.POST), httpEntityCaptor.capture(), eq(String.class)); final HttpEntity<String> capturedHttpEntity = httpEntityCaptor.getAllValues().get(30); final String expectedPostBody = IOUtils.readFull(AsciiDocToXHtmlServiceImplTest.class .getResourceAsStream("/swagger-confluence-create-json-body-user-example.json")); assertNotNull("Failed to Capture RequestEntity 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:cn.org.once.cstack.cli.rest.RestUtils.java
/** * // w w w .ja va 2s.com * /** sendPostCommand * * @param url * @param parameters * @return * @throws ClientProtocolException */ public Map<String, Object> sendPostForUpload(String url, Map<String, Object> parameters) { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); requestFactory.setBufferRequestBody(false); RestTemplate restTemplate = new RestTemplate(requestFactory); List<HttpMessageConverter<?>> mc = restTemplate.getMessageConverters(); mc.add(new MappingJackson2HttpMessageConverter()); restTemplate.setMessageConverters(mc); MultiValueMap<String, Object> postParams = new LinkedMultiValueMap<String, Object>(); postParams.setAll(parameters); Map<String, Object> response = new HashMap<String, Object>(); HttpHeaders headers = new HttpHeaders(); headers.set("Content-Type", "multipart/form-data"); headers.set("Accept", "application/json"); headers.add("Cookie", "JSESSIONID=" + localContext.getCookieStore().getCookies().get(0).getValue()); HttpEntity<Object> request = new HttpEntity<Object>(postParams, headers); ResponseEntity<?> result = restTemplate.exchange(url, HttpMethod.POST, request, String.class); String body = result.getBody().toString(); MediaType contentType = result.getHeaders().getContentType(); HttpStatus statusCode = result.getStatusCode(); response.put(CONTENT_TYPE, contentType); response.put(STATUS_CODE, statusCode); response.put(BODY, body); return response; }
From source file:org.appverse.web.framework.backend.test.util.frontfacade.mvc.tests.predefined.BasicAuthEndPointsServiceEnabledPredefinedTests.java
@Test public void simpleAuthenticationRemoteLogServiceEnabledWithoutCsrfTokenTest() throws Exception { RemoteLogRequestVO logRequestVO = new RemoteLogRequestVO(); logRequestVO.setMessage("Test mesage!"); logRequestVO.setLogLevel("DEBUG"); HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Basic " + new String(Base64.encode((getUsername() + ":" + getPassword()).getBytes("UTF-8")))); HttpEntity<RemoteLogRequestVO> entity = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers); UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl("http://localhost:" + port + baseApiPath + remoteLogEndpointPath); ResponseEntity<String> responseEntity = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entity, String.class); assertEquals(HttpStatus.FORBIDDEN, responseEntity.getStatusCode()); }
From source file:com.sitewhere.rest.service.SiteWhereClient.java
@Override public DeviceAssignment updateDeviceAssignmentMetadata(String token, MetadataProvider metadata) throws SiteWhereException { Map<String, String> vars = new HashMap<String, String>(); vars.put("token", token); return sendRest(getBaseUrl() + "assignments/{token}/metadata", HttpMethod.POST, metadata, DeviceAssignment.class, vars); }
From source file:org.trustedanalytics.servicebroker.gearpump.service.CloudFoundryService.java
private String createUIInstance(String uiInstanceName, String spaceId, String orgId, String uiServicePlanGuid, String username, String password, String gearpumpMaster, String uaaClientName) throws IOException { LOGGER.info("Creating Service Instance"); String body = String.format(CREATE_SERVICE_BODY_TEMPLATE, uiInstanceName, spaceId, uiServicePlanGuid, uiInstanceName, username, password, gearpumpMaster, uaaClientName, password, loginHost(), cfApiEndpoint, orgId);/*from ww w. jav a2 s. c o m*/ LOGGER.debug("Create app body: {}", body); ResponseEntity<String> response = execute(CREATE_SERVICE_INSTANCE_URL, HttpMethod.POST, body, cfApiEndpoint); String uiServiceInstanceGuid = cfCaller.getValueFromJson(response.getBody(), METADATA_GUID); LOGGER.debug("UI Service Instance Guid '{}'", uiServiceInstanceGuid); return uiServiceInstanceGuid; }
From source file:access.deploy.geoserver.PiazzaEnvironment.java
/** * Creates the Piazza Postgres vector data store *//*w ww . jav a2 s .c o m*/ private void createPostgresStore() { // Get Request XML ClassLoader classLoader = getClass().getClassLoader(); InputStream inputStream = null; String dataStoreBody = null; try { inputStream = classLoader.getResourceAsStream("templates" + File.separator + "createDataStore.xml"); dataStoreBody = IOUtils.toString(inputStream); } catch (Exception exception) { LOGGER.error("Error reading GeoServer Data Store Template.", exception); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (Exception exception) { LOGGER.error("Error closing GeoServer Data Store Template Stream.", exception); } } // Create Workspace if (dataStoreBody != null) { // Insert the credential data into the template dataStoreBody = dataStoreBody.replace("$DB_USER", postgresServiceKeyUser); dataStoreBody = dataStoreBody.replace("$DB_PASSWORD", postgresServiceKeyPassword); dataStoreBody = dataStoreBody.replace("$DB_PORT", postgresPort); dataStoreBody = dataStoreBody.replace("$DB_NAME", postgresDatabase); dataStoreBody = dataStoreBody.replace("$DB_HOST", postgresHost); // POST Data Store to GeoServer authHeaders.setContentType(MediaType.APPLICATION_XML); HttpEntity<String> request = new HttpEntity<>(dataStoreBody, authHeaders.get()); String uri = String.format("%s/rest/workspaces/piazza/datastores", accessUtilities.getGeoServerBaseUrl()); try { pzLogger.log(String.format("Creating Piazza Data Store to %s", uri), Severity.INFORMATIONAL, new AuditElement(ACCESS, "tryCreateGeoServerDataStore", uri)); restTemplate.exchange(uri, HttpMethod.POST, request, String.class); } catch (HttpClientErrorException | HttpServerErrorException exception) { String error = String.format("HTTP Error occurred while trying to create Piazza Data Store: %s", exception.getResponseBodyAsString()); LOGGER.info(error, exception); pzLogger.log(error, Severity.WARNING); determineExit(); } catch (Exception exception) { String error = String.format( "Unexpected Error occurred while trying to create Piazza Data Store: %s", exception.getMessage()); LOGGER.error(error, exception); pzLogger.log(error, Severity.ERROR); determineExit(); } } else { pzLogger.log("Could not create GeoServer Data Store. Could not load Request XML from local Resources.", Severity.ERROR); } }
From source file:com.projectx.mvc.servicehandler.quickregister.QuickRegisterHandler.java
@Override public EmailVerificationDetailsDTO getEmailVerificationDetailsByCustomerIdTypeAndEmail(Long customerId, Integer customerType, Integer emailType) throws EmailVerificationDetailNotFoundException { CustomerIdTypeEmailTypeDTO emailDTO = new CustomerIdTypeEmailTypeDTO(customerId, customerType, emailType); HttpEntity<CustomerIdTypeEmailTypeDTO> entity = new HttpEntity<CustomerIdTypeEmailTypeDTO>(emailDTO); ResponseEntity<EmailVerificationDetailsDTO> result = restTemplate.exchange( env.getProperty("rest.host") + "/customer/quickregister/getEmailVerificationDetails", HttpMethod.POST, entity, EmailVerificationDetailsDTO.class); if (result.getStatusCode() == HttpStatus.FOUND) return result.getBody(); else//from w ww . j a va 2 s. c om throw new EmailVerificationDetailNotFoundException(); }
From source file:org.appverse.web.framework.backend.test.util.frontfacade.mvc.tests.predefined.BasicAuthEndPointsServiceEnabledPredefinedTests.java
@Test public void simpleAuthenticationFlowTest() throws Exception { // Login first TestLoginInfo loginInfo = login();/*w ww . j a va 2 s . co m*/ // Calling protected remotelog service RemoteLogRequestVO logRequestVO = new RemoteLogRequestVO(); logRequestVO.setMessage("Test mesage!"); logRequestVO.setLogLevel("DEBUG"); HttpHeaders headers = new HttpHeaders(); headers.set("Cookie", loginInfo.getJsessionid()); HttpEntity<RemoteLogRequestVO> entityRemotelog = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers); UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl("http://localhost:" + port + baseApiPath + remoteLogEndpointPath); // Try without token first - It should be 'Forbidden' // http://springinpractice.com/2012/04/08/sending-cookies-with-resttemplate ResponseEntity<String> responseEntityRemotelog = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entityRemotelog, String.class); assertEquals(HttpStatus.FORBIDDEN, responseEntityRemotelog.getStatusCode()); // Try now with the CSRF token - It should work well // This implies passing JSESSIONID and CSRF Token headers.set(DEFAULT_CSRF_HEADER_NAME, loginInfo.getXsrfToken()); entityRemotelog = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers); responseEntityRemotelog = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entityRemotelog, String.class); assertEquals(HttpStatus.OK, responseEntityRemotelog.getStatusCode()); // Calling here logout builder = UriComponentsBuilder .fromHttpUrl("http://localhost:" + port + basicAuthenticationLogoutEndpointPath); HttpEntity<Void> entityLogout = new HttpEntity<Void>(headers); responseEntityRemotelog = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entityLogout, String.class); assertEquals(HttpStatus.OK, responseEntityRemotelog.getStatusCode()); // Try to call remotelog again (after logout) // This implies passing JSESSIONID and CSRF Token - We expect this not to work as the CSRF token has been removed and the session invalidated entityRemotelog = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers); responseEntityRemotelog = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entityRemotelog, String.class); assertEquals(HttpStatus.FORBIDDEN, responseEntityRemotelog.getStatusCode()); }
From source file:org.appverse.web.framework.backend.test.util.oauth2.tests.predefined.authorizationcode.Oauth2AuthorizationCodeFlowPredefinedTests.java
public void refreshToken() { UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(authServerBaseUrl + oauth2TokenEndpointPath); // Here we don't authenticate the user, we authenticate the client and we pass the authcode proving that the user has accepted and loged in builder.queryParam("grant_type", "refresh_token"); builder.queryParam("refresh_token", refreshToken); // Add Basic Authorization headers for CLIENT authentication (user was authenticated in previous request (authorization code) HttpHeaders headers = new HttpHeaders(); Encoder encoder = Base64.getEncoder(); headers.add("Authorization", "Basic " + encoder.encodeToString((getClientId() + ":" + getClientSecret()).getBytes())); HttpEntity<String> entity = new HttpEntity<>("", headers); ResponseEntity<OAuth2AccessToken> result2 = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entity, OAuth2AccessToken.class); assertEquals(HttpStatus.OK, result2.getStatusCode()); // Obtain and keep the token accessToken = result2.getBody().getValue(); assertNotNull(accessToken);/*from w w w . j a v a 2 s . c o m*/ refreshToken = result2.getBody().getRefreshToken().getValue(); assertNotNull(refreshToken); }
From source file:com.sitewhere.rest.service.SiteWhereClient.java
@Override public DeviceMeasurements createDeviceMeasurements(String assignmentToken, DeviceMeasurementsCreateRequest request) throws SiteWhereException { Map<String, String> vars = new HashMap<String, String>(); vars.put("token", assignmentToken); return sendRest(getBaseUrl() + "assignments/{token}/measurements", HttpMethod.POST, request, DeviceMeasurements.class, vars); }