List of usage examples for javax.servlet.http HttpServletResponse getStatus
public int getStatus();
From source file:org.auraframework.impl.adapter.ServletUtilAdapterImplUnitTest.java
/** * Verifies second exception within handleServletException is caught and processed * we throw 'EmptyStackException' when getting InstanceStack, when * exceptionAdapter.handleException(death) handle the exception, * we throw second exception, then verify we printout the error message to response's writer *//*from w w w. j a v a 2 s.co m*/ @Test public void testHandleExceptionDoubleDeathCaught() throws Exception { PrintWriter writer = Mockito.mock(PrintWriter.class); HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class); HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class); ContextService mockContextService = Mockito.mock(ContextService.class); AuraContext mockContext = Mockito.mock(AuraContext.class); ConfigAdapter mockConfigAdapter = Mockito.mock(ConfigAdapter.class); ExceptionAdapter mockExceptionAdapter = Mockito.mock(ExceptionAdapter.class); Throwable firstException = new EmptyStackException(); String ccmeMsg = "double dead"; Throwable secondException = new ConcurrentModificationException("double dead"); Mockito.when(mockResponse.getWriter()).thenReturn(writer); Mockito.when(mockResponse.getStatus()).thenReturn(HttpStatus.SC_OK); Mockito.when(mockContext.getFormat()).thenReturn(AuraContext.Format.HTML); Mockito.when(mockContext.getMode()).thenReturn(Mode.DEV); Mockito.when(mockConfigAdapter.isProduction()).thenReturn(false); Mockito.when(mockContextService.getCurrentContext()).thenReturn(mockContext); Mockito.when(mockContext.getInstanceStack()).thenThrow(firstException); Mockito.when(mockExceptionAdapter.handleException(firstException)).thenThrow(secondException); Throwable exception = new InterruptedException("opps"); ServletUtilAdapterImpl adapter = Mockito.spy(new ServletUtilAdapterImpl()); adapter.setContextService(mockContextService); adapter.setConfigAdapter(mockConfigAdapter); adapter.setExceptionAdapter(mockExceptionAdapter); adapter.handleServletException(exception, true, mockContext, mockRequest, mockResponse, true); ArgumentCaptor<String> exceptionMessage = ArgumentCaptor.forClass(String.class); Mockito.verify(writer, Mockito.times(1)).println(exceptionMessage.capture()); assertEquals(ccmeMsg, exceptionMessage.getValue()); // in this case we return SC_OK, and we set non-cacheable. Mockito.verify(mockResponse, Mockito.atLeastOnce()).setStatus(HttpStatus.SC_OK); Mockito.verify(mockContextService, Mockito.atLeastOnce()).endContext(); Mockito.verify(adapter, Mockito.atLeastOnce()).setNoCache(mockResponse); }
From source file:com.groupon.odo.Proxy.java
/** * Log original response/* ww w . j av a 2s . co m*/ * * @param httpServletResponse * @param history * @throws URIException */ private void logOriginalResponseHistory(HttpServletResponse httpServletResponse, History history, OutputStream outStream) throws URIException { RequestInformation requestInfo = requestInformation.get(); if (requestInfo.handle && requestInfo.client.getIsActive()) { logger.info("Storing original response history"); history.setOriginalResponseHeaders(HttpUtilities.getHeaders(httpServletResponse)); history.setOriginalResponseCode(Integer.toString(httpServletResponse.getStatus())); history.setOriginalResponseContentType(httpServletResponse.getContentType()); history.setOriginalResponseData(outStream.toString()); logger.info("Done storing"); } }
From source file:de.digitalcollections.streaming.euphoria.controller.StreamingController.java
private String setContentHeaders(HttpServletRequest request, HttpServletResponse response, ResourceInfo resourceInfo, List<Range> ranges) { String contentType = resourceInfo.contentType; // If content type is unknown, then set the default value. // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp // To add new content types, add new mime-mapping entry in web.xml. if (contentType == null) { contentType = "application/octet-stream"; }//from w w w . ja va2s . c o m String disposition = isAttachment(request, contentType) ? "attachment" : "inline"; String filename = encodeURI(resourceInfo.fileName); response.setHeader("Content-Disposition", String.format(CONTENT_DISPOSITION_HEADER, disposition, filename)); response.setHeader("Accept-Ranges", "bytes"); if (ranges.size() == 1) { Range range = ranges.get(0); response.setContentType(contentType); response.setHeader("Content-Length", String.valueOf(range.length)); if (response.getStatus() == HttpServletResponse.SC_PARTIAL_CONTENT) { response.setHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + resourceInfo.length); } } else { response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); } return contentType; }
From source file:org.structr.web.servlet.UploadServlet.java
@Override protected void doPut(final HttpServletRequest request, final HttpServletResponse response) throws ServletException { try (final Tx tx = StructrApp.getInstance().tx(false, false, false)) { final String uuid = PathHelper.getName(request.getPathInfo()); if (uuid == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getOutputStream().write("URL path doesn't end with UUID.\n".getBytes("UTF-8")); return; }//w ww. j a va 2 s . c o m Matcher matcher = threadLocalUUIDMatcher.get(); matcher.reset(uuid); if (!matcher.matches()) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getOutputStream() .write("ERROR (400): URL path doesn't end with UUID.\n".getBytes("UTF-8")); return; } final SecurityContext securityContext = getConfig().getAuthenticator() .initializeAndExamineRequest(request, response); // Ensure access mode is frontend securityContext.setAccessMode(AccessMode.Frontend); request.setCharacterEncoding("UTF-8"); // Important: Set character encoding before calling response.getWriter() !!, see Servlet Spec 5.4 response.setCharacterEncoding("UTF-8"); // don't continue on redirects if (response.getStatus() == 302) { return; } uploader.setFileSizeMax(MEGABYTE * Long.parseLong(StructrApp.getConfigurationValue("UploadServlet.maxFileSize", MAX_FILE_SIZE))); uploader.setSizeMax(MEGABYTE * Long .parseLong(StructrApp.getConfigurationValue("UploadServlet.maxRequestSize", MAX_REQUEST_SIZE))); List<FileItem> fileItemsList = uploader.parseRequest(request); Iterator<FileItem> fileItemsIterator = fileItemsList.iterator(); while (fileItemsIterator.hasNext()) { final FileItem fileItem = fileItemsIterator.next(); try { final GraphObject node = StructrApp.getInstance().getNodeById(uuid); if (node == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.getOutputStream().write("ERROR (404): File not found.\n".getBytes("UTF-8")); } if (node instanceof org.structr.web.entity.AbstractFile) { final org.structr.dynamic.File file = (org.structr.dynamic.File) node; if (file.isGranted(Permission.write, securityContext)) { FileHelper.writeToFile(file, fileItem.getInputStream()); file.increaseVersion(); // upload trigger file.notifyUploadCompletion(); } else { response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.getOutputStream() .write("ERROR (403): Write access forbidden.\n".getBytes("UTF-8")); } } } catch (IOException ex) { logger.log(Level.WARNING, "Could not write to file", ex); } } tx.success(); } catch (FrameworkException | IOException | FileUploadException t) { t.printStackTrace(); logger.log(Level.SEVERE, "Exception while processing request", t); UiAuthenticator.writeInternalServerError(response); } }
From source file:byps.http.HHttpServlet.java
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (log.isDebugEnabled()) log.debug("service("); if (log.isDebugEnabled()) { log.debug("method=" + request.getMethod()); log.debug("params= " + request.getParameterMap()); }/*from w w w . jav a2 s . c om*/ int status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; Throwable ex = null; try { super.service(request, response); status = response.getStatus(); } catch (Throwable e) { ex = e; if (!(e instanceof ClientAbortException)) { if (e instanceof FileNotFoundException) { status = HttpServletResponse.SC_NOT_FOUND; } try { response.sendError(status, e.getMessage()); } catch (Throwable e2) { // java.lang.IllegalStateException: Cannot call sendError() after the // response has been committed log.debug("ex2=" + e2 + " caused by:", e); } } } finally { switch (status) { case HttpServletResponse.SC_OK: case BExceptionC.RESEND_LONG_POLL: case BExceptionC.UNAUTHORIZED: case BExceptionC.SESSION_CLOSED: if (log.isDebugEnabled()) log.debug(makeLogRequest(request, status)); break; case BExceptionC.FORBIDDEN: case BExceptionC.TIMEOUT: if (log.isInfoEnabled()) log.info(makeLogRequest(request, status)); break; default: if (log.isInfoEnabled()) log.info(makeLogRequest(request, status), ex); break; } } if (log.isDebugEnabled()) log.debug(")service"); }
From source file:org.structr.web.servlet.UploadServlet.java
@Override protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException { try (final Tx tx = StructrApp.getInstance().tx()) { if (!ServletFileUpload.isMultipartContent(request)) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getOutputStream()//from w ww.j a v a 2s. c om .write("ERROR (400): Request does not contain multipart content.\n".getBytes("UTF-8")); return; } final SecurityContext securityContext = getConfig().getAuthenticator() .initializeAndExamineRequest(request, response); if (securityContext.getUser(false) == null && Boolean.FALSE.equals(Boolean.parseBoolean( StructrApp.getConfigurationValue("UploadServlet.allowAnonymousUploads", "false")))) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.getOutputStream().write("ERROR (403): Anonymous uploads forbidden.\n".getBytes("UTF-8")); return; } // Ensure access mode is frontend securityContext.setAccessMode(AccessMode.Frontend); request.setCharacterEncoding("UTF-8"); // Important: Set character encoding before calling response.getWriter() !!, see Servlet Spec 5.4 response.setCharacterEncoding("UTF-8"); // don't continue on redirects if (response.getStatus() == 302) { return; } final String pathInfo = request.getPathInfo(); String type = null; if (StringUtils.isNotBlank(pathInfo)) { type = SchemaHelper.normalizeEntityName(StringUtils.stripStart(pathInfo.trim(), "/")); } uploader.setFileSizeMax(MEGABYTE * Long.parseLong(StructrApp.getConfigurationValue("UploadServlet.maxFileSize", MAX_FILE_SIZE))); uploader.setSizeMax(MEGABYTE * Long .parseLong(StructrApp.getConfigurationValue("UploadServlet.maxRequestSize", MAX_REQUEST_SIZE))); response.setContentType("text/html"); final PrintWriter out = response.getWriter(); List<FileItem> fileItemsList = uploader.parseRequest(request); Iterator<FileItem> fileItemsIterator = fileItemsList.iterator(); final Map<String, Object> params = new HashMap<>(); while (fileItemsIterator.hasNext()) { final FileItem item = fileItemsIterator.next(); if (item.isFormField()) { params.put(item.getFieldName(), item.getString()); } else { try { final String contentType = item.getContentType(); boolean isImage = (contentType != null && contentType.startsWith("image")); boolean isVideo = (contentType != null && contentType.startsWith("video")); // Override type from path info if (params.containsKey(NodeInterface.type.jsonName())) { type = (String) params.get(NodeInterface.type.jsonName()); } final Class cls = type != null ? SchemaHelper.getEntityClassForRawType(type) : (isImage ? Image.class : (isVideo ? VideoFile.class : org.structr.dynamic.File.class)); final String name = item.getName().replaceAll("\\\\", "/"); final org.structr.dynamic.File newFile = FileHelper.createFile(securityContext, IOUtils.toByteArray(item.getInputStream()), contentType, cls); newFile.setProperty(AbstractNode.name, PathHelper.getName(name)); if (!newFile.validatePath(securityContext, null)) { newFile.setProperty(AbstractNode.name, name.concat("_").concat(FileHelper.getDateString())); } PropertyMap additionalProperties = PropertyMap.inputTypeToJavaType(securityContext, cls, params); for (PropertyKey key : additionalProperties.keySet()) { newFile.setProperty(key, additionalProperties.get(key)); } // upload trigger newFile.notifyUploadCompletion(); // Just write out the uuids of the new files out.write(newFile.getUuid()); } catch (IOException ex) { logger.log(Level.WARNING, "Could not upload file", ex); } } } tx.success(); } catch (FrameworkException | IOException | FileUploadException t) { t.printStackTrace(); logger.log(Level.SEVERE, "Exception while processing request", t); UiAuthenticator.writeInternalServerError(response); } }
From source file:org.jitsi.videobridge.rest.HandlerImpl.java
/** * {@inheritDoc}/*from w w w .j a v a2 s. com*/ */ @Override protected void handleJSON(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { super.handleJSON(target, baseRequest, request, response); if (baseRequest.isHandled()) return; // The super implementation has handled the request. // The target starts with "/colibri/". if (target.startsWith(COLIBRI_TARGET)) { target = target.substring(COLIBRI_TARGET.length()); // FIXME In order to not invoke beginResponse() and endResponse() in // each and every one of the methods to which handleColibriJSON() // delegates/forwards, we will invoke them here. However, we do not // know whether handleColibriJSON() will actually handle the // request. As a workaround we will mark the response with a status // code that we know handleColibriJSON() does not utilize (at the // time of this writing) and we will later recognize whether // handleColibriJSON() has handled the request by checking whether // the response is still marked with the unused status code. int oldResponseStatus = response.getStatus(); response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED); // All responses to requests for resources under the base /colibri/ // are in JSON format. beginResponse(target, baseRequest, request, response); handleColibriJSON(target, baseRequest, request, response); int newResponseStatus = response.getStatus(); if (newResponseStatus == HttpServletResponse.SC_NOT_IMPLEMENTED) { // Restore the status code which was in place before we replaced // it with our workaround. response.setStatus(oldResponseStatus); } else { // It looks like handleColibriJSON() indeed handled the request. endResponse(target, baseRequest, request, response); } } else { // Initially, we had VERSION_TARGET equal to /version. But such an // HTTP resource could be rewritten by Meet. In order to decrease // the risk of rewriting, we moved the VERSION_TARGET to // /about/version. For the sake of compatiblity though, we are // preserving /version. String versionTarget = "/version"; if (versionTarget.equals(target)) { target = target.substring(versionTarget.length()); handleVersionJSON(target, baseRequest, request, response); } } }
From source file:org.structr.web.servlet.DeploymentServlet.java
@Override protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException { try (final Tx tx = StructrApp.getInstance().tx()) { if (!ServletFileUpload.isMultipartContent(request)) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getOutputStream()/*from ww w. jav a2s .c o m*/ .write("ERROR (400): Request does not contain multipart content.\n".getBytes("UTF-8")); return; } final SecurityContext securityContext; try { securityContext = getConfig().getAuthenticator().initializeAndExamineRequest(request, response); } catch (AuthenticationException ae) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.getOutputStream().write("ERROR (401): Invalid user or password.\n".getBytes("UTF-8")); return; } if (securityContext.getUser(false) == null && !Settings.DeploymentAllowAnonymousUploads.getValue()) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.getOutputStream().write("ERROR (401): Anonymous uploads forbidden.\n".getBytes("UTF-8")); return; } // Ensure access mode is frontend securityContext.setAccessMode(AccessMode.Frontend); request.setCharacterEncoding("UTF-8"); // Important: Set character encoding before calling response.getWriter() !!, see Servlet Spec 5.4 response.setCharacterEncoding("UTF-8"); // don't continue on redirects if (response.getStatus() == 302) { return; } final String pathInfo = request.getPathInfo(); String type = null; if (StringUtils.isNotBlank(pathInfo)) { type = SchemaHelper.normalizeEntityName(StringUtils.stripStart(pathInfo.trim(), "/")); } uploader.setFileSizeMax(MEGABYTE * Settings.DeploymentMaxFileSize.getValue()); uploader.setSizeMax(MEGABYTE * Settings.DeploymentMaxRequestSize.getValue()); response.setContentType("text/html"); final List<FileItem> fileItemsList = uploader.parseRequest(request); final Iterator<FileItem> fileItemsIterator = fileItemsList.iterator(); final Map<String, Object> params = new HashMap<>(); while (fileItemsIterator.hasNext()) { final FileItem item = fileItemsIterator.next(); try { final String directoryPath = "/tmp/" + UUID.randomUUID(); final String filePath = directoryPath + ".zip"; File file = new File(filePath); Files.write(IOUtils.toByteArray(item.getInputStream()), file); unzip(file, directoryPath); DeployCommand deployCommand = StructrApp.getInstance(securityContext) .command(DeployCommand.class); final Map<String, Object> attributes = new HashMap<>(); attributes.put("source", directoryPath + "/" + StringUtils.substringBeforeLast(item.getName(), ".")); deployCommand.execute(attributes); file.deleteOnExit(); File dir = new File(directoryPath); dir.deleteOnExit(); } catch (IOException ex) { logger.warn("Could not upload file", ex); } } tx.success(); } catch (FrameworkException | IOException | FileUploadException t) { logger.error("Exception while processing request", t); UiAuthenticator.writeInternalServerError(response); } }
From source file:com.groupon.odo.Proxy.java
/** * @param httpServletResponse/* ww w. j av a2s . co m*/ * @param outStream * @param jsonpCallback * @throws IOException */ private void writeResponseOutput(HttpServletResponse httpServletResponse, OutputStream outStream, String jsonpCallback) throws IOException { RequestInformation requestInfo = requestInformation.get(); // check to see if this is chunked boolean chunked = false; if (httpServletResponse.containsHeader(HttpUtilities.STRING_TRANSFER_ENCODING) && httpServletResponse .getHeader(HttpUtilities.STRING_TRANSFER_ENCODING).compareTo("chunked") == 0) { httpServletResponse.setHeader(HttpUtilities.STRING_CONNECTION, HttpUtilities.STRING_CHUNKED); chunked = true; } // reattach JSONP if needed if (requestInfo.outputString != null && jsonpCallback != null) { requestInfo.outputString = jsonpCallback + "(" + requestInfo.outputString + ");"; } // don't do this if we got a HTTP 304 since there is no data to send back if (httpServletResponse.getStatus() != HttpServletResponse.SC_NOT_MODIFIED) { logger.info("Chunked: {}, {}", chunked, httpServletResponse.getBufferSize()); if (!chunked) { // change the content length header to the new length if (requestInfo.outputString != null) { httpServletResponse.setContentLength(requestInfo.outputString.getBytes().length); } else { httpServletResponse.setContentLength(((ByteArrayOutputStream) outStream).toByteArray().length); } } OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); if (requestInfo.outputString != null) { outputStreamClientResponse.write(requestInfo.outputString.getBytes()); } else { outputStreamClientResponse.write(((ByteArrayOutputStream) outStream).toByteArray()); } httpServletResponse.flushBuffer(); logger.info("Done writing"); } // outstr might still be null.. let's try to set it from outStream if (requestInfo.outputString == null) { try { requestInfo.outputString = outStream.toString(); } catch (Exception e) { // can ignore any issues.. worst case outstr is still null } } }
From source file:org.structr.web.auth.UiAuthenticator.java
/** * This method checks all configured external authentication services. * * @param request/*from w ww .j av a2 s . c om*/ * @param response * @return user */ protected static Principal checkExternalAuthentication(final HttpServletRequest request, final HttpServletResponse response) throws FrameworkException { final String path = PathHelper.clean(request.getPathInfo()); final String[] uriParts = PathHelper.getParts(path); logger.log(Level.FINE, "Checking external authentication ..."); if (uriParts == null || uriParts.length != 3 || !("oauth".equals(uriParts[0]))) { logger.log(Level.FINE, "Incorrect URI parts for OAuth process, need /oauth/<name>/<action>"); return null; } final String name = uriParts[1]; final String action = uriParts[2]; // Try to getValue an OAuth2 server for the given name final StructrOAuthClient oauthServer = StructrOAuthClient.getServer(name); if (oauthServer == null) { logger.log(Level.FINE, "No OAuth2 authentication server configured for {0}", path); return null; } if ("login".equals(action)) { try { response.sendRedirect(oauthServer.getEndUserAuthorizationRequestUri(request)); return null; } catch (Exception ex) { logger.log(Level.SEVERE, "Could not send redirect to authorization server", ex); } } else if ("auth".equals(action)) { final String accessToken = oauthServer.getAccessToken(request); final SecurityContext superUserContext = SecurityContext.getSuperUserInstance(); if (accessToken != null) { logger.log(Level.FINE, "Got access token {0}", accessToken); //securityContext.setAttribute("OAuthAccessToken", accessToken); String value = oauthServer.getCredential(request); logger.log(Level.FINE, "Got credential value: {0}", new Object[] { value }); if (value != null) { PropertyKey credentialKey = oauthServer.getCredentialKey(); Principal user = AuthHelper.getPrincipalForCredential(credentialKey, value); if (user == null && userAutoCreate) { user = RegistrationResource.createUser(superUserContext, credentialKey, value, true, userClass); } if (user != null) { AuthHelper.doLogin(request, user); HtmlServlet.setNoCacheHeaders(response); try { logger.log(Level.FINE, "Response status: {0}", response.getStatus()); response.sendRedirect(oauthServer.getReturnUri()); } catch (IOException ex) { logger.log(Level.SEVERE, "Could not redirect to {0}: {1}", new Object[] { oauthServer.getReturnUri(), ex }); } return user; } } } } try { response.sendRedirect(oauthServer.getErrorUri()); } catch (IOException ex) { logger.log(Level.SEVERE, "Could not redirect to {0}: {1}", new Object[] { oauthServer.getReturnUri(), ex }); } return null; }