List of usage examples for org.springframework.mock.web MockHttpServletRequest addHeader
public void addHeader(String name, Object value)
From source file:org.geoserver.security.BruteForceAttackTest.java
private void testParallelLogin(String expectedMessage, Function<Integer, String> userNameGenerator) throws InterruptedException, ExecutionException { // idea, setup several threads to do the same failing auth in parallel, // ensuring they are all ready to go at the same time using a latch final int NTHREADS = 32; ExecutorService service = Executors.newFixedThreadPool(NTHREADS); CountDownLatch latch = new CountDownLatch(NTHREADS); AtomicInteger concurrentLoginsPrevented = new AtomicInteger(0); List<Future<?>> futures = new ArrayList<>(); long start = System.currentTimeMillis(); for (int i = 0; i < NTHREADS; i++) { final int idx = i; Future<?> future = service.submit(() -> { // mark and ready and wait for others latch.countDown();//ww w . ja v a 2 s .c o m latch.await(); // execute request timing how long it took MockHttpServletRequest request = createRequest(HELLO_GET_REQUEST); request.setMethod("GET"); request.setContent(new byte[] {}); String userName = userNameGenerator.apply(idx); String token = userName + ":foobar"; request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes()))); MockHttpServletResponse response = dispatch(request, "UTF-8"); // check the response and see the error message assertEquals(401, response.getStatus()); final String message = response.getErrorMessage(); // System.out.println(message); if (message.contains(expectedMessage)) { concurrentLoginsPrevented.incrementAndGet(); } return null; }); futures.add(future); } // wait for termination for (Future<?> future : futures) { future.get(); } long awaitTime = System.currentTimeMillis() - start; service.shutdown(); // now, either the threads all serialized and waited (extremely unlikely, but // not impossible) or at least one got bumped immediately with a concurrent login message assertTrue(awaitTime > NTHREADS * 1000 || concurrentLoginsPrevented.get() > 0); }
From source file:org.jahia.bin.ErrorFileDumperTest.java
private void generateExceptions() { for (int i = 0; i < LOOP_COUNT; i++) { MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/cms"); request.setQueryString("name=value"); request.addHeader("headerName", "headerValue"); try {/*from www . j ava 2 s.co m*/ ErrorFileDumper.dumpToFile(new Throwable("mock error " + i), (HttpServletRequest) request); } catch (IOException e) { logger.error("Error while dumping error", e); } } }
From source file:org.jasig.portal.portlet.rendering.PortletRendererImplTest.java
/** * Same as {@link #doServeResourceCachedContentValidationMethodTest()}, but simulate browser * sending If-None-Match header that matches the etag. Verify no content returned and a 304 status code. * /* w w w .j a v a2s. co m*/ * @throws PortletException * @throws IOException * @throws PortletContainerException */ @Test public void doServeResourceCachedContentValidationMethodNotModifiedTest() throws PortletException, IOException, PortletContainerException { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("If-None-Match", "123456"); MockHttpServletResponse response = new MockHttpServletResponse(); Date now = new Date(); CacheControlImpl cacheControl = new CacheControlImpl(); cacheControl.setUseCachedContent(true); cacheControl.setExpirationTime(300); cacheControl.setETag("123456"); CachedPortletData cachedPortletData = new CachedPortletData(); cachedPortletData.setContentType("application/json"); byte[] content = "{ \"hello\": \"world\" }".getBytes(); cachedPortletData.setByteData(content); cachedPortletData.setExpirationTimeSeconds(cacheControl.getExpirationTime()); cachedPortletData.setEtag("123456"); cachedPortletData.setTimeStored(now); setupPortletExecutionMocks(request); when(portletCacheControlService.getPortletResourceCacheControl(portletWindowId, request, response)) .thenReturn(cacheControl); when(portletCacheControlService.getCachedPortletResourceOutput(portletWindowId, request)) .thenReturn(cachedPortletData); portletRenderer.doServeResource(portletWindowId, request, response); //byte [] fromResponse = response.getContentAsByteArray(); Assert.assertEquals(0, response.getContentLength()); Assert.assertEquals(304, response.getStatus()); // verify we enter the first branch and never execute portletContainer#doServeResource verify(portletContainer, never()).doServeResource(isA(PortletWindow.class), isA(PortletHttpServletRequestWrapper.class), isA(PortletHttpServletResponseWrapper.class)); // verify we never enter the other branch of the "should render cached output" if statement verify(portletCacheControlService, never()).shouldOutputBeCached(isA(CacheControl.class)); }
From source file:org.jasig.portal.portlet.rendering.PortletRendererImplTest.java
/** * Same as {@link #doServeResourceCachedContentValidationMethodTest()}, but simulate browser * sending If-None-Match header with mismatched etag. Response is 200 with content and new etag * //from w ww .j a v a 2 s .co m * @throws PortletException * @throws IOException * @throws PortletContainerException */ @Test public void doServeResourceCachedContentValidationMethodIfNoneMatchInvalidTest() throws PortletException, IOException, PortletContainerException { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("If-None-Match", "123456"); MockHttpServletResponse response = new MockHttpServletResponse(); Date now = new Date(); CacheControlImpl cacheControl = new CacheControlImpl(); cacheControl.setUseCachedContent(true); cacheControl.setExpirationTime(300); cacheControl.setETag("123457"); CachedPortletData cachedPortletData = new CachedPortletData(); cachedPortletData.setContentType("application/json"); byte[] content = "{ \"hello\": \"world\" }".getBytes(); cachedPortletData.setByteData(content); cachedPortletData.setExpirationTimeSeconds(cacheControl.getExpirationTime()); cachedPortletData.setEtag("123457"); cachedPortletData.setTimeStored(now); setupPortletExecutionMocks(request); when(portletCacheControlService.getPortletResourceCacheControl(portletWindowId, request, response)) .thenReturn(cacheControl); when(portletCacheControlService.getCachedPortletResourceOutput(portletWindowId, request)) .thenReturn(cachedPortletData); portletRenderer.doServeResource(portletWindowId, request, response); // verify content matches what was in cache (no array support in Assert.assertEquals, check byte for byte) byte[] fromResponse = response.getContentAsByteArray(); Assert.assertEquals(content.length, fromResponse.length); for (int i = 0; i < content.length; i++) { Assert.assertEquals(content[i], fromResponse[i]); } Assert.assertEquals(200, response.getStatus()); Assert.assertEquals("123457", response.getHeader("ETag")); // verify we enter the first branch and never execute portletContainer#doServeResource verify(portletContainer, never()).doServeResource(isA(PortletWindow.class), isA(PortletHttpServletRequestWrapper.class), isA(PortletHttpServletResponseWrapper.class)); // verify we never enter the other branch of the "should render cached output" if statement verify(portletCacheControlService, never()).shouldOutputBeCached(isA(CacheControl.class)); }
From source file:org.jasig.portal.portlet.rendering.PortletRendererImplTest.java
/** * Same as {@link #doServeResourceCachedContentValidationMethodNotModifiedTest()}, however the CachedPortletData * is older than it's expiration time. Verify the renderer still detects the etag and returns 304 not modified. * /*w ww.j ava 2 s . c o m*/ * @throws PortletException * @throws IOException * @throws PortletContainerException */ @Test public void doServeResourceCachedContentValidationMethodNotModifiedInternalCacheExpiredTest() throws PortletException, IOException, PortletContainerException { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("If-None-Match", "123456"); MockHttpServletResponse response = new MockHttpServletResponse(); Date now = new Date(); CacheControlImpl cacheControl = new CacheControlImpl(); cacheControl.setUseCachedContent(true); cacheControl.setExpirationTime(300); cacheControl.setETag("123456"); CachedPortletData cachedPortletData = new CachedPortletData(); cachedPortletData.setContentType("application/json"); byte[] content = "{ \"hello\": \"world\" }".getBytes(); cachedPortletData.setByteData(content); cachedPortletData.setExpirationTimeSeconds(cacheControl.getExpirationTime()); cachedPortletData.setEtag("123456"); // set Time stored to a value prior to the expiration time cachedPortletData.setTimeStored(DateUtils.addSeconds(now, -310)); setupPortletExecutionMocks(request); when(portletCacheControlService.getPortletResourceCacheControl(portletWindowId, request, response)) .thenReturn(cacheControl); when(portletCacheControlService.getCachedPortletResourceOutput(portletWindowId, request)) .thenReturn(cachedPortletData); portletRenderer.doServeResource(portletWindowId, request, response); Assert.assertEquals(0, response.getContentLength()); Assert.assertEquals(304, response.getStatus()); // since the cached content is expired, a doServeResource is going to be invoked verify(portletContainer, times(1)).doServeResource(isA(PortletWindow.class), isA(PortletHttpServletRequestWrapper.class), isA(PortletHttpServletResponseWrapper.class)); // portlet said we should useCachedContent, so don't expect an attempt to "cache output" verify(portletCacheControlService, never()).shouldOutputBeCached(isA(CacheControl.class)); }
From source file:org.opennms.core.test.rest.AbstractSpringJerseyRestTestCase.java
protected <T> T getJsonObject(ObjectMapper mapper, String url, Map<String, String> parameterMap, int expectedStatus, Class<T> expectedClass) throws Exception { MockHttpServletRequest request = createRequest(servletContext, GET, url, parameterMap, getUser(), getUserRoles());//from w w w.j a va 2 s . co m MockHttpServletResponse response = createResponse(); request.addHeader(ACCEPT, MediaType.APPLICATION_JSON); dispatch(request, response); assertEquals(expectedStatus, response.getStatus()); System.err.printf("json: %s%n", response.getContentAsString()); InputStream in = new ByteArrayInputStream(response.getContentAsByteArray()); return mapper.readValue(in, expectedClass); }
From source file:org.opennms.core.test.rest.AbstractSpringJerseyRestTestCase.java
protected <T> T getXmlObject(JAXBContext context, String url, Map<String, String> parameterMap, int expectedStatus, Class<T> expectedClass) throws Exception { MockHttpServletRequest request = createRequest(servletContext, GET, url, parameterMap, getUser(), getUserRoles());//from w w w . j a v a 2s . com MockHttpServletResponse response = createResponse(); request.addHeader(ACCEPT, MediaType.APPLICATION_XML); dispatch(request, response); assertEquals(expectedStatus, response.getStatus()); System.err.printf("xml: %s%n", response.getContentAsString()); InputStream in = new ByteArrayInputStream(response.getContentAsByteArray()); Unmarshaller unmarshaller = context.createUnmarshaller(); T result = expectedClass.cast(unmarshaller.unmarshal(in)); return result; }
From source file:org.opennms.web.rest.AcknowledgmentRestServiceTest.java
@Test @JUnitTemporaryDatabase//from w w w . j av a2s .co m public void testGetAcksJson() throws Exception { String url = "/acks"; // GET all items MockHttpServletRequest jsonRequest = createRequest(getServletContext(), GET, url); jsonRequest.addHeader("Accept", MediaType.APPLICATION_JSON); String json = sendRequest(jsonRequest, 200); JSONObject restObject = new JSONObject(json); JSONObject expectedObject = new JSONObject( IOUtils.toString(new FileInputStream("src/test/resources/v1/acks.json"))); JSONAssert.assertEquals(expectedObject, restObject, true); }
From source file:org.opennms.web.rest.AlarmRestServiceTest.java
@Test @JUnitTemporaryDatabase/*from w w w.ja v a 2s .c o m*/ public void testAlarmsJson() throws Exception { String url = "/alarms"; // GET all items MockHttpServletRequest jsonRequest = createRequest(getServletContext(), GET, url, "admin", Arrays.asList(new String[] { Authentication.ROLE_ADMIN })); jsonRequest.addHeader("Accept", MediaType.APPLICATION_JSON); String json = sendRequest(jsonRequest, 200); JSONObject restObject = new JSONObject(json); JSONObject expectedObject = new JSONObject( IOUtils.toString(new FileInputStream("src/test/resources/v1/alarms.json"))); JSONAssert.assertEquals(expectedObject, restObject, true); }
From source file:org.opennms.web.rest.AlarmStatsRestServiceTest.java
/** * TODO: Doesn't test firstAutomationTime, lastAutomationTime, reductionKey, * reductionKeyMemo, suppressedTime, suppressedUntil, clearKey, or stickyMemo * fields./*from w w w .ja v a 2 s .c om*/ */ @Test @JUnitTemporaryDatabase public void testGetAlarmStatsJson() throws Exception { createAlarm(OnmsSeverity.CLEARED, "admin"); createAlarm(OnmsSeverity.MAJOR, "admin"); createAlarm(OnmsSeverity.CRITICAL, "admin"); createAlarm(OnmsSeverity.CRITICAL, null); createAlarm(OnmsSeverity.MINOR, null); createAlarm(OnmsSeverity.NORMAL, null); // GET all users MockHttpServletRequest jsonRequest = createRequest(getServletContext(), GET, "/stats/alarms"); jsonRequest.addHeader("Accept", MediaType.APPLICATION_JSON); String json = sendRequest(jsonRequest, 200); JSONObject restObject = new JSONObject(json); JSONObject expectedObject = new JSONObject( IOUtils.toString(new FileInputStream("src/test/resources/v1/stats_alarms.json"))); JSONAssert.assertEquals(expectedObject, restObject, true); }