@BeforeClass public static void beforeClass() throws Exception { jettyServer = new Server(0); WebAppContext webApp = new WebAppContext(); webApp.setServer(jettyServer); webApp.setContextPath(CONTEXT_PATH); webApp.setWar("src/test/webapp"); jettyServer.setHandler(webApp); jettyServer.start(); serverPort = ((ServerConnector)jettyServer.getConnectors()[0]).getLocalPort(); testRestTemplate = new TestRestTemplate(new RestTemplateBuilder() .rootUri("http://localhost:" + serverPort + CONTEXT_PATH)); }
@Test public void testPushTaupageLog() throws Exception { final TestRestTemplate restOperations = new TestRestTemplate(CORRECT_USER, CORRECT_PASSWORD); stubFor(post(urlPathEqualTo("/api/instance-logs")).willReturn(aResponse().withStatus(201))); final URI url = URI.create("http://localhost:" + port + "/instance-logs"); final ResponseEntity<String> response = restOperations.exchange( RequestEntity.post(url).contentType(APPLICATION_JSON).body( instanceLogsPayload), String.class); assertThat(response.getStatusCode()).isEqualTo(CREATED); log.debug("Waiting for async tasks to finish"); TimeUnit.SECONDS.sleep(1); verify(postRequestedFor(urlPathEqualTo("/api/instance-logs")) .withRequestBody(equalToJson(intanceLogsJsonPayload)) .withHeader(AUTHORIZATION, equalTo("Bearer 1234567890"))); verify(putRequestedFor(urlPathEqualTo("/events/" + eventID)) .withRequestBody(equalToJson(new String(auditTrailJsonPayload))) .withHeader(AUTHORIZATION, equalTo("Bearer 1234567890"))); log.info("METRICS:\n{}", restOperations.getForObject("http://localhost:" + managementPort + "/metrics", String.class)); }
@Test public void getJwtTokenByImplicitGrant() throws JsonParseException, JsonMappingException, IOException { String redirectUrl = "http://localhost:"+port+"/resources/user"; ResponseEntity<String> response = new TestRestTemplate("user","password").postForEntity("http://localhost:" + port + "oauth/authorize?response_type=token&client_id=normal-app&redirect_uri={redirectUrl}", null, String.class,redirectUrl); assertEquals(HttpStatus.OK, response.getStatusCode()); List<String> setCookie = response.getHeaders().get("Set-Cookie"); String jSessionIdCookie = setCookie.get(0); String cookieValue = jSessionIdCookie.split(";")[0]; HttpHeaders headers = new HttpHeaders(); headers.add("Cookie", cookieValue); response = new TestRestTemplate("user","password").postForEntity("http://localhost:" + port + "oauth/authorize?response_type=token&client_id=normal-app&redirect_uri={redirectUrl}&user_oauth_approval=true&authorize=Authorize", new HttpEntity<>(headers), String.class, redirectUrl); assertEquals(HttpStatus.FOUND, response.getStatusCode()); assertNull(response.getBody()); String location = response.getHeaders().get("Location").get(0); //FIXME: Is this a bug with redirect URL? location = location.replace("#", "?"); response = new TestRestTemplate().getForEntity(location, String.class); assertEquals(HttpStatus.OK, response.getStatusCode()); }
@SuppressWarnings({"rawtypes", "unchecked"}) @Test public void getJwtTokenByClientCredentialForUser() throws JsonParseException, JsonMappingException, IOException { ResponseEntity<String> response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?grant_type=password&username=user&password=password", null, String.class); String responseText = response.getBody(); assertEquals(HttpStatus.OK, response.getStatusCode()); HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class); assertEquals("bearer", jwtMap.get("token_type")); assertEquals("read write", jwtMap.get("scope")); assertTrue(jwtMap.containsKey("access_token")); assertTrue(jwtMap.containsKey("expires_in")); assertTrue(jwtMap.containsKey("jti")); String accessToken = (String) jwtMap.get("access_token"); Jwt jwtToken = JwtHelper.decode(accessToken); String claims = jwtToken.getClaims(); HashMap claimsMap = new ObjectMapper().readValue(claims, HashMap.class); assertEquals("spring-boot-application", ((List<String>) claimsMap.get("aud")).get(0)); assertEquals("trusted-app", claimsMap.get("client_id")); assertEquals("user", claimsMap.get("user_name")); assertEquals("read", ((List<String>) claimsMap.get("scope")).get(0)); assertEquals("write", ((List<String>) claimsMap.get("scope")).get(1)); assertEquals("ROLE_USER", ((List<String>) claimsMap.get("authorities")).get(0)); }
@SuppressWarnings({"rawtypes", "unchecked"}) @Test public void getJwtTokenByClientCredentialForAdmin() throws JsonParseException, JsonMappingException, IOException { ResponseEntity<String> response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?grant_type=password&username=admin&password=password", null, String.class); String responseText = response.getBody(); assertEquals(HttpStatus.OK, response.getStatusCode()); HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class); assertEquals("bearer", jwtMap.get("token_type")); assertEquals("read write", jwtMap.get("scope")); assertTrue(jwtMap.containsKey("access_token")); assertTrue(jwtMap.containsKey("expires_in")); assertTrue(jwtMap.containsKey("jti")); String accessToken = (String) jwtMap.get("access_token"); Jwt jwtToken = JwtHelper.decode(accessToken); String claims = jwtToken.getClaims(); HashMap claimsMap = new ObjectMapper().readValue(claims, HashMap.class); assertEquals("spring-boot-application", ((List<String>) claimsMap.get("aud")).get(0)); assertEquals("trusted-app", claimsMap.get("client_id")); assertEquals("admin", claimsMap.get("user_name")); assertEquals("read", ((List<String>) claimsMap.get("scope")).get(0)); assertEquals("write", ((List<String>) claimsMap.get("scope")).get(1)); assertEquals("ROLE_ADMIN", ((List<String>) claimsMap.get("authorities")).get(0)); }
@Test public void accessProtectedResourceByJwtTokenForUser() throws JsonParseException, JsonMappingException, IOException { ResponseEntity<String> response = new TestRestTemplate().getForEntity("http://localhost:" + port + "/resources/user", String.class); assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?grant_type=password&username=user&password=password", null, String.class); String responseText = response.getBody(); assertEquals(HttpStatus.OK, response.getStatusCode()); HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class); String accessToken = (String) jwtMap.get("access_token"); HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Bearer " + accessToken); response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/user", HttpMethod.GET, new HttpEntity<>(null, headers), String.class); assertEquals(HttpStatus.OK, response.getStatusCode()); response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/principal", HttpMethod.GET, new HttpEntity<>(null, headers), String.class); assertEquals("user", response.getBody()); response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/roles", HttpMethod.GET, new HttpEntity<>(null, headers), String.class); assertEquals("[{\"authority\":\"ROLE_USER\"}]", response.getBody()); }
@Test public void accessProtectedResourceByJwtTokenForAdmin() throws JsonParseException, JsonMappingException, IOException { ResponseEntity<String> response = new TestRestTemplate().getForEntity("http://localhost:" + port + "/resources/admin", String.class); assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?grant_type=password&username=admin&password=password", null, String.class); String responseText = response.getBody(); assertEquals(HttpStatus.OK, response.getStatusCode()); HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class); String accessToken = (String) jwtMap.get("access_token"); HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Bearer " + accessToken); response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/admin", HttpMethod.GET, new HttpEntity<>(null, headers), String.class); assertEquals(HttpStatus.OK, response.getStatusCode()); response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/principal", HttpMethod.GET, new HttpEntity<>(null, headers), String.class); assertEquals("admin", response.getBody()); response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/roles", HttpMethod.GET, new HttpEntity<>(null, headers), String.class); assertEquals("[{\"authority\":\"ROLE_ADMIN\"}]", response.getBody()); }
@Test public void dashboardLoads() { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/dashboard", String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); String body = entity.getBody(); // System.err.println(body); assertTrue(body.contains("eureka/js")); assertTrue(body.contains("eureka/css")); // The "DS Replicas" assertTrue( body.contains("<a href=\"http://localhost:8761/eureka/\">localhost</a>")); // The Home assertTrue(body.contains("<a href=\"/dashboard\">Home</a>")); // The Lastn assertTrue(body.contains("<a href=\"/dashboard/lastn\">Last")); }
@Test(timeout = 180000) public void testTraces() throws Exception { waitForAppsToStart(); String uri = "http://localhost:" + shoppingCart.port() + "/checkout"; TestRestTemplate restTemplate = new TestRestTemplate(); ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class); assertEquals("{\"message\":\"order processed successfully\"}", response.getBody()); Trace shoppingCartTrace = shoppingCart.getTrace(); Trace ordersTrace = orders.getTrace(); Trace paymentsTrace = payments.getTrace(); assertThat(paymentsTrace.getTraceId()).isEqualTo(shoppingCartTrace.getTraceId()); assertThat(ordersTrace.getTraceId()).isEqualTo(shoppingCartTrace.getTraceId()); assertThat(paymentsTrace.getParentSpanId()).isEqualTo(ordersTrace.getSpanId()); assertThat(ordersTrace.getParentSpanId()).isEqualTo(shoppingCartTrace.getSpanId()); assertThat(shoppingCartTrace.getSpanId()).isNotEqualTo(ordersTrace.getSpanId()); assertThat(ordersTrace.getSpanId()).isNotEqualTo(paymentsTrace.getSpanId()); }
@Test public void testPassword() throws IOException { String tokenUrl = authUrlPrefix + "/oauth/token?client_id=" + clientId + "&client_secret=" + clientSecret + "&grant_type=password&username=" + username + "&password=" + password; HttpHeaders headers1 = null; //headers1 = AuthorizationUtil.basic("admin","admin"); ResponseEntity<String> response = new TestRestTemplate().postForEntity(tokenUrl, null, String.class); assertEquals(HttpStatus.OK, response.getStatusCode()); HashMap map = new ObjectMapper().readValue(response.getBody(), HashMap.class); String accessToken = (String) map.get("access_token"); String refreshToken = (String) map.get("refresh_token"); System.out.println("Token Info:" + map.toString()); HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Bearer " + accessToken); response = new TestRestTemplate().exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(null, headers), String.class); assertEquals(HttpStatus.OK, response.getStatusCode()); assertEquals("secure", new ObjectMapper().readValue(response.getBody(), HashMap.class).get("content")); refreshToken(refreshToken); }
@Test public void testImplicit() throws IOException { unauthorizedRequest(); String authUrl = authBasicUrlPrefix + "/oauth/authorize?response_type=token&client_id=" + clientId + "&redirect_uri=" + resourceUrl; HttpHeaders headers1 = null; headers1 = AuthorizationUtil.basic("admin", "admin"); ResponseEntity<String> response = new TestRestTemplate().postForEntity(authUrl, new HttpEntity<>(headers1), null, String.class); assertEquals(HttpStatus.OK, response.getStatusCode()); String cookieValue = response.getHeaders().get("Set-Cookie").get(0).split(";")[0]; HttpHeaders headers = new HttpHeaders(); headers.add("Cookie", cookieValue); authUrl = authUrlPrefix + "/oauth/authorize?user_oauth_approval=true&scope.read=true"; response = new TestRestTemplate().postForEntity(authUrl, new HttpEntity<>(headers), String.class); assertEquals(HttpStatus.FOUND, response.getStatusCode()); String location = response.getHeaders().get("Location").get(0).replace("#", "?"); System.out.println("Token Info For Location:" + location); response = new TestRestTemplate().getForEntity(location, String.class); assertEquals(HttpStatus.OK, response.getStatusCode()); assertEquals("secure", new ObjectMapper().readValue(response.getBody(), HashMap.class).get("content")); }
@Test public void testPushTaupageLogWithRetry() throws Exception { final TestRestTemplate restOperations = new TestRestTemplate(CORRECT_USER, CORRECT_PASSWORD); stubFor(post(urlPathEqualTo("/api/instance-logs")).willReturn(aResponse().withStatus(201).withFixedDelay(100))); stubFor(put(urlEqualTo("/events/" + eventID)).willReturn(aResponse().withStatus(429).withFixedDelay(100))); final URI url = URI.create("http://localhost:" + port + "/instance-logs"); final ResponseEntity<String> response = restOperations.exchange( RequestEntity.post(url).contentType(APPLICATION_JSON).body( instanceLogsPayload), String.class); assertThat(response.getStatusCode()).isEqualTo(CREATED); log.debug("Waiting for async tasks to finish"); TimeUnit.MILLISECONDS.sleep(7500); verify(postRequestedFor(urlPathEqualTo("/api/instance-logs")) .withRequestBody(equalToJson(intanceLogsJsonPayload)) .withHeader(AUTHORIZATION, equalTo("Bearer 1234567890"))); verify(3, putRequestedFor(urlPathEqualTo("/events/" + eventID)) .withRequestBody(equalToJson(new String(auditTrailJsonPayload))) .withHeader(AUTHORIZATION, equalTo("Bearer 1234567890"))); }
@Test public void testMetricsIsSecure() throws Exception { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port + "/metrics", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); entity = new TestRestTemplate() .getForEntity("http://localhost:" + this.port + "/metrics/", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/metrics/foo", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/metrics.json", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); }
@Test public void testLogin() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.set("username", "admin"); form.set("password", "admin"); getCsrf(form, headers); ResponseEntity<String> entity = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/login", HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(form, headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); assertThat(entity.getHeaders().getLocation().toString()) .isEqualTo("http://localhost:" + this.port + "/"); }
private void printAccessToken(String authServerURL, String userId, String userPassword) throws IOException { String encodedPassword = null; try { encodedPassword = URLEncoder.encode(userPassword, "UTF-8"); } catch (UnsupportedEncodingException e) { return; } String url = authServerURL + "/oauth/token?grant_type=password&username=" + userId + "&password=" + encodedPassword; ResponseEntity<String> responseEntity = new TestRestTemplate( "trusted-sw360-client", "sw360-secret") .postForEntity(url, null, String.class); String responseBody = responseEntity.getBody(); JsonNode responseBodyJsonNode = new ObjectMapper().readTree(responseBody); assertThat(responseBodyJsonNode.has("access_token"), is(true)); String accessToken = responseBodyJsonNode.get("access_token").asText(); System.out.println("Authorization: Bearer " + accessToken); }
@Test public void testLogin() throws Exception { HttpHeaders headers = getHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.set("username", "user"); form.set("password", "user"); ResponseEntity<String> entity = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/login", HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(form, headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FOUND); assertThat(entity.getHeaders().getLocation().toString()) .endsWith(this.port + "/"); assertThat(entity.getHeaders().get("Set-Cookie")).isNotNull(); }
@Test public void testCompression() throws Exception { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Accept-Encoding", "gzip"); HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders); TestRestTemplate restTemplate = new TestRestTemplate(); ResponseEntity<byte[]> entity = restTemplate.exchange( "http://localhost:" + this.port, HttpMethod.GET, requestEntity, byte[].class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); GZIPInputStream inflater = new GZIPInputStream( new ByteArrayInputStream(entity.getBody())); try { assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))) .isEqualTo("Hello World"); } finally { inflater.close(); } }
private void verifyAuthentication(ClientDetails config, HttpStatus finalStatus) { String baseUrl = "http://localhost:" + this.context.getWebServer().getPort(); TestRestTemplate 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<>(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).isEqualTo("bearer"); assertThat(scope).isEqualTo("\"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()).isEqualTo(HttpStatus.OK); assertThat(securedResponse.getBody()).isEqualTo( "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()).isEqualTo(finalStatus); }
@Autowired public void setRestTemplate(TestRestTemplate testRestTemplate) { List<HttpMessageConverter<?>> messageConverters = testRestTemplate.getRestTemplate().getMessageConverters(); messageConverters.add(0, new YamlJackson2HttpMessageConverter()); messageConverters.add(0, new JsonJackson2HttpMessageConverter()); messageConverters.add( 0, new ByteArrayHttpMessageConverter()); this.restTemplate = testRestTemplate; }
@Before public void setUp() { gitHubRepoUrl = environment.getProperty("github.repo.url"); gitHubUserUrl = environment.getProperty("github.user.url"); restTemplate = new TestRestTemplate(); githubCache = this.cacheManager.getCache("githubStats"); }
@SuppressWarnings({"rawtypes", "unchecked"}) @Test public void getJwtTokenByTrustedClient() throws JsonParseException, JsonMappingException, IOException { ResponseEntity<String> response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?client_id=trusted-app&grant_type=client_credentials", null, String.class); String responseText = response.getBody(); assertEquals(HttpStatus.OK, response.getStatusCode()); HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class); assertEquals("bearer", jwtMap.get("token_type")); assertEquals("read write", jwtMap.get("scope")); assertTrue(jwtMap.containsKey("access_token")); assertTrue(jwtMap.containsKey("expires_in")); assertTrue(jwtMap.containsKey("jti")); String accessToken = (String) jwtMap.get("access_token"); Jwt jwtToken = JwtHelper.decode(accessToken); String claims = jwtToken.getClaims(); logJson(claims); HashMap claimsMap = new ObjectMapper().readValue(claims, HashMap.class); assertEquals("spring-boot-application", ((List<String>) claimsMap.get("aud")).get(0)); assertEquals("trusted-app", claimsMap.get("client_id")); assertEquals("read", ((List<String>) claimsMap.get("scope")).get(0)); assertEquals("write", ((List<String>) claimsMap.get("scope")).get(1)); List<String> authorities = (List<String>) claimsMap.get("authorities"); assertEquals(1, authorities.size()); assertEquals("ROLE_TRUSTED_CLIENT", authorities.get(0)); }
@Test public void accessProtectedResourceByJwtToken() throws JsonParseException, JsonMappingException, IOException, InvalidJwtException { ResponseEntity<String> response = new TestRestTemplate().getForEntity("http://localhost:" + port + "/resources/client", String.class); assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?client_id=trusted-app&grant_type=client_credentials", null, String.class); String responseText = response.getBody(); assertEquals(HttpStatus.OK, response.getStatusCode()); HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class); String accessToken = (String) jwtMap.get("access_token"); HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Bearer " + accessToken); JwtContext jwtContext = jwtConsumer.process(accessToken); logJWTClaims(jwtContext); response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/principal", HttpMethod.GET, new HttpEntity<>(null, headers), String.class); assertEquals("trusted-app", response.getBody()); response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/trusted_client", HttpMethod.GET, new HttpEntity<>(null, headers), String.class); assertEquals(HttpStatus.OK, response.getStatusCode()); response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/roles", HttpMethod.GET, new HttpEntity<>(null, headers), String.class); assertEquals("[{\"authority\":\"ROLE_TRUSTED_CLIENT\"}]", response.getBody()); }
public static void main(String[] args) { try { String access_token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsic3ByaW5nLWJvb3QtYXBwbGljYXRpb24iXSwidXNlcl9uYW1lIjoiYXBwX2NsaWVudCIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSJdLCJleHAiOjE0OTA5NTI5NzcsImF1dGhvcml0aWVzIjpbIlJPTEVfVVNFUiJdLCJqdGkiOiJmOTA4Njk5Mi1mNTc5LTQzZmEtODBjYi00MmViOTEzMjJmMTkiLCJjbGllbnRfaWQiOiJub3JtYWwtYXBwIn0.dTXMB_yDMEQ5n5fS9VXKjvPDOMJQIFJwbpP7WQdw4WU"; HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", "Bearer " + access_token); ResponseEntity<String> response = new TestRestTemplate().exchange("http://localhost:" + 8080 + "/resources/roles", HttpMethod.GET, new HttpEntity<>(null, headers), String.class); System.out.println(response.getBody()); } catch (Exception e) { e.printStackTrace(); } }
/** * This test method checks whether the 'Home' page returns a correct response status and body or not. * * @throws Exception if the body returned is not the expected or the connection fails. */ @Test public void testHome() throws Exception { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port, String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertTrue("Wrong body (title doesn't match):\n" + entity.getBody(), entity .getBody().contains("<title>Hello")); }
/** * This test method checks whether the website's CSS returns a correct response status and body or not, * and also if the sheet returned is the expected. * * @throws Exception if the connection fails, the body is not valid or the sheet is other than specified. */ @Test public void testCss() throws Exception { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/webjars/bootstrap/3.3.5/css/bootstrap.min.css", String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertTrue("Wrong body:\n" + entity.getBody(), entity.getBody().contains("body")); assertEquals("Wrong content type:\n" + entity.getHeaders().getContentType(), MediaType.valueOf("text/css"), entity.getHeaders() .getContentType()); }
@Test public void catalogLoads() { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/context/eureka/apps", Map.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); }
@Test public void dashboardLoads() { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/context/", String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); String body = entity.getBody(); // System.err.println(body); assertTrue(body.contains("eureka/js")); assertTrue(body.contains("eureka/css")); // The "DS Replicas" assertTrue( body.contains("<a href=\"http://localhost:8761/eureka/\">localhost</a>")); }
@Test public void cssAvailable() { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/context/eureka/css/wro.css", String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); }
@Test public void jsAvailable() { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/context/eureka/js/wro.js", String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); }
@Test public void adminLoads() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/context/env", HttpMethod.GET, new HttpEntity<>("parameters", headers), Map.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); }
@Test public void catalogLoads() { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/eureka/apps", Map.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); }
@Test public void dashboardLoads() { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/servlet/", String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); String body = entity.getBody(); // System.err.println(body); assertTrue(body.contains("eureka/js")); assertTrue(body.contains("eureka/css")); // The "DS Replicas" assertTrue( body.contains("<a href=\"http://localhost:8761/eureka/\">localhost</a>")); }
@Test public void cssAvailable() { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/servlet/eureka/css/wro.css", String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); }
@Test public void jsAvailable() { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/servlet/eureka/js/wro.js", String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); }
@Test public void adminLoads() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/servlet/env", HttpMethod.GET, new HttpEntity<>("parameters", headers), Map.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); }
@Test public void adminLoads() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/env", HttpMethod.GET, new HttpEntity<>("parameters", headers), Map.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); }
@Test public void noDoubleSlashes() { String basePath = "http://localhost:" + this.port + "/"; ResponseEntity<String> entity = new TestRestTemplate().getForEntity(basePath, String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); String body = entity.getBody(); assertNotNull(body); assertFalse("basePath contains double slashes", body.contains(basePath + "/")); }