List of usage examples for org.springframework.mock.web MockHttpServletRequest setContent
public void setContent(@Nullable byte[] content)
From source file:org.geoserver.restupload.ResumableUploadTest.java
@Test public void testGetAfterPartial() throws Exception { String uploadId = sendPostRequest(); byte[] bigFile = generateFileAsBytes(); byte[] partialFile = ArrayUtils.subarray(bigFile, 0, (int) partialSize); // First upload MockHttpServletRequest request = createRequest("/rest/resumableupload/" + uploadId); request.setMethod("PUT"); request.setContentType("application/octet-stream"); request.setContent(partialFile); request.addHeader("Content-type", "application/octet-stream"); request.addHeader("Content-Length", String.valueOf(bigFile.length)); dispatch(request);//from w w w. ja va2 s. c o m File uploadedFile = getTempPath(uploadId); assertTrue(uploadedFile.exists()); MockHttpServletResponse response = getAsServletResponse("/rest/resumableupload/" + uploadId, "text/plain"); assertEquals(ResumableUploadCatalogResource.RESUME_INCOMPLETE.getCode(), response.getStatus()); assertEquals(null, response.getHeader("Content-Length")); assertEquals("0-" + (partialSize - 1), response.getHeader("Range")); }
From source file:org.geoserver.restupload.ResumableUploadTest.java
@Test public void testGetAfterFull() throws Exception { String uploadId = sendPostRequest(); File uploadedFile = getTempPath(uploadId); assertTrue(uploadedFile.exists());/* www. ja v a2s . com*/ MockHttpServletRequest request = createRequest("/rest/resumableupload/" + uploadId); request.setMethod("PUT"); request.setContentType("application/octet-stream"); byte[] bigFile = generateFileAsBytes(); request.setContent(bigFile); request.addHeader("Content-type", "application/octet-stream"); request.addHeader("Content-Length", String.valueOf(bigFile.length)); MockHttpServletResponse response = dispatch(request); assertEquals(Status.SUCCESS_OK.getCode(), response.getStatus()); File sidecarFile = new File( FilenameUtils.concat(tmpUploadFolder.dir().getCanonicalPath(), uploadId + ".sidecar")); assertTrue(sidecarFile.exists()); }
From source file:org.geoserver.restupload.ResumableUploadTest.java
private String sendPostRequest() throws Exception { MockHttpServletRequest request = createRequest("/rest/resumableupload/"); request.setMethod("POST"); request.setContentType("text/plain"); request.setContent(fileName.getBytes("UTF-8")); request.addHeader("Content-type", "text/plain"); MockHttpServletResponse response = dispatch(request); assertEquals(Status.SUCCESS_CREATED.getCode(), response.getStatus()); String responseBody = response.getContentAsString(); String url = responseBody.split("\\r?\\n")[1]; String uploadId = FilenameUtils.getBaseName(url); return uploadId; }
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();/*from w ww . j a 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.jtalks.jcommune.web.exception.PrettyLogExceptionResolverTest.java
@Test public void testLogExceptionWithIncomingNotFoundException() throws Exception { Log mockLog = replaceLoggerWithMock(prettyLogExceptionResolver); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); NotFoundException notFoundException = new NotFoundException("Entity not found"); String logMessage = String.format("[%s][%s][%s][%s]", request.getMethod(), request.getRequestURL().toString(), request.getHeader("Cookie"), "Entity not found"); request.setContent("".getBytes()); prettyLogExceptionResolver.logException(notFoundException, request); verify(mockLog).info(logMessage);//from www . j av a 2s .c om }
From source file:org.jtalks.jcommune.web.exception.PrettyLogExceptionResolverTest.java
@Test public void testLogExceptionWithIncomingTypeMismatchException() throws Exception { Log mockLog = replaceLoggerWithMock(prettyLogExceptionResolver); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); TypeMismatchException typeMismatchException = new TypeMismatchException("Not a number", Number.class); String logMessage = String.format("[%s][%s][%s][%s]", request.getMethod(), request.getRequestURL().toString(), request.getHeader("Cookie"), typeMismatchException.getMessage()); request.setContent("".getBytes()); prettyLogExceptionResolver.logException(typeMismatchException, request); verify(mockLog).info(logMessage);/* w w w . j a v a 2s .c o m*/ }
From source file:org.jtalks.jcommune.web.exception.PrettyLogExceptionResolverTest.java
@Test public void testLogExceptionWithIncomingAccessDeniedException() throws Exception { Log mockLog = replaceLoggerWithMock(prettyLogExceptionResolver); AccessDeniedException accessDeniedException = new AccessDeniedException("Access denied"); MockHttpServletRequest request = new MockHttpServletRequest("POST", "/testing/url/42"); request.setServerName("testserver.com"); request.setServerPort(8080);//from www.j a v a 2s .c om request.setContent("12345".getBytes()); request.setUserPrincipal(new UsernamePasswordAuthenticationToken("username", "password")); prettyLogExceptionResolver.logException(accessDeniedException, request); verify(mockLog).info( "Access was denied for user [username] trying to POST http://testserver.com:8080/testing/url/42"); }
From source file:org.jtalks.jcommune.web.exception.PrettyLogExceptionResolverTest.java
@Test public void testLogExceptionWithoutNotFoundException() throws Exception { Log mockLog = replaceLoggerWithMock(prettyLogExceptionResolver); Exception exception = new Exception(); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); request.setContent("".getBytes()); prettyLogExceptionResolver.logException(exception, request); verify(mockLog, times(1)).info(anyString()); }
From source file:org.jtalks.jcommune.web.exception.PrettyLogExceptionResolverTest.java
@Test public void testResolveExceptionFirstlyLogExceptionThenDebug() throws Exception { Log mockLog = replaceLoggerWithMock(prettyLogExceptionResolver); Exception exception = new Exception(); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); MockHttpServletResponse response = new MockHttpServletResponse(); Object handler = new Object(); request.setContent("".getBytes()); prettyLogExceptionResolver.resolveException(request, response, handler, exception); InOrder inOrder = inOrder(mockLog);/* www . j a v a 2s .c om*/ inOrder.verify(mockLog, times(1)).info(anyString()); inOrder.verify(mockLog, times(1)).debug(request, exception); }
From source file:org.openmrs.module.webservices.rest.web.v1_0.controller.openmrs1_8.TaskDefinitionController1_8Test.java
@Test public void shouldSaveTaskDefinition() throws Exception { SimpleObject mockTask = new SimpleObject(); mockTask.add("name", "MockTask"); mockTask.add("description", "MockTask Description"); mockTask.add("taskClass", "org.openmrs.scheduler.tasks.TestTask"); mockTask.add("startTime", "2017-08-28T23:59:59.000+0530"); mockTask.add("repeatInterval", "10"); mockTask.add("startOnStartup", false); mockTask.add("properties", null); String json = new ObjectMapper().writeValueAsString(mockTask); Assert.assertNull(mockTaskServiceWrapper.getTaskByName("MockTask")); MockHttpServletRequest req = request(RequestMethod.POST, getURI()); req.setContent(json.getBytes()); deserialize(handle(req));//from w w w .j a v a2 s . c om Assert.assertEquals(mockTaskServiceWrapper.getTaskByName("MockTask").getName(), "MockTask"); }