List of usage examples for org.springframework.mock.web MockHttpServletRequest addHeader
public void addHeader(String name, Object value)
From source file:org.fenixedu.bennu.oauth.OAuthServletTest.java
@Test public void refreshAccessTokenHeaderTest() { MockHttpServletRequest req = new MockHttpServletRequest(); MockHttpServletResponse res = new MockHttpServletResponse(); Authenticate.unmock();/* w w w . ja v a2 s . c o m*/ ExternalApplication externalApp = new ExternalApplication(); externalApp.setAuthor(user1); externalApp.setName("Test External Application"); externalApp.setDescription("This is a test external application"); externalApp.setRedirectUrl("http://test.url/callback"); ApplicationUserSession applicationUserSession = new ApplicationUserSession(); applicationUserSession.setTokens(generateToken(applicationUserSession), generateToken(applicationUserSession)); ApplicationUserAuthorization applicationUserAuthorization = new ApplicationUserAuthorization(user1, externalApp); applicationUserAuthorization.addSession(applicationUserSession); externalApp.addApplicationUserAuthorization(applicationUserAuthorization); String clientSecret = externalApp.getExternalId() + ":" + externalApp.getSecret(); req.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + Base64.getEncoder().encodeToString(clientSecret.getBytes(StandardCharsets.UTF_8))); req.addParameter(REFRESH_TOKEN, applicationUserSession.getRefreshToken()); req.addParameter(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); req.setMethod("POST"); req.setPathInfo("/refresh_token"); try { oauthServlet.service(req, res); Assert.assertEquals("must return status OK", 200, res.getStatus()); String tokenJson = res.getContentAsString(); final JsonObject token = new JsonParser().parse(tokenJson).getAsJsonObject(); Assert.assertTrue("response must be a valid json and have access_token field", token.has(ACCESS_TOKEN) && token.get(ACCESS_TOKEN).getAsString().length() > 0); } catch (ServletException | IOException e) { Assert.fail(e.getMessage()); } }
From source file:org.fenixedu.bennu.oauth.OAuthServletTest.java
@Test public void testTokenTypeRefreshAccessTokenInHeader() { MockHttpServletRequest req = new MockHttpServletRequest(); MockHttpServletResponse res = new MockHttpServletResponse(); Authenticate.unmock();/*from www .j a va 2s . co m*/ ExternalApplication externalApp = new ExternalApplication(); externalApp.setAuthor(user1); externalApp.setName("Test External Application"); externalApp.setDescription("This is a test external application"); externalApp.setRedirectUrl("http://test.url/callback"); externalApp.addScopes(externalApplicationScope); ApplicationUserSession applicationUserSession = new ApplicationUserSession(); applicationUserSession.setTokens(generateToken(applicationUserSession), generateToken(applicationUserSession)); ApplicationUserAuthorization applicationUserAuthorization = new ApplicationUserAuthorization(user1, externalApp); applicationUserAuthorization.addSession(applicationUserSession); externalApp.addApplicationUserAuthorization(applicationUserAuthorization); String clientSecret = externalApp.getExternalId() + ":" + externalApp.getSecret(); req.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + Base64.getEncoder().encodeToString(clientSecret.getBytes(StandardCharsets.UTF_8))); req.addParameter(REFRESH_TOKEN, applicationUserSession.getRefreshToken()); req.addParameter(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); req.setMethod("POST"); req.setPathInfo("/refresh_token"); try { oauthServlet.service(req, res); Assert.assertEquals("must return status OK", 200, res.getStatus()); String tokenJson = res.getContentAsString(); final JsonObject token = new JsonParser().parse(tokenJson).getAsJsonObject(); Assert.assertTrue("response must be a valid json and have access_token field", token.has(ACCESS_TOKEN) && token.get(ACCESS_TOKEN).getAsString().length() > 0); Assert.assertTrue("response must be a valid json and have " + TOKEN_TYPE + " field", token.has(TOKEN_TYPE) && token.get(TOKEN_TYPE).getAsString().length() > 0); String accessToken = token.get(ACCESS_TOKEN).getAsString(); String tokenType = token.get(TOKEN_TYPE).getAsString(); String result = target("bennu-oauth").path("test").path("test-scope").request() .header(HttpHeaders.AUTHORIZATION, tokenType + " " + accessToken).get(String.class); Assert.assertEquals("this is an endpoint with TEST scope user1", result); } catch (ServletException | IOException e) { Assert.fail(e.getMessage()); } }
From source file:org.fenixedu.bennu.oauth.OAuthServletTest.java
@Test public void testOAuthServletAccessTokenRequestWithLoginExpired() { MockHttpServletRequest req = new MockHttpServletRequest(); MockHttpServletResponse res = new MockHttpServletResponse(); Authenticate.unmock();/*from w w w . j av a 2s .c om*/ User user = createUser("testOAuthServletAccessTokenRequestWithLoginExpired", "John", "Doe", "John Doe", "john.doe@fenixedu.org"); user.closeLoginPeriod(); ExternalApplication externalApp = new ExternalApplication(); externalApp.setAuthor(user1); externalApp.setName("Test External Application"); externalApp.setDescription("This is a test external application"); externalApp.setRedirectUrl("http://test.url/callback"); ApplicationUserSession applicationUserSession = new ApplicationUserSession(); applicationUserSession.setCode("fenixedu"); ApplicationUserAuthorization applicationUserAuthorization = new ApplicationUserAuthorization(user, externalApp); applicationUserAuthorization.addSession(applicationUserSession); externalApp.addApplicationUserAuthorization(applicationUserAuthorization); String clientSecret = externalApp.getExternalId() + ":" + externalApp.getSecret(); req.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + Base64.getEncoder().encodeToString(clientSecret.getBytes(StandardCharsets.UTF_8))); req.addParameter(REDIRECT_URI, externalApp.getRedirectUrl()); req.addParameter(CODE, applicationUserSession.getCode()); req.addParameter(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE); req.setMethod("POST"); req.setPathInfo("/access_token"); try { oauthServlet.service(req, res); Assert.assertEquals("must return bad request", Status.BAD_REQUEST.getStatusCode(), res.getStatus()); user.openLoginPeriod(); res = new MockHttpServletResponse(); oauthServlet.service(req, res); final JsonObject token = new JsonParser().parse(res.getContentAsString()).getAsJsonObject(); Assert.assertTrue("response must be a valid json and have access_token field", token.has("access_token") && token.get("access_token").getAsString().length() > 0); } catch (ServletException | IOException e) { Assert.fail(e.getMessage()); } }
From source file:org.fenixedu.bennu.oauth.OAuthServletTest.java
@Test public void testOAuthServletRefreshTokenRequestWithLoginExpired() { MockHttpServletRequest req = new MockHttpServletRequest(); MockHttpServletResponse res = new MockHttpServletResponse(); Authenticate.unmock();/* w w w . j a v a 2 s . co m*/ User user = createUser("testOAuthServletRefreshTokenRequestWithLoginExpired", "John", "Doe", "John Doe", "john.doe@fenixedu.org"); user.closeLoginPeriod(); ExternalApplication externalApp = new ExternalApplication(); externalApp.setAuthor(user1); externalApp.setName("Test External Application"); externalApp.setDescription("This is a test external application"); externalApp.setRedirectUrl("http://test.url/callback"); ApplicationUserSession applicationUserSession = new ApplicationUserSession(); applicationUserSession.setTokens(generateToken(applicationUserSession), generateToken(applicationUserSession)); ApplicationUserAuthorization applicationUserAuthorization = new ApplicationUserAuthorization(user, externalApp); applicationUserAuthorization.addSession(applicationUserSession); externalApp.addApplicationUserAuthorization(applicationUserAuthorization); String clientSecret = externalApp.getExternalId() + ":" + externalApp.getSecret(); req.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + Base64.getEncoder().encodeToString(clientSecret.getBytes(StandardCharsets.UTF_8))); req.addParameter(REFRESH_TOKEN, applicationUserSession.getRefreshToken()); req.addParameter(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); req.setMethod("POST"); req.setPathInfo("/refresh_token"); try { oauthServlet.service(req, res); Assert.assertEquals("must return bad request", Status.BAD_REQUEST.getStatusCode(), res.getStatus()); user.openLoginPeriod(); res = new MockHttpServletResponse(); oauthServlet.service(req, res); final JsonObject token = new JsonParser().parse(res.getContentAsString()).getAsJsonObject(); Assert.assertTrue("response must be a valid json and have access_token field", token.has("access_token") && token.get("access_token").getAsString().length() > 0); } catch (ServletException | IOException e) { Assert.fail(e.getMessage()); } }
From source file:com.liferay.document.library.webdav.test.BaseWebDAVTestCase.java
public Tuple service(String method, String path, Map<String, String> headers, byte[] data) { WebDAVServlet webDAVServlet = new WebDAVServlet(); String requestURI = _CONTEXT_PATH + _SERVLET_PATH + _PATH_INFO_PREFACE + path; MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(method, requestURI); mockHttpServletRequest.setContextPath(_CONTEXT_PATH); mockHttpServletRequest.setServletPath(_SERVLET_PATH); mockHttpServletRequest.setPathInfo(_PATH_INFO_PREFACE + path); try {/*from w w w.ja v a 2 s. c o m*/ mockHttpServletRequest.setRemoteUser(String.valueOf(TestPropsValues.getUserId())); } catch (Exception e) { Assert.fail("User ID cannot be initialized"); } if (headers == null) { headers = new HashMap<>(); } headers.put(HttpHeaders.USER_AGENT, getUserAgent()); try { throw new Exception(); } catch (Exception e) { StackTraceElement[] stackTraceElements = e.getStackTrace(); for (StackTraceElement stackTraceElement : stackTraceElements) { String methodName = stackTraceElement.getMethodName(); if (methodName.equals("setUp") || methodName.equals("tearDown") || methodName.startsWith("test")) { String testName = StringUtil.extractLast(stackTraceElement.getClassName(), CharPool.PERIOD); testName = StringUtil.removeSubstrings(testName, "WebDAV", "Test"); headers.put("X-Litmus", testName + ": (" + stackTraceElement.getMethodName() + ":" + stackTraceElement.getLineNumber() + ")"); break; } } } if (data != null) { mockHttpServletRequest.setContent(data); String contentType = headers.remove(HttpHeaders.CONTENT_TYPE); if (contentType != null) { mockHttpServletRequest.setContentType(contentType); } else { mockHttpServletRequest.setContentType(ContentTypes.TEXT_PLAIN); } } for (Map.Entry<String, String> entry : headers.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); mockHttpServletRequest.addHeader(key, value); } try { MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); webDAVServlet.service(mockHttpServletRequest, mockHttpServletResponse); int statusCode = mockHttpServletResponse.getStatus(); byte[] responseBody = mockHttpServletResponse.getContentAsByteArray(); Map<String, String> responseHeaders = new HashMap<>(); for (String name : mockHttpServletResponse.getHeaderNames()) { responseHeaders.put(name, mockHttpServletResponse.getHeader(name)); } return new Tuple(statusCode, responseBody, responseHeaders); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:org.apache.archiva.web.rss.RssFeedServletTest.java
@Test public void testRequestNewArtifactsInRepo() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/feeds/test-repo"); request.addHeader("User-Agent", "Apache Archiva unit test"); request.setMethod("GET"); Base64 encoder = new Base64(0, new byte[0]); String userPass = "user1:password1"; String encodedUserPass = encoder.encodeToString(userPass.getBytes()); request.addHeader("Authorization", "BASIC " + encodedUserPass); MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); rssFeedServlet.doGet(request, mockHttpServletResponse); assertEquals(RssFeedServlet.MIME_TYPE, mockHttpServletResponse.getHeader("CONTENT-TYPE")); assertNotNull("Should have recieved a response", mockHttpServletResponse.getContentAsString()); assertEquals("Should have been an OK response code.", HttpServletResponse.SC_OK, mockHttpServletResponse.getStatus()); }
From source file:org.apache.archiva.web.rss.RssFeedServletTest.java
@Test public void testRequestNewVersionsOfArtifact() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/feeds/org/apache/archiva/artifact-two"); request.addHeader("User-Agent", "Apache Archiva unit test"); request.setMethod("GET"); //WebRequest request = new GetMethodWebRequest( "http://localhost/feeds/org/apache/archiva/artifact-two" ); Base64 encoder = new Base64(0, new byte[0]); String userPass = "user1:password1"; String encodedUserPass = encoder.encodeToString(userPass.getBytes()); request.addHeader("Authorization", "BASIC " + encodedUserPass); MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); rssFeedServlet.doGet(request, mockHttpServletResponse); assertEquals(RssFeedServlet.MIME_TYPE, mockHttpServletResponse.getHeader("CONTENT-TYPE")); assertNotNull("Should have recieved a response", mockHttpServletResponse.getContentAsString()); assertEquals("Should have been an OK response code.", HttpServletResponse.SC_OK, mockHttpServletResponse.getStatus()); }
From source file:org.apache.archiva.web.rss.RssFeedServletTest.java
@Test public void testInvalidRequest() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/feeds?invalid_param=xxx"); request.addHeader("User-Agent", "Apache Archiva unit test"); request.setMethod("GET"); MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); rssFeedServlet.doGet(request, mockHttpServletResponse); assertEquals(HttpServletResponse.SC_BAD_REQUEST, mockHttpServletResponse.getStatus()); }
From source file:org.apache.archiva.web.rss.RssFeedServletTest.java
@Test public void testInvalidAuthenticationRequest() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/feeds/unauthorized-repo"); request.addHeader("User-Agent", "Apache Archiva unit test"); request.setMethod("GET"); Encoder encoder = new Base64(); String userPass = "unauthUser:unauthPass"; String encodedUserPass = new String((byte[]) encoder.encode(userPass.getBytes())); request.addHeader("Authorization", "BASIC " + encodedUserPass); MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); rssFeedServlet.doGet(request, mockHttpServletResponse); assertEquals(HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus()); }
From source file:org.apache.archiva.web.rss.RssFeedServletTest.java
@Test public void testUnauthorizedRequest() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/feeds/unauthorized-repo"); request.addHeader("User-Agent", "Apache Archiva unit test"); request.setMethod("GET"); Base64 encoder = new Base64(0, new byte[0]); String userPass = "user1:password1"; String encodedUserPass = encoder.encodeToString(userPass.getBytes()); request.addHeader("Authorization", "BASIC " + encodedUserPass); MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); rssFeedServlet.doGet(request, mockHttpServletResponse); assertEquals(HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus()); }