List of usage examples for javax.servlet.http HttpServletResponse getStatus
public int getStatus();
From source file:org.terasoluna.gfw.web.exception.HandlerExceptionResolverLoggingInterceptorTest.java
@Test public void testafterPropertiesSet() throws Throwable { testTarget = new HandlerExceptionResolverLoggingInterceptor(); testTarget.afterPropertiesSet();//from w w w. java2 s. co m this.mockExceptionLogger = spy(testTarget.getExceptionLogger()); testTarget.setExceptionLogger(mockExceptionLogger); // do setup for test case. NullPointerException occurException = new NullPointerException("null pointer exception."); HttpServletResponse mockResponse = mock(HttpServletResponse.class); ExceptionHandlerExceptionResolver resolver = new ExceptionHandlerExceptionResolver(); when(mockMethodInvocation.proceed()).thenReturn("viewname"); when(mockMethodInvocation.getThis()).thenReturn(resolver); when(mockResponse.getStatus()).thenReturn(100); when(mockMethodInvocation.getArguments()) .thenReturn(new Object[] { null, mockResponse, null, occurException }); // do test. testTarget.invoke(mockMethodInvocation); // do assert. verify(mockExceptionLogger, times(1)).info((Exception) any()); }
From source file:com.cognitivabrasil.repositorio.web.FileControllerTest.java
@Test public void testGetFile() throws IOException { com.cognitivabrasil.repositorio.data.entities.Files f3 = new Files(); f3.setId(3);/* w w w . j a v a 2s .co m*/ f3.setName("testGet.txt"); f3.setContentType("text"); f3.setLocation("somewhere"); HttpServletResponse response = new MockHttpServletResponse(); HttpServletResponse response2 = new MockHttpServletResponse(); FileController fileController = mockFiles(); // proves response and response2 are not comitted yet. Assert.assertFalse(response.isCommitted()); Assert.assertFalse(response2.isCommitted()); int fileId = 3; when(fileService.get(fileId)).thenReturn(f3); // tests non-existent id. int id = 99; fileController.getFile(id, response); Assert.assertTrue(response.isCommitted()); assertThat(HttpServletResponse.SC_GONE, equalTo(response.getStatus())); // tests valid id. // Problem: how to make the getFile method avoid the f=null. id = 3; Assert.assertFalse(response2.isCommitted()); fileController.getFile(id, response2); Assert.assertTrue(response2.isCommitted()); assertThat(HttpServletResponse.SC_GONE, equalTo(response2.getStatus())); Assert.assertTrue(response2.isCommitted()); }
From source file:org.magnum.mobilecloud.video.VideoServiceController.java
@PreAuthorize("hasRole(user)") @RequestMapping(value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}/like", method = RequestMethod.POST) public void likeVideo(@PathVariable("id") long id, HttpServletResponse response, Principal user) { String userName = user.getName(); Video v = videoRepository.findById(id); if (v == null) { response.setStatus(404);//from www .j a va2 s . co m return; } Set<Like> likes = likeRepository.findByVideo_id(id); Unlike unlike = unlikeRepository.findByVideo_idAndUser(id, userName); if (unlike != null) unlikeRepository.delete(unlike); if (likes.size() == 0) { addNewLike(v, userName); response.setStatus(200); } else { for (Like like : likes) { if (like.getUser().equals(userName)) { response.setStatus(400); } } if (response.getStatus() != 400) { addNewLike(v, userName); response.setStatus(200); } } }
From source file:org.magnum.mobilecloud.video.VideoServiceController.java
@PreAuthorize("hasRole(user)") @RequestMapping(value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}/unlike", method = RequestMethod.POST) public void unlikeVideo(@PathVariable("id") long id, HttpServletResponse response, Principal user) { String userName = user.getName(); Video v = videoRepository.findById(id); if (v == null) { response.setStatus(404);//from w w w .ja va 2 s .c om return; } Set<Unlike> unlikeSet = unlikeRepository.findByVideo_id(id); Like like = likeRepository.findByVideo_idAndUser(id, userName); if (like != null) likeRepository.delete(like); if (unlikeSet.size() == 0) { addNewUnLike(v, userName); response.setStatus(200); } else { for (Unlike unlike : unlikeSet) { if (unlike.getUser().equals(userName)) { response.setStatus(404); } } if (response.getStatus() != 404) { addNewUnLike(v, userName); response.setStatus(200); } } }
From source file:ar.com.zauber.commons.spring.exceptions.HeaderBasedStatusSimpleMappingExceptionHandlerTest.java
/** test */ public final void testFoo() { final Properties views = new Properties(); views.put(NotOwnerException.class.getName(), "notowner"); views.put(IllegalArgumentException.class.getName(), "arguments"); views.put(DataAccessResourceFailureException.class.getName(), "data"); final Properties status = new Properties(); status.put("arguments", "400"); status.put("notowner", "403"); status.put("data", "500"); AbstractView view = new AbstractView() { @Override/* w ww . j a v a 2s . co m*/ protected void renderMergedOutputModel(final Map<String, Object> model, final HttpServletRequest request, final HttpServletResponse response) throws Exception { } }; view.setBeanName("test"); final HeaderBasedStatusSimpleMappingExceptionHandler h = new HeaderBasedStatusSimpleMappingExceptionHandler( view, "application/json"); h.setDefaultStatusCode(200); h.setExceptionMappings(views); h.setStatusMappings(status); h.setDefaultErrorView("default"); MockHttpServletResponse response; ModelAndView v; response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Accept", "application/json"); v = h.resolveException(request, response, null, new IllegalArgumentException("io!io!")); assertEquals(view, v.getView()); assertEquals(400, response.getStatus()); }
From source file:com.sangupta.httpd.HttpdHandler.java
/** * Log the request details to screen// www . j av a 2 s. co m * * @param request * @param response * @param requestTime */ private void logRequest(HttpServletRequest request, HttpServletResponse response, long requestTime) { SimpleDateFormat format = new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss"); StringBuilder builder = new StringBuilder(1024); builder.append(request.getRemoteAddr()); builder.append(" - ["); builder.append(format.format(new Date(requestTime))); builder.append("] \""); builder.append(request.getMethod()); builder.append(' '); builder.append(request.getRequestURI()); builder.append(' '); builder.append(request.getProtocol()); builder.append(" - "); builder.append(response.getStatus()); builder.append(" - "); String length = response.getHeader("Content-Length"); if (length == null) { length = "0"; } builder.append(length); System.out.println(builder.toString()); }
From source file:org.wso2.carbon.device.mgt.iot.services.firealarm.FireAlarmControllerService.java
@Path("/pushalarmdata") @POST//from w w w . j a v a 2s . com @Consumes(MediaType.APPLICATION_JSON) public String pushAlarmData(final DeviceJSON dataMsg, @Context HttpServletResponse response) { String result = null; String sensorValues = dataMsg.value; log.info("Recieved Sensor Data Values: " + sensorValues); String sensors[] = sensorValues.split("-"); if (sensors.length == 3) { String temperature = sensors[0]; String bulb = sensors[1]; String fan = sensors[2]; sensorValues = "Temperature:" + temperature + "C\tBulb Status:" + bulb + "\t\tFan Status:" + fan; log.info(sensorValues); result = DeviceControllerService.pushData(dataMsg.owner, "FireAlarm", dataMsg.deviceId, System.currentTimeMillis(), "DeviceData", temperature, "TEMP", response); if (response.getStatus() != HttpStatus.SC_ACCEPTED) { return result; } result = DeviceControllerService.pushData(dataMsg.owner, "FireAlarm", dataMsg.deviceId, System.currentTimeMillis(), "DeviceData", bulb, "BULB", response); if (response.getStatus() != HttpStatus.SC_ACCEPTED) { return result; } result = DeviceControllerService.pushData(dataMsg.owner, "FireAlarm", dataMsg.deviceId, System.currentTimeMillis(), "DeviceData", fan, "FAN", response); } else { result = DeviceControllerService.pushData(dataMsg.owner, "FireAlarm", dataMsg.deviceId, System.currentTimeMillis(), "DeviceData", dataMsg.value, dataMsg.reply, response); return result; } return result; }
From source file:org.auraframework.impl.adapter.ServletUtilAdapterImplUnitTest.java
@Test public void testHandleServletExceptionSetsNoCacheForOKBeforeThrowing() throws Exception { ServletUtilAdapterImpl sua = new ServletUtilAdapterImpl(); Throwable t = new IOException(); ContextService contextService = Mockito.mock(ContextService.class); AuraContext context = Mockito.mock(AuraContext.class); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); sua.setContextService(contextService); Mockito.when(response.getStatus()).thenReturn(HttpStatus.SC_OK); sua = Mockito.spy(sua);//from w w w. java2 s.c om Throwable expected = null; try { sua.handleServletException(t, false, context, request, response, false); } catch (Throwable x) { expected = x; } Mockito.verify(sua, Mockito.times(1)).setNoCache(response); Mockito.verify(contextService, Mockito.times(1)).endContext(); assertEquals(expected, t); }
From source file:org.auraframework.impl.adapter.ServletUtilAdapterImplUnitTest.java
@Test public void testHandleServletExceptionDoesNotSetNoCacheBeforeThrowingWhenNoCacheThrows() throws Exception { ServletUtilAdapterImpl sua = new ServletUtilAdapterImpl(); Throwable t = new IOException(); ContextService contextService = Mockito.mock(ContextService.class); AuraContext context = Mockito.mock(AuraContext.class); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); sua.setContextService(contextService); sua = Mockito.spy(sua);// w w w.j a v a2s . c o m Mockito.when(response.getStatus()).thenReturn(HttpStatus.SC_OK); Mockito.doThrow(new Error()).when(response).setHeader(Mockito.any(), Mockito.any()); Throwable expected = null; try { sua.handleServletException(t, false, context, request, response, true); } catch (Throwable x) { expected = x; } Mockito.verify(sua, Mockito.times(1)).setNoCache(response); ArgumentCaptor<Integer> statusCaptor = ArgumentCaptor.forClass(Integer.class); Mockito.verify(response, Mockito.atLeastOnce()).setStatus(statusCaptor.capture()); List<Integer> statuses = statusCaptor.getAllValues(); assertEquals("Must end up with 'SERVER_ERROR'", Integer.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR), statuses.get(statuses.size() - 1)); Mockito.verify(contextService, Mockito.times(1)).endContext(); assertEquals(t, expected); }
From source file:org.smigo.log.LogHandler.java
public String getRequestDump(HttpServletRequest request, HttpServletResponse response, String separator) { StringBuilder s = new StringBuilder("####REQUEST ").append(request.getMethod()).append(" ") .append(request.getRequestURL()).append(separator); s.append("Auth type:").append(request.getAuthType()).append(separator); s.append("Principal:").append(request.getUserPrincipal()).append(separator); s.append(Log.create(request, response).toString()).append(separator); s.append("Headers:").append(separator); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); s.append(headerName).append("=").append(request.getHeader(headerName)).append(separator); }//from www . j a va 2 s. com s.append(separator); s.append("####RESPONSE").append(separator); s.append("Status:").append(response.getStatus()).append(separator); s.append("Char encoding:").append(response.getCharacterEncoding()).append(separator); s.append("Locale:").append(response.getLocale()).append(separator); s.append("Content type:").append(response.getContentType()).append(separator); s.append("Headers:").append(separator); s.append(response.getHeaderNames().stream().map(rh -> rh + "=" + response.getHeader(rh)) .collect(Collectors.joining(separator))); final Long start = (Long) request.getAttribute(RequestLogFilter.REQUEST_TIMER); if (start != null) { final long elapsedTime = System.nanoTime() - start; s.append(separator).append("####Request time elapsed:").append(elapsedTime); s.append("ns which is ").append(elapsedTime / 1000000).append("ms").append(separator); } return s.toString(); }