@Test public void testCss() throws Exception { ResponseEntity<String> entity = getRestTemplate().getForEntity("http://localhost:8080/css/bootstrap.min.css", String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody().contains("body")); }
@Test public void testCreateZoneWithNonUniqueSubdomain() { IdentityZone idZone1 = new IdentityZone(); String id1 = UUID.randomUUID().toString(); idZone1.setId(id1); idZone1.setSubdomain(id1 + "non-unique"); idZone1.setName("testCreateZone() " + id1); ResponseEntity<Void> response1 = client.exchange( serverRunning.getUrl("/identity-zones"), HttpMethod.POST, new HttpEntity<>(idZone1), new ParameterizedTypeReference<Void>() {}, id1); assertEquals(HttpStatus.CREATED, response1.getStatusCode()); IdentityZone idZone2 = new IdentityZone(); String id2 = UUID.randomUUID().toString(); idZone2.setId(id2); idZone2.setSubdomain(id1 + "non-unique"); idZone2.setName("testCreateZone() " + id2); ResponseEntity<Map<String, String>> response2 = client.exchange( serverRunning.getUrl("/identity-zones"), HttpMethod.POST, new HttpEntity<>(idZone2), new ParameterizedTypeReference<Map<String, String>>() {}, id2); assertEquals(HttpStatus.CONFLICT, response2.getStatusCode()); Assert.assertTrue( response2.getBody().get("error_description").toLowerCase().contains("subdomain")); }
private void getDCAppTerms() { final String url = "http://www.dcapp.org/rest/taxonomy_vocabulary/getTree"; MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>(); body.add("vid", "12"); ResponseEntity<TermList> responseEntity = null; HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "xml"))); HttpEntity<?> requestEntity = new HttpEntity<Object>(body, requestHeaders); TermList termlist = null; try { RestTemplate restTemplate = new DCAppRestTemplate(10 * 1000); SimpleXmlHttpMessageConverter converter = new SimpleXmlHttpMessageConverter(); HttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter(); HttpMessageConverter stringHttpMessageConverternew = new StringHttpMessageConverter(); restTemplate.getMessageConverters().add(converter); restTemplate.getMessageConverters().add(formHttpMessageConverter); restTemplate.getMessageConverters().add(stringHttpMessageConverternew); responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, TermList.class); termlist = responseEntity.getBody(); } catch (RestClientException e) { Log.e("DirectoryFragment", "Exception while retrieving terms listing.", e.getCause()); } if (termlist != null) { termlist.setIsParent(); DCAppApplication app = (DCAppApplication) getApplication(); app.setTermList(termlist); } }
@Test public void test_createConferenceRoom_returns_BAD_REQUEST() { ConferenceRoom room = ConferenceRoomFixture.createConferenceRoom(); doThrow(new ValidationException("")).when(conferenceRoomValidator).validate(room); ResponseEntity<String> response = controller.createConferenceRoom(room); assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); }
/** * POST /users : Creates a new user. * * <p>Creates a new user if the login and email are not already used, and sends an mail with an * activation link. The user needs to be activated on creation. * * @param managedUserVM the user to create * @return the ResponseEntity with status 201 (Created) and with body the new user, or with status * 400 (Bad Request) if the login or email is already in use * @throws URISyntaxException if the Location URI syntax is incorrect */ @PostMapping("/users") @Timed @Secured(AuthoritiesConstants.ADMIN) public ResponseEntity<?> createUser(@RequestBody ManagedUserVM managedUserVM) throws URISyntaxException { log.debug("REST request to save User : {}", managedUserVM); // Lowercase the user login before comparing with database if (userRepository.findOneByLogin(managedUserVM.getLogin().toLowerCase()).isPresent()) { return ResponseEntity.badRequest() .headers( HeaderUtil.createFailureAlert("userManagement", "userexists", "Login already in use")) .body(null); } else if (userRepository.findOneByEmail(managedUserVM.getEmail()).isPresent()) { return ResponseEntity.badRequest() .headers( HeaderUtil.createFailureAlert( "userManagement", "emailexists", "Email already in use")) .body(null); } else { User newUser = userService.createUser(managedUserVM); mailService.sendCreationEmail(newUser); return ResponseEntity.created(new URI("/api/users/" + newUser.getLogin())) .headers(HeaderUtil.createAlert("userManagement.created", newUser.getLogin())) .body(newUser); } }
/** * @name UnBindUsers * @description this method is used to unbind all user which is created at the time of binding for * the service from bugzilla * @param matchName * @return boolean */ private boolean UnBindUsers(String matchName) { try { setProperties(); url = new URI( REST_GET_USER_BY_MATCH + "?match=" + matchName + "&Bugzilla_api_key=" + BUGZILLA_API_KEY); HttpEntity<?> requestEntity = new HttpEntity<Object>(createHeaders()); ResponseEntity<String> responseEntity = getRestTemplate().exchange(url, HttpMethod.GET, requestEntity, String.class); ObjectMapper mapper = new ObjectMapper(); BugzillaUser bugzillaUser = mapper.readValue(responseEntity.getBody(), BugzillaUser.class); if (bugzillaUser.getUsers() != null && bugzillaUser.getUsers().size() != 0) { for (BugzillaUser user : bugzillaUser.getUsers()) { blockUser(user.getId()); } } } catch (Exception e) { e.printStackTrace(); } return false; }
@Test public void shouldGetInventoryById() throws Exception { EquipmentInventory inventory = new EquipmentInventory(); when(service.getInventoryById(1L)).thenReturn(inventory); ResponseEntity<OpenLmisResponse> response = controller.getInventory(1L); assertThat(inventory, is(response.getBody().getData().get("inventory"))); }
/** * Call recurly API. * * @param <T> the generic type * @param <E> the element type * @param path the path * @param payload the payload * @param responseClass the response class * @param method the method * @param headers the headers * @return the t * @throws RecurlyException the recurly exception */ protected <T, E> T call( String path, E payload, Class<T> responseClass, HttpMethod method, HttpHeaders headers) throws RecurlyException { URI uri = null; ResponseEntity<T> responseEntity = null; T reponse = null; HttpEntity<?> entity = null; try { if (headers == null) { entity = new HttpEntity<>(payload, recurly.getRecurlyHeaders()); } else { entity = new HttpEntity<>(payload, headers); } uri = new URI(URIUtil.encodeQuery(recurly.getRecurlyServerURL() + path, "UTF-8")); getLogger().debug("Calling Recurly URL {}, method: {}", uri.toString(), method.toString()); responseEntity = restTemplate.exchange(uri, method, entity, responseClass); if (responseEntity != null) reponse = responseEntity.getBody(); } catch (URIException | UnsupportedEncodingException | URISyntaxException e) { throw new RecurlyException("Not able to reach recurly. Please check the URL.", e); } catch (RestClientException e) { String err = ((HttpStatusCodeException) e).getResponseBodyAsString(); int code = ((HttpStatusCodeException) e).getStatusCode().value(); publishError(uri.toString(), err, code); RecurlyException ex = handleError(err, code, e); throw ex; } return reponse; }
@Test public void ok() { ResponseEntity<String> entity = this.restTemplate.getForEntity( "http://localhost:" + this.port + "/hello" + "/ok", String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); }
@Test public void postTest() throws RestClientException, URISyntaxException { String url = dirFrontEnd + "/empresa/"; String acceptHeaderValue = "application/json"; HttpHeaders requestHeaders = new HttpHeaders(); List<MediaType> mediaTypes = new ArrayList<MediaType>(); mediaTypes.add(MediaType.valueOf(acceptHeaderValue)); requestHeaders.setAccept(mediaTypes); requestHeaders.setContentType(MediaType.valueOf(acceptHeaderValue)); HttpMethod post = HttpMethod.POST; String body = "{\"nif\":\"nifPrueba\",\"nombre\":\"nombrePrueba\",\"direccionFiscal\":\"DirPrueba\",\"fechaInicioActividades\":\"2014-01-10\",\"version\":\"0\"}"; HttpEntity<String> entity = new HttpEntity<String>(body, requestHeaders); ResponseEntity<String> response = restTemplate.exchange(url, post, entity, String.class); assertTrue(response.getStatusCode().equals(HttpStatus.CREATED)); String nombreEmpresa = (String) jdbcTemplate.queryForObject( "SELECT NOMBRE FROM EMPRESA WHERE NIF= ?", new Object[] {"nifPrueba"}, String.class); assertTrue(nombreEmpresa.equals("nombrePrueba")); }
@Override protected Object doInBackground(Object[] params) { try { RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); HttpHeaders requestHeaders = new HttpHeaders(); String restUrl = ServerConstants.SERVER_API_URL + "user/login"; User user = new User(username, password); SingleUser singleUser = new SingleUser(); singleUser.setUser(user); HttpEntity<SingleUser> requestEntity = new HttpEntity<>(singleUser, requestHeaders); ResponseEntity<Boolean> responseEntity = restTemplate.exchange(restUrl, HttpMethod.POST, requestEntity, Boolean.class); boolean loginSuccessful = responseEntity.getBody(); Log.d("Login", Boolean.toString(loginSuccessful)); return loginSuccessful; } catch (Exception ex) { ex.printStackTrace(); return false; } }
@Test public void putTest() throws RestClientException, URISyntaxException { String url = dirFrontEnd + "/empresa/nifPrueba"; String acceptHeaderValue = "application/json"; HttpHeaders requestHeaders = new HttpHeaders(); List<MediaType> mediaTypes = new ArrayList<MediaType>(); mediaTypes.add(MediaType.valueOf(acceptHeaderValue)); requestHeaders.setAccept(mediaTypes); requestHeaders.setContentType(MediaType.valueOf(acceptHeaderValue)); HttpMethod put = HttpMethod.PUT; String body = "{\"nombre\":\"nombrePruebaModificado\"}"; HttpEntity<String> entity = new HttpEntity<String>(body, requestHeaders); ResponseEntity<String> response = restTemplate.exchange(url, put, entity, String.class); assertTrue(response.getStatusCode().equals(HttpStatus.NO_CONTENT)); String nombreEmpresa = (String) jdbcTemplate.queryForObject( "SELECT NOMBRE FROM EMPRESA WHERE NIF= ?", new Object[] {"nifPrueba"}, String.class); assertTrue(nombreEmpresa.equals("nombrePruebaModificado")); }
@Bean public Token getToken() { Token token; String creds = authUser + ":" + authPassword; byte[] credsBytes = creds.getBytes(); byte[] credsB64 = Base64.getEncoder().encode(credsBytes); String credsStr = new String(credsB64); HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", "Basic " + credsStr); headers.add("Content-Type", "application/x-www-form-urlencoded"); headers.add("Accept", "application/json"); headers.add("Accept-Charset", "UTF-8"); // не работает ! HttpEntity<String> request = new HttpEntity<String>(authParam, headers); log.info("Request token from server..."); try { ResponseEntity resp = rest.exchange(authUri, HttpMethod.POST, request, Token.class); token = (Token) (resp.getBody()); } catch (HttpClientErrorException e) { log.error(e.getMessage()); token = new Token(); } log.debug("Token=" + token.access_token); log.info("End of request token from server..."); return token; }
@Test public void find() { HttpHeaders headers = new HttpHeaders(); final HttpEntity<String> request = new HttpEntity<String>(headers); RestClient client = new RestClient(); client.setApplicationPath(""); String url = client.login("robin", "password"); System.out.println(url); ResponseEntity<Currency[]> response = client .template() .exchange(client.apiUrl("currency"), HttpMethod.GET, request, Currency[].class); System.out.println("Response -->" + response.getBody()); final Currency[] currency = response.getBody(); if (currency != null) { System.out.println("Total currency Found " + currency.length); } for (int i = 0; i < currency.length; i++) { Assertions.assertThat(currency[i]).isNotNull(); } }
/** * @name createBugzillaUser * @description this method is used to create user for bugzilla at the time of binding as the name * as [email protected] as the service id is used to create the product and group so by * default this user will associate that group and product * @param serviceInstance * @return */ public BugzillaUser createBugzillaUser(ServiceInstance serviceInstance) { String userMailId = "admin@" + serviceInstance.getId() + ".com"; final String password = generatePassword(); BugzillaUser bugzillaUser = new BugzillaUser(); setProperties(); try { url = new URI(REST_CREATE_USER_URL); MultiValueMap<String, String> userData = new LinkedMultiValueMap<String, String>(); userData.add("email", userMailId); // a valid email required userData.add("full_name", userMailId); userData.add("password", password); HttpEntity<?> requestEntity = new HttpEntity<Object>(userData, createHeaders()); ResponseEntity<String> responseEntity = getRestTemplate().exchange(url, HttpMethod.POST, requestEntity, String.class); ObjectMapper mapper = new ObjectMapper(); bugzillaUser = mapper.readValue(responseEntity.getBody(), BugzillaUser.class); if (bugzillaUser.getId() != null) { bugzillaUser.setEmail(userMailId); bugzillaUser.setPassword(password); } logger.info("Bugzilla User Created " + bugzillaUser.getId()); updateBugzillaUserAsAdmin(bugzillaUser); createComponent(serviceInstance.getId()); } catch (Exception e) { e.printStackTrace(); } return bugzillaUser; }
@RequestMapping("/{userPseudo}/validateStep4") public ResponseEntity<Void> validateStep4( @PathVariable("userPseudo") String userPseudo, @RequestParam("userHostAndPort") String userHostAndPort) { log.info("Validation step 4 for player {} with data {}", userPseudo, userHostAndPort); ResponseEntity<Void> result = new ResponseEntity<Void>(HttpStatus.BAD_REQUEST); String url = "http://" + userHostAndPort + "/zen/env"; ResponseEntity<String> responseEntityShouldFail = restTemplate.exchange( url, HttpMethod.GET, new HttpEntity<>(new HttpHeaders()), String.class); byte[] encodedAuth = Base64.encodeBase64("zenika:technozaure".getBytes()); String authHeader = "Basic " + new String(encodedAuth); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.set("Authorization", authHeader); HttpEntity<String> entity = new HttpEntity<>(headers); ResponseEntity<String> responseEntityShouldSucceed = restTemplate.exchange(url, HttpMethod.GET, entity, String.class); if (responseEntityShouldFail.getStatusCode() != HttpStatus.OK && responseEntityShouldSucceed.getStatusCode() == HttpStatus.OK) { gameStepRepository.save(new GameStep(userPseudo, Step._4)); result = new ResponseEntity<Void>(HttpStatus.OK); broadcastGameStatus(); } return result; }
public Boolean updateBugzillaUserAsAdmin(BugzillaUser bugzillaUser) { setProperties(); try { url = new URI( REST_UPDATE_USER_URL + bugzillaUser.getEmail() + "?Bugzilla_api_key=" + BUGZILLA_API_KEY); System.out.println("in update group " + url.toASCIIString()); String userdate = "{\"name\" : \"" + bugzillaUser.getEmail() + "\", \"groups\" : { \"set\" : [\"admin\"] }}"; HttpEntity<?> requestEntity = new HttpEntity<Object>(userdate, createHeaders()); System.out.println(userdate); ResponseEntity<String> responseEntity = getRestTemplate().exchange(url, HttpMethod.PUT, requestEntity, String.class); if (responseEntity.getBody() != null) { return true; } } catch (Exception e) { e.printStackTrace(); } return false; }
@Test public void testFreeMarkerTemplate() throws Exception { ResponseEntity<String> entity = new TestRestTemplate().getForEntity("http://localhost:8080", String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody().contains("Hello, Andy")); }
@Test public void testHome() throws Exception { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = getRestTemplate().getForEntity("http://localhost:" + port, Map.class); assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode()); }
/** POST /newss -> Create a new news. */ @RequestMapping( value = "/newss", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<News> createNews(@Valid @RequestBody News news) throws URISyntaxException { log.debug("REST request to save News : {}", news); if (news.getId() != null) { return ResponseEntity.badRequest() .headers( HeaderUtil.createFailureAlert( "news", "idexists", "A new news cannot already have an ID")) .body(null); } News result = newsRepository.save(news); List<Subscription> subscriptions = subscriptionRepository .findAll() .stream() .filter(item -> (item.getIdMarketPlace().equals(result.getMarketPlace().getId()))) .collect(Collectors.toList()); String title = result.getMarketPlace().getName() + " vous a envoyé une News !"; String content = result.getTitle() + "\n\n\n" + result.getContent(); for (Subscription subscription : subscriptions) { mailService.sendEmail(subscription.getUser().getEmail(), title, content, false, false); } return ResponseEntity.created(new URI("/api/newss/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert("news", result.getId().toString())) .body(result); }
@Test public void test_createConferenceRoom_returns_CREATED() { ConferenceRoom room = ConferenceRoomFixture.createConferenceRoom(); ResponseEntity<String> response = controller.createConferenceRoom(room); assertEquals("Conference room created.", response.getBody()); assertEquals(HttpStatus.CREATED, response.getStatusCode()); }
@Test public void testVelocityTemplate() throws Exception { ResponseEntity<String> entity = new TestRestTemplate().getForEntity("http://localhost:" + this.port, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("Hello, Andy"); }
/** * PUT /users : Updates an existing User. * * @param managedUserVM the user to update * @return the ResponseEntity with status 200 (OK) and with body the updated user, or with status * 400 (Bad Request) if the login or email is already in use, or with status 500 (Internal * Server Error) if the user couldn't be updated */ @PutMapping("/users") @Timed @Secured(AuthoritiesConstants.ADMIN) public ResponseEntity<ManagedUserVM> updateUser(@RequestBody ManagedUserVM managedUserVM) { log.debug("REST request to update User : {}", managedUserVM); Optional<User> existingUser = userRepository.findOneByEmail(managedUserVM.getEmail()); if (existingUser.isPresent() && (!existingUser.get().getId().equals(managedUserVM.getId()))) { return ResponseEntity.badRequest() .headers( HeaderUtil.createFailureAlert( "userManagement", "emailexists", "E-mail already in use")) .body(null); } existingUser = userRepository.findOneByLogin(managedUserVM.getLogin().toLowerCase()); if (existingUser.isPresent() && (!existingUser.get().getId().equals(managedUserVM.getId()))) { return ResponseEntity.badRequest() .headers( HeaderUtil.createFailureAlert("userManagement", "userexists", "Login already in use")) .body(null); } userService.updateUser( managedUserVM.getId(), managedUserVM.getLogin(), managedUserVM.getFirstName(), managedUserVM.getLastName(), managedUserVM.getEmail(), managedUserVM.isActivated(), managedUserVM.getLangKey(), managedUserVM.getAuthorities()); return ResponseEntity.ok() .headers(HeaderUtil.createAlert("userManagement.updated", managedUserVM.getLogin())) .body(new ManagedUserVM(userService.getUserWithAuthorities(managedUserVM.getId()))); }
@Test public void testHome() throws Exception { ResponseEntity<String> entity = new TestRestTemplate().getForEntity("http://localhost:" + this.port, String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals("Hello World", entity.getBody()); }
public void logout(String user) { logger.debug("logging out account with userId: " + user); ResponseEntity<?> response = restTemplate.getForEntity("http://accounts/logout/{user}", String.class, user); logger.debug("Logout response: " + response.getStatusCode()); }
@Override protected Message doInBackground(Void... params) { final String url = getString(R.string.base_uri) + "/getmessage"; // Populate the HTTP Basic Authentitcation header with the username and password HttpAuthentication authHeader = new HttpBasicAuthentication(username, password); HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setAuthorization(authHeader); requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); // Create a new RestTemplate instance RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter()); try { // Make the network request Log.d(TAG, url); ResponseEntity<Message> response = restTemplate.exchange( url, HttpMethod.GET, new HttpEntity<Object>(requestHeaders), Message.class); return response.getBody(); } catch (HttpClientErrorException e) { Log.e(TAG, e.getLocalizedMessage(), e); return new Message(0, e.getStatusText(), e.getLocalizedMessage()); } catch (ResourceAccessException e) { Log.e(TAG, e.getLocalizedMessage(), e); return new Message(0, e.getClass().getSimpleName(), e.getLocalizedMessage()); } }
private TermList getTermlist() { // TODO Auto-generated method stub MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>(); ResponseEntity<TermList> responseEntity = null; HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "xml"))); HttpEntity<?> requestEntity = new HttpEntity<Object>(body, requestHeaders); String newurl = "http://www.dcapp.org/export/category.xml"; try { RestTemplate restTemplate = new DCAppRestTemplate(10000); SimpleXmlHttpMessageConverter converter = new SimpleXmlHttpMessageConverter(); HttpMessageConverter<?> formHttpMessageConverter = new FormHttpMessageConverter(); HttpMessageConverter<?> stringHttpMessageConverternew = new StringHttpMessageConverter(); restTemplate.getMessageConverters().add(converter); restTemplate.getMessageConverters().add(formHttpMessageConverter); restTemplate.getMessageConverters().add(stringHttpMessageConverternew); // responseEntity = restTemplate.exchange(this.url, HttpMethod.POST, requestEntity, // TermList.class); responseEntity = restTemplate.exchange(newurl, HttpMethod.GET, requestEntity, TermList.class); } catch (RestClientException e) { Log.e("DirectoryFragment", "Exception while retrieving terms listing.", e.getCause()); } TermList terms = responseEntity.getBody(); terms.setIsParent(); return terms; }
/** * @name createProduct * @description Method is used in provisioning of service to create the product for bugzilla by * taking the service_instance as a name whenever the product is created at the same time with * same name the group for that product is created by bugzilla internally * @param productName * @return Product * @throws IOException */ public Product createProduct(String productName) throws IOException { if (getBugzillaProduct(productName).getProducts() != null && getBugzillaProduct(productName).getProducts().size() != 0) { updateProductGroup(productName); return getBugzillaProduct(productName).getProducts().get(0); } Product bugzillaProduct = new Product(); setProperties(); try { logger.info( "Bugzilla getBugzillaResource().getBugzillaServer() " + getBugzillaResource().getBugzillaServer()); url = new URI(REST_PRODUCT_URL); MultiValueMap<String, String> productData = new LinkedMultiValueMap<String, String>(); productData.add("name", productName); productData.add("description", productName + " as description"); productData.add("version", "1.0"); HttpEntity<?> requestEntity = new HttpEntity<Object>(productData, createHeaders()); ResponseEntity<String> responseEntity = getRestTemplate().exchange(url, HttpMethod.POST, requestEntity, String.class); ObjectMapper mapper = new ObjectMapper(); bugzillaProduct = mapper.readValue(responseEntity.getBody(), Product.class); logger.info("Bugzilla Product Created " + bugzillaProduct.getId()); if (bugzillaProduct.getId() != null) { bugzillaProduct = getBugzillaProduct(productName).getProducts().get(0); updateProductGroup(productName); } } catch (Exception e) { e.printStackTrace(); } return bugzillaProduct; }
private void verifyAuthentication(ClientDetails config, HttpStatus finalStatus) { String baseUrl = "http://localhost:" + this.context.getEmbeddedServletContainer().getPort(); RestTemplate rest = new TestRestTemplate(); // First, verify the web endpoint can't be reached assertEndpointUnauthorized(baseUrl, rest); // Since we can't reach it, need to collect an authorization token HttpHeaders headers = getHeaders(config); String url = baseUrl + "/oauth/token"; JsonNode tokenResponse = rest.postForObject( url, new HttpEntity<MultiValueMap<String, Object>>(getBody(), headers), JsonNode.class); String authorizationToken = tokenResponse.findValue("access_token").asText(); String tokenType = tokenResponse.findValue("token_type").asText(); String scope = tokenResponse.findValues("scope").get(0).toString(); assertThat(tokenType, equalTo("bearer")); assertThat(scope, equalTo("\"read\"")); // Now we should be able to see that endpoint. headers.set("Authorization", "BEARER " + authorizationToken); ResponseEntity<String> securedResponse = rest.exchange( new RequestEntity<Void>(headers, HttpMethod.GET, URI.create(baseUrl + "/securedFind")), String.class); assertThat(securedResponse.getStatusCode(), equalTo(HttpStatus.OK)); assertThat( securedResponse.getBody(), equalTo("You reached an endpoint " + "secured by Spring Security OAuth2")); ResponseEntity<String> entity = rest.exchange( new RequestEntity<Void>(headers, HttpMethod.POST, URI.create(baseUrl + "/securedSave")), String.class); assertThat(entity.getStatusCode(), equalTo(finalStatus)); }
/** POST /evolutionPrescriptions -> Create a new evolutionPrescription. */ @RequestMapping( value = "/episodes/{episode_id}/evolutionPrescriptions", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<EvolutionPrescription> createByEpisode( @PathVariable(value = "episode_id") Long episodeId, @RequestBody EvolutionPrescription evolutionPrescription) throws URISyntaxException { log.debug("REST request to save EvolutionPrescription : {}", evolutionPrescription); if (evolutionPrescription.getId() != null) { return ResponseEntity.badRequest() .header("Failure", "A new evolutionPrescription cannot already have an ID") .body(null); } Episode episode = new Episode(); episode.setId(episodeId); evolutionPrescription.setEpisode(episode); EvolutionPrescription result = evolutionPrescriptionRepository.save(evolutionPrescription); return ResponseEntity.created( new URI("/api/episodes/" + episodeId + "/evolutionPrescriptions/" + result.getId())) .headers( HeaderUtil.createEntityCreationAlert( "evolutionPrescription", result.getId().toString())) .body(result); }