List of usage examples for org.springframework.mock.web MockHttpServletResponse getHeader
@Override
@Nullable
public String getHeader(String name)
From source file:com.boundlessgeo.geoserver.AppIntegrationTest.java
@Test public void testWorkspaceExport() throws Exception { MockHttpServletResponse response = doWorkspaceExport("sf"); assertEquals("application/zip", response.getContentType()); assertEquals("attachment; filename=\"sf.zip\"", response.getHeader("Content-Disposition")); Path tmp = Files.createTempDirectory(Paths.get("target"), "export"); org.geoserver.data.util.IOUtils.decompress(new ByteArrayInputStream(response.getContentAsByteArray()), tmp.toFile());/*from w ww .j a v a2 s . co m*/ assertTrue(tmp.resolve("bundle.json").toFile().exists()); }
From source file:ch.ralscha.extdirectspring.controller.ApiControllerTest.java
private void testGroup1(Configuration config, String fingerprint) throws Exception { ApiRequestParams params = ApiRequestParams.builder().apiNs("Ext.ns").actionNs("actionns").group("group1") .configuration(config).build(); doTest("/api-debug-doc.js", params, group1Apis("actionns")); doTest("/api-debug.js", params, group1Apis("actionns")); if (fingerprint == null) { doTest("/api.js", params, group1Apis("actionns")); } else {// w w w. j a v a2 s.c o m MvcResult result = doTest("/api" + fingerprint + ".js", params, group1Apis("actionns")); MockHttpServletResponse response = result.getResponse(); assertThat(response.getHeaderNames()).hasSize(5); assertThat(response.getHeader("ETag")).isNotNull(); assertThat(response.getHeader("Cache-Control")).isEqualTo("public, max-age=" + 6 * 30 * 24 * 60 * 60); Long expiresMillis = (Long) response.getHeaderValue("Expires"); DateTime expires = new DateTime(expiresMillis, DateTimeZone.UTC); DateTime inSixMonths = DateTime.now(DateTimeZone.UTC).plusSeconds(6 * 30 * 24 * 60 * 60); assertThat(expires.getYear()).isEqualTo(inSixMonths.getYear()); assertThat(expires.getMonthOfYear()).isEqualTo(inSixMonths.getMonthOfYear()); assertThat(expires.getDayOfMonth()).isEqualTo(inSixMonths.getDayOfMonth()); assertThat(expires.getHourOfDay()).isEqualTo(inSixMonths.getHourOfDay()); assertThat(expires.getMinuteOfDay()).isEqualTo(inSixMonths.getMinuteOfDay()); } }
From source file:com.tasktop.c2c.server.common.service.tests.ajp.AjpProxyWebTest.java
@Test public void testProxyHandlesCookies() throws Exception { final String ajpBaseUri = String.format("ajp://localhost:%s", container.getAjpPort()); Payload payload = new Payload(HttpServletResponse.SC_OK, "some content\none two three\n\nfour"); payload.getResponseHeaders().put("foo", "bar"); payload.getSessionVariables().put("s1", "v1"); TestServlet.setResponsePayload(payload); MockHttpServletRequest request = new MockHttpServletRequest(); request.setMethod("GET"); request.setRequestURI("/test"); request.setQueryString("a=b"); request.setParameter("a", new String[] { "b" }); request.addHeader("c", "d ef"); MockHttpServletResponse response = new MockHttpServletResponse(); proxy.proxyRequest(ajpBaseUri + "/foo", request, response); Request firstRequest = null;// w w w . jav a 2s . c om for (int i = 0; i < 100; i++) { firstRequest = TestServlet.getLastRequest(); // If our request is not yet there, then pause and retry shortly - proxying is an async process, and this // request was sometimes coming back as null which was causing test failures on the first assert below. if (firstRequest == null) { Thread.sleep(10); } else { // Got our request, so break now. break; } } Assert.assertTrue(firstRequest.isNewSession()); Assert.assertEquals("v1", firstRequest.getSessionAttributes().get("s1")); List<org.apache.commons.httpclient.Cookie> cookies = new ArrayList<org.apache.commons.httpclient.Cookie>(); for (String headerName : response.getHeaderNames()) { if (headerName.equalsIgnoreCase("set-cookie") || headerName.equalsIgnoreCase("set-cookie2")) { cookies.addAll(Arrays.asList(new RFC2965Spec().parse("localhost", container.getPort(), "/", false, response.getHeader(headerName).toString()))); } } Assert.assertEquals(1, cookies.size()); Cookie cookie = cookies.get(0); Assert.assertEquals("almp.JSESSIONID", cookie.getName()); MockHttpServletRequest request2 = new MockHttpServletRequest(); request2.setMethod("GET"); request2.setRequestURI("/test"); request2.addHeader("Cookie", cookie.toExternalForm()); MockHttpServletResponse response2 = new MockHttpServletResponse(); payload = new Payload(HttpServletResponse.SC_OK, "test"); TestServlet.setResponsePayload(payload); proxy.proxyRequest(ajpBaseUri + "/foo", request2, response2); Request secondRequest = TestServlet.getLastRequest(); Assert.assertFalse(secondRequest.isNewSession()); Assert.assertEquals(firstRequest.getSessionId(), secondRequest.getSessionId()); Assert.assertEquals("v1", secondRequest.getSessionAttributes().get("s1")); }
From source file:org.openmrs.module.atomfeed.web.AtomFeedDownloadServletTest.java
/** * @see AtomFeedDownloadServlet#doHead(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) * @verifies send not modified error if atom feed has not changed *//* www . j a va2s . com*/ @Test public void doHead_shouldSendNotModifiedErrorIfAtomFeedHasNotChanged() throws Exception { // create servlet and corresponding request and response object to be sent AtomFeedDownloadServlet atomFeedDownloadServlet = new AtomFeedDownloadServlet(); MockHttpServletRequest request = new MockHttpServletRequest("HEAD", "/atomfeed"); request.setContextPath("/somecontextpath"); MockHttpServletResponse response = new MockHttpServletResponse(); // intentionally change atom feed in order to not depend from other tests AtomFeedUtil.objectCreated(new Encounter()); // read atom feed header specific information from the header file String headerFileContent = AtomFeedUtil.readFeedHeaderFile(); int contentLength = 0; String etagToken = ""; Date lastModified = null; if (StringUtils.isNotBlank(headerFileContent)) { contentLength = headerFileContent.length() + Integer .valueOf(StringUtils.substringBetween(headerFileContent, "<entriesSize>", "</entriesSize>")); etagToken = StringUtils.substringBetween(headerFileContent, "<versionId>", "</versionId>"); try { lastModified = new SimpleDateFormat(AtomFeedUtil.RFC_3339_DATE_FORMAT) .parse(StringUtils.substringBetween(headerFileContent, "<updated>", "</updated>")); } catch (ParseException e) { // ignore it here } } // set request headers request.addHeader("If-None-Match", '"' + etagToken + '"'); request.addHeader("If-Modified-Since", lastModified); atomFeedDownloadServlet.service(request, response); // check response headers Assert.assertEquals(contentLength, response.getContentLength()); Assert.assertEquals("application/atom+xml", response.getContentType()); Assert.assertEquals(HttpServletResponse.SC_NOT_MODIFIED, response.getStatus()); Assert.assertNotNull(response.getHeader("Last-Modified")); }
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.webdav.AbstractRepositoryServletTestCase.java
protected WebResponse getWebResponse(WebRequest webRequest) //, boolean followRedirect ) throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI(webRequest.getUrl().getPath()); request.addHeader("User-Agent", "Apache Archiva unit test"); request.setMethod(webRequest.getHttpMethod().name()); if (webRequest.getHttpMethod() == HttpMethod.PUT) { PutMethodWebRequest putRequest = PutMethodWebRequest.class.cast(webRequest); request.setContentType(putRequest.contentType); request.setContent(IOUtils.toByteArray(putRequest.inputStream)); }/*from w w w . j av a 2 s .c om*/ if (webRequest instanceof MkColMethodWebRequest) { request.setMethod("MKCOL"); } final MockHttpServletResponse response = execute(request); if (response.getStatus() == HttpServletResponse.SC_MOVED_PERMANENTLY || response.getStatus() == HttpServletResponse.SC_MOVED_TEMPORARILY) { String location = response.getHeader("Location"); log.debug("follow redirect to {}", location); return getWebResponse(new GetMethodWebRequest(location)); } return new WebResponse(null, null, 1) { @Override public String getContentAsString() { try { return response.getContentAsString(); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } } @Override public int getStatusCode() { return response.getStatus(); } @Override public String getResponseHeaderValue(String headerName) { return response.getHeader(headerName); } }; }
From source file:org.apache.archiva.webdav.RepositoryServletNoProxyTest.java
@Test public void testGetNoProxySnapshotRedirectToTimestampedSnapshot() throws Exception { String commonsLangQuery = "commons-lang/commons-lang/2.1-SNAPSHOT/commons-lang-2.1-SNAPSHOT.jar"; String commonsLangMetadata = "commons-lang/commons-lang/2.1-SNAPSHOT/maven-metadata.xml"; String commonsLangJar = "commons-lang/commons-lang/2.1-SNAPSHOT/commons-lang-2.1-20050821.023400-1.jar"; String expectedArtifactContents = "dummy-commons-lang-snapshot-artifact"; archivaConfiguration.getConfiguration().getWebapp().getUi().setApplicationUrl("http://localhost"); File artifactFile = new File(repoRootInternal, commonsLangJar); artifactFile.getParentFile().mkdirs(); FileUtils.writeStringToFile(artifactFile, expectedArtifactContents, Charset.defaultCharset()); File metadataFile = new File(repoRootInternal, commonsLangMetadata); metadataFile.getParentFile().mkdirs(); FileUtils.writeStringToFile(metadataFile, createVersionMetadata("commons-lang", "commons-lang", "2.1-SNAPSHOT", "20050821.023400", "1", "20050821.023400")); WebRequest webRequest = new GetMethodWebRequest("http://localhost/repository/internal/" + commonsLangQuery); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI(webRequest.getUrl().getPath()); request.addHeader("User-Agent", "Apache Archiva unit test"); request.setMethod(webRequest.getHttpMethod().name()); final MockHttpServletResponse response = execute(request); assertEquals(HttpServletResponse.SC_MOVED_TEMPORARILY, response.getStatus()); assertEquals("http://localhost/repository/internal/" + commonsLangJar, response.getHeader("Location")); }
From source file:org.cloudfoundry.identity.uaa.scim.endpoints.ScimGroupEndpointsTests.java
@Test public void testGetGroup() throws Exception { MockHttpServletResponse httpServletResponse = new MockHttpServletResponse(); ScimGroup g = endpoints.getGroup(groupIds.get(groupIds.size() - 1), httpServletResponse); validateGroup(g, "uaa.none", 2); assertEquals("\"0\"", httpServletResponse.getHeader("ETag")); }