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:org.client.one.service.OAuthAuthenticationService.java
public boolean registerUserIntranet(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(profile), headersA); ResponseEntity<String> responseUpdate = rest.exchange( oauthServerBaseURL + "/resources/profile/registerUser", HttpMethod.POST, request, String.class); JSONObject responseUpdateJSON = new JSONObject(responseUpdate.getBody()); return responseUpdateJSON.getBoolean("success"); }
From source file:com.goldengekko.meetr.itest.AuthITest.java
public static JConnection registerToken(RestTemplate restTemplate) { LinkedMultiValueMap<String, String> request = getOAuth2Request(); HttpEntity requestEntity = new HttpEntity(request, getHttpBasicHeader()); // register federated token first // JConnection fedResponse = restTemplate.postForObject(API_URL + "/federated/v11", // requestEntity, JConnection.class); ResponseEntity<JConnection> fedResponse = restTemplate.exchange(API_URL + "/federated/v11", HttpMethod.POST, requestEntity, JConnection.class); //assertEquals(HttpStatus.CREATED, fedResponse.getStatusCode()); assertNotNull("JConnection ", fedResponse.getBody()); return fedResponse.getBody(); }
From source file:com.orange.ngsi.client.RegisterContextRequestTest.java
@Test public void registerContextRequestOK_XML() throws Exception { ngsiClient.protocolRegistry.registerHost(baseUrl); String responseBody = xml(xmlConverter, createRegisterContextResponseTemperature()); this.mockServer.expect(requestTo(baseUrl + "/ngsi9/registerContext")).andExpect(method(HttpMethod.POST)) .andExpect(header("Content-Type", MediaType.APPLICATION_XML_VALUE)) .andExpect(header("Accept", MediaType.APPLICATION_XML_VALUE)) .andExpect(/*from ww w . j a v a2 s. c o m*/ xpath("registerContextRequest/contextRegistrationList/contextRegistration[*]").nodeCount(1)) .andExpect(xpath( "registerContextRequest/contextRegistrationList/contextRegistration/providingApplication") .string("http://localhost:1028/accumulate")) .andExpect(xpath( "registerContextRequest/contextRegistrationList/contextRegistration/entityIdList/entityId[*]") .nodeCount(1)) .andExpect(xpath( "registerContextRequest/contextRegistrationList/contextRegistration/entityIdList/entityId/id") .string("Room*")) .andExpect(xpath( "registerContextRequest/contextRegistrationList/contextRegistration/entityIdList/entityId/@type") .string("Room")) .andExpect(xpath( "registerContextRequest/contextRegistrationList/contextRegistration/entityIdList/entityId/@isPattern") .string("true")) .andExpect(xpath( "registerContextRequest/contextRegistrationList/contextRegistration/contextRegistrationAttributeList/contextRegistrationAttribute[*]") .nodeCount(1)) .andExpect(xpath( "registerContextRequest/contextRegistrationList/contextRegistration/contextRegistrationAttributeList/contextRegistrationAttribute/name") .string("temperature")) .andExpect(xpath( "registerContextRequest/contextRegistrationList/contextRegistration/contextRegistrationAttributeList/contextRegistrationAttribute/type") .string("float")) .andExpect(xpath( "registerContextRequest/contextRegistrationList/contextRegistration/contextRegistrationAttributeList/contextRegistrationAttribute/isDomain") .string("false")) .andExpect(xpath("registerContextRequest/duration").string("PT10S")) .andRespond(withSuccess(responseBody, MediaType.APPLICATION_XML)); RegisterContextResponse response = ngsiClient .registerContext(baseUrl, null, createRegisterContextTemperature()).get(); this.mockServer.verify(); Assert.assertNull(response.getErrorCode()); Assert.assertEquals("123456789", response.getRegistrationId()); Assert.assertEquals("PT10S", response.getDuration()); }
From source file:org.cloudfoundry.identity.uaa.login.feature.ImplicitGrantIT.java
@Test public void testInvalidScopes() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>(); postBody.add("client_id", "cf"); postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf"); postBody.add("response_type", "token"); postBody.add("source", "credentials"); postBody.add("username", testAccounts.getUserName()); postBody.add("password", testAccounts.getPassword()); postBody.add("scope", "read"); ResponseEntity<Void> responseEntity = restOperations.exchange(baseUrl + "/oauth/authorize", HttpMethod.POST, new HttpEntity<>(postBody, headers), Void.class); Assert.assertEquals(HttpStatus.FOUND, responseEntity.getStatusCode()); System.out.println(//from w w w. j a v a 2 s. c om "responseEntity.getHeaders().getLocation() = " + responseEntity.getHeaders().getLocation()); UriComponents locationComponents = UriComponentsBuilder.fromUri(responseEntity.getHeaders().getLocation()) .build(); Assert.assertEquals("uaa.cloudfoundry.com", locationComponents.getHost()); Assert.assertEquals("/redirect/cf", locationComponents.getPath()); MultiValueMap<String, String> params = parseFragmentParams(locationComponents); Assert.assertThat(params.getFirst("error"), is("invalid_scope")); Assert.assertThat(params.getFirst("access_token"), isEmptyOrNullString()); Assert.assertThat(params.getFirst("credentials"), isEmptyOrNullString()); }
From source file:org.appverse.web.framework.backend.test.util.oauth2.tests.predefined.authorizationcode.Oauth2AuthorizationCodeFlowPredefinedTests.java
@Test public void testRemoteLogIsProtected() throws Exception { RemoteLogRequestVO remoteLogRequest = new RemoteLogRequestVO(); remoteLogRequest.setLogLevel("DEBUG"); remoteLogRequest.setMessage("This is my log message!"); // We call remote log WITHOUT the access token HttpEntity<RemoteLogRequestVO> entity = new HttpEntity<RemoteLogRequestVO>(remoteLogRequest); UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(resourceServerBaseUrl + baseApiPath + remoteLogEndpointPath); ResponseEntity<String> result = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entity, String.class); assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode()); assertTrue("Wrong header: " + result.getHeaders(), result.getHeaders().getFirst("WWW-Authenticate").startsWith("Bearer realm=")); }
From source file:org.obiba.mica.core.service.MailService.java
private synchronized void sendEmail(String subject, String text, String recipient) { try {/*from www . j av a2 s . c om*/ RestTemplate template = newRestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.set(APPLICATION_AUTH_HEADER, getApplicationAuth()); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); String form = (Strings.isNullOrEmpty(recipient) ? "" : recipient + "&") + "subject=" + encode(subject, "UTF-8") + "&body=" + encode(text, "UTF-8"); HttpEntity<String> entity = new HttpEntity<>(form, headers); ResponseEntity<String> response = template.exchange(getNotificationsUrl(), HttpMethod.POST, entity, String.class); if (response.getStatusCode().is2xxSuccessful()) { log.info("Email sent via Agate"); } else { log.error("Sending email via Agate failed with status: {}", response.getStatusCode()); } } catch (Exception e) { log.error("Agate connection failure: {}", e.getMessage()); } }
From source file:org.trustedanalytics.h2oscoringengine.publisher.steps.AppRouteCreatingStepTest.java
@Test public void createAppRoute_noRouteFound_createNewRouteCfCallOccured() throws Exception { // given/* w w w.j av a 2 s. c o m*/ AppRouteCreatingStep step = new AppRouteCreatingStep(restTemplateMock, testCfApi, testAppGuid); // when when(domainsResponseMock.getBody()).thenReturn(validDomainsResponse); when(routesResponseMock.getBody()).thenReturn(noRouteResponse); when(routeCreatedResponseMock.getBody()).thenReturn(routeCreatedResponse); step.createAppRoute(testSpaceGuid, testSubdomain); // then verify(restTemplateMock).exchange(eq(testCfCreateRouteEndpoint), same(HttpMethod.POST), eq(HttpCommunication.postRequest(createRouteRequestBody)), same(String.class)); }
From source file:io.fabric8.che.starter.client.CheRestClient.java
@Async public void createProject(String cheServerURL, String workspaceId, String name, String repo, String branch) throws IOException { // Before we can create a project, we must start the new workspace startWorkspace(cheServerURL, workspaceId); // Poll until the workspace is started WorkspaceStatus status = checkWorkspace(cheServerURL, workspaceId); long currentTime = System.currentTimeMillis(); while (!WORKSPACE_STATUS_RUNNING.equals(status.getWorkspaceStatus()) && System.currentTimeMillis() < (currentTime + WORKSPACE_START_TIMEOUT_MS)) { try {// w w w . ja v a 2 s. c o m Thread.sleep(1000); } catch (InterruptedException e) { LOG.error("Error while polling for workspace status", e); break; } status = checkWorkspace(cheServerURL, workspaceId); } Workspace workspace = getWorkspaceByKey(cheServerURL, workspaceId); DevMachineServer server = workspace.getRuntime().getDevMachine().getRuntime().getServers().get("4401/tcp"); // Next we create a new project within the workspace String url = generateURL(server.getUrl(), CheRestEndpoints.CREATE_PROJECT, workspaceId); LOG.info("Creating project against workspace agent URL: {}", url); String jsonTemplate = projectTemplate.createRequest().setName(name).setRepo(repo).setBranch(branch) .getJSON(); RestTemplate template = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<String>(jsonTemplate, headers); ResponseEntity<Project[]> response = template.exchange(url, HttpMethod.POST, entity, Project[].class); if (response.getBody().length > 0) { Project p = response.getBody()[0]; LOG.info("Successfully created project {}", p.getName()); } else { LOG.info("There seems to have been a problem creating project {}", name); } }
From source file:com.orange.ngsi2.client.Ngsi2Client.java
/** * Create a new entity//from w ww . j a v a 2s . co m * @param entity the Entity to add * @return the listener to notify of completion */ public ListenableFuture<Void> addEntity(Entity entity) { return adapt(request(HttpMethod.POST, UriComponentsBuilder.fromHttpUrl(baseURL).path("v2/entities").toUriString(), entity, Void.class)); }
From source file:io.github.microcks.util.postman.PostmanTestStepsRunner.java
@Override public List<TestReturn> runTest(Service service, Operation operation, TestResult testResult, List<Request> requests, String endpointUrl, HttpMethod method) throws URISyntaxException, IOException { if (log.isDebugEnabled()) { log.debug("Launching test run on " + endpointUrl + " for " + requests.size() + " request(s)"); }/*w ww. j av a 2 s. c o m*/ if (endpointUrl.endsWith("/")) { endpointUrl = endpointUrl.substring(0, endpointUrl.length() - 1); } // Microcks-postman-runner interface object building. JsonNode jsonArg = mapper.createObjectNode(); ((ObjectNode) jsonArg).put("operation", operation.getName()); ((ObjectNode) jsonArg).put("callbackUrl", testsCallbackUrl + "/api/tests/" + testResult.getId() + "/testCaseResult"); // First we have to retrieved and add the test script for this operation from within Postman collection. JsonNode testScript = extractOperationTestScript(operation); if (testScript != null) { log.debug("Found a testScript for this operation !"); ((ObjectNode) jsonArg).set("testScript", testScript); } // Then we have to add the corresponding 'requests' objects. ArrayNode jsonRequests = mapper.createArrayNode(); for (Request request : requests) { JsonNode jsonRequest = mapper.createObjectNode(); String operationName = operation.getName().substring(operation.getName().indexOf(" ") + 1); String customizedEndpointUrl = endpointUrl + URIBuilder.buildURIFromPattern(operationName, request.getQueryParameters()); log.debug("Using customized endpoint url: " + customizedEndpointUrl); ((ObjectNode) jsonRequest).put("endpointUrl", customizedEndpointUrl); ((ObjectNode) jsonRequest).put("method", operation.getMethod()); ((ObjectNode) jsonRequest).put("name", request.getName()); if (request.getContent() != null && request.getContent().length() > 0) { ((ObjectNode) jsonRequest).put("body", request.getContent()); } if (request.getQueryParameters() != null && request.getQueryParameters().size() > 0) { ArrayNode jsonParams = buildQueryParams(request.getQueryParameters()); ((ObjectNode) jsonRequest).set("queryParams", jsonParams); } if (request.getHeaders() != null && request.getHeaders().size() > 0) { ArrayNode jsonHeaders = buildHeaders(request.getHeaders()); ((ObjectNode) jsonRequest).set("headers", jsonHeaders); } jsonRequests.add(jsonRequest); } ((ObjectNode) jsonArg).set("requests", jsonRequests); URI postmanRunnerURI = new URI(postmanRunnerUrl + "/tests/" + testResult.getId()); ClientHttpRequest httpRequest = clientHttpRequestFactory.createRequest(postmanRunnerURI, HttpMethod.POST); httpRequest.getBody().write(mapper.writeValueAsBytes(jsonArg)); httpRequest.getHeaders().add("Content-Type", "application/json"); // Actually execute request. ClientHttpResponse httpResponse = null; try { httpResponse = httpRequest.execute(); } catch (IOException ioe) { log.error("IOException while executing request ", ioe); } return new ArrayList<TestReturn>(); }