List of usage examples for javax.servlet.http HttpServletResponse getContentType
public String getContentType();
From source file:org.codelabor.system.file.web.servlet.FileUploadServlet.java
/** * ?? .//from w ww . j a v a2 s. c om * * @param request * * @param response * ? * @throws Exception * */ protected void download(HttpServletRequest request, HttpServletResponse response) throws Exception { WebApplicationContext ctx = WebApplicationContextUtils .getRequiredWebApplicationContext(this.getServletContext()); FileManager fileManager = (FileManager) ctx.getBean("fileManager"); Map<String, Object> paramMap = RequestUtils.getParameterMap(request); logger.debug("paramMap: {}", paramMap.toString()); String fileId = (String) paramMap.get("fileId"); StringBuilder sb = new StringBuilder(); FileDTO fileDTO; fileDTO = fileManager.selectFileByFileId(fileId); logger.debug("fileDTO: {}", fileDTO); String repositoryPath = fileDTO.getRepositoryPath(); String uniqueFilename = fileDTO.getUniqueFilename(); String realFilename = fileDTO.getRealFilename(); InputStream inputStream = null; if (StringUtils.isNotEmpty(repositoryPath)) { // FILE_SYSTEM sb.setLength(0); sb.append(repositoryPath); if (!repositoryPath.endsWith(File.separator)) { sb.append(File.separator); } sb.append(uniqueFilename); File file = new File(sb.toString()); inputStream = new FileInputStream(file); } else { // DATABASE byte[] bytes = new byte[] {}; if (fileDTO.getFileSize() > 0) { bytes = fileDTO.getBytes(); } inputStream = new ByteArrayInputStream(bytes); } // set response contenttype, header String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8"); logger.debug("realFilename: {}", realFilename); logger.debug("encodedRealFilename: {}", encodedRealFilename); response.setContentType(org.codelabor.system.file.FileConstants.CONTENT_TYPE); sb.setLength(0); if (request.getHeader(HttpRequestHeaderConstants.USER_AGENT).indexOf("MSIE5.5") > -1) { sb.append("filename="); } else { sb.append("attachment; filename="); } sb.append(encodedRealFilename); response.setHeader(HttpResponseHeaderConstants.CONTENT_DISPOSITION, sb.toString()); logger.debug("header: {}", sb.toString()); logger.debug("character encoding: {}", response.getCharacterEncoding()); logger.debug("content type: {}", response.getContentType()); logger.debug("bufferSize: {}", response.getBufferSize()); logger.debug("locale: {}", response.getLocale()); BufferedInputStream bufferdInputStream = new BufferedInputStream(inputStream); ServletOutputStream servletOutputStream = response.getOutputStream(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(servletOutputStream); int bytesRead; byte buffer[] = new byte[2048]; while ((bytesRead = bufferdInputStream.read(buffer)) != -1) { bufferedOutputStream.write(buffer, 0, bytesRead); } // flush stream bufferedOutputStream.flush(); // close stream inputStream.close(); bufferdInputStream.close(); servletOutputStream.close(); bufferedOutputStream.close(); }
From source file:org.codelabor.system.file.web.spring.controller.FileController.java
@RequestMapping("/download") public void download(@RequestHeader("User-Agent") String userAgent, @RequestParam("fileId") String fileId, HttpServletResponse response) throws Exception { FileDTO fileDTO = fileManager.selectFileByFileId(fileId); logger.debug("fileDTO: {}", fileDTO); String repositoryPath = fileDTO.getRepositoryPath(); String uniqueFilename = fileDTO.getUniqueFilename(); String realFilename = fileDTO.getRealFilename(); InputStream inputStream = null; StringBuilder sb = new StringBuilder(); if (StringUtils.isNotEmpty(repositoryPath)) { // FILE_SYSTEM sb.append(repositoryPath);/* w w w . ja va 2 s . c om*/ if (!repositoryPath.endsWith(File.separator)) { sb.append(File.separator); } sb.append(uniqueFilename); File file = new File(sb.toString()); inputStream = new FileInputStream(file); } else { // DATABASE byte[] bytes = new byte[] {}; if (fileDTO.getFileSize() > 0) { bytes = fileDTO.getBytes(); } inputStream = new ByteArrayInputStream(bytes); } // set response contenttype, header String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8"); logger.debug("realFilename: {}", realFilename); logger.debug("encodedRealFilename: {}", encodedRealFilename); response.setContentType(org.codelabor.system.file.FileConstants.CONTENT_TYPE); sb.setLength(0); if (userAgent.indexOf("MSIE5.5") > -1) { sb.append("filename="); } else { sb.append("attachment; filename="); } sb.append(encodedRealFilename); response.setHeader(HttpResponseHeaderConstants.CONTENT_DISPOSITION, sb.toString()); logger.debug("header: {}", sb.toString()); logger.debug("character encoding: {}", response.getCharacterEncoding()); logger.debug("content type: {}", response.getContentType()); logger.debug("bufferSize: {}", response.getBufferSize()); logger.debug("locale: {}", response.getLocale()); BufferedInputStream bufferdInputStream = new BufferedInputStream(inputStream); ServletOutputStream servletOutputStream = response.getOutputStream(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(servletOutputStream); int bytesRead; byte buffer[] = new byte[2048]; while ((bytesRead = bufferdInputStream.read(buffer)) != -1) { bufferedOutputStream.write(buffer, 0, bytesRead); } // flush stream bufferedOutputStream.flush(); // close stream inputStream.close(); bufferdInputStream.close(); servletOutputStream.close(); bufferedOutputStream.close(); }
From source file:org.codelabor.system.file.web.spring.controller.FileController.java
@RequestMapping("/view") public void view(@RequestParam("fileId") String fileId, HttpServletResponse response) throws Exception { StringBuilder stringBuilder = null; FileDTO fileDTO;/*w w w .ja v a2 s. c om*/ fileDTO = fileManager.selectFileByFileId(fileId); logger.debug("fileDTO: {}", fileDTO); String repositoryPath = fileDTO.getRepositoryPath(); String uniqueFilename = fileDTO.getUniqueFilename(); String realFilename = fileDTO.getRealFilename(); InputStream inputStream = null; if (StringUtils.isNotEmpty(repositoryPath)) { // FILE_SYSTEM stringBuilder = new StringBuilder(); stringBuilder.append(repositoryPath); if (!repositoryPath.endsWith(File.separator)) { stringBuilder.append(File.separator); } stringBuilder.append(uniqueFilename); File file = new File(stringBuilder.toString()); inputStream = new FileInputStream(file); } else { // DATABASE byte[] bytes = new byte[] {}; if (fileDTO.getFileSize() > 0) { bytes = fileDTO.getBytes(); } inputStream = new ByteArrayInputStream(bytes); } response.setContentType(fileDTO.getContentType()); // set response contenttype, header String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8"); logger.debug("realFilename: {}", realFilename); logger.debug("encodedRealFilename: {}", encodedRealFilename); logger.debug("character encoding: {}", response.getCharacterEncoding()); logger.debug("content type: {}", response.getContentType()); logger.debug("bufferSize: {}", response.getBufferSize()); logger.debug("locale: {}", response.getLocale()); BufferedInputStream bufferdInputStream = new BufferedInputStream(inputStream); ServletOutputStream servletOutputStream = response.getOutputStream(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(servletOutputStream); int bytesRead; byte buffer[] = new byte[2048]; while ((bytesRead = bufferdInputStream.read(buffer)) != -1) { bufferedOutputStream.write(buffer, 0, bytesRead); } // flush stream bufferedOutputStream.flush(); // close stream inputStream.close(); bufferdInputStream.close(); servletOutputStream.close(); bufferedOutputStream.close(); }
From source file:org.codelabor.system.file.web.struts.action.FileDownloadAction.java
@Override protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> paramMap = RequestUtils.getParameterMap(request); logger.debug(paramMap.toString());/*from w w w .j a va 2 s .com*/ String fileId = (String) paramMap.get("fileId"); StreamInfo streamInfo = null; WebApplicationContext ctx = WebApplicationContextUtils .getRequiredWebApplicationContext(servlet.getServletContext()); FileManager fileManager = (FileManager) ctx.getBean("fileManager"); FileDTO fileDTO = fileManager.selectFileByFileId(fileId); logger.debug("fileDTO: {}", fileDTO); String repositoryPath = fileDTO.getRepositoryPath(); String uniqueFilename = fileDTO.getUniqueFilename(); String realFilename = fileDTO.getRealFilename(); StringBuilder sb = new StringBuilder(); // FILE_SYSTEM if (StringUtils.isNotEmpty(repositoryPath)) { sb.append(repositoryPath); if (!repositoryPath.endsWith(File.separator)) { sb.append(File.separator); } sb.append(uniqueFilename); File file = new File(sb.toString()); streamInfo = new FileStreamInfo(org.codelabor.system.file.FileConstants.CONTENT_TYPE, file); // DATABASE } else { byte[] bytes = fileDTO.getBytes(); streamInfo = new ByteArrayStreamInfo(org.codelabor.system.file.FileConstants.CONTENT_TYPE, bytes); } // set response contenttype, header String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8"); logger.debug("realFilename: {}", realFilename); logger.debug("encodedRealFilename: {}", encodedRealFilename); response.setContentType(org.codelabor.system.file.FileConstants.CONTENT_TYPE); sb.setLength(0); if (request.getHeader(HttpRequestHeaderConstants.USER_AGENT).indexOf("MSIE5.5") > -1) { sb.append("filename="); } else { sb.append("attachment; filename="); } // stringBuilder.append("\""); sb.append(encodedRealFilename); // stringBuilder.append("\""); response.setHeader(HttpResponseHeaderConstants.CONTENT_DISPOSITION, sb.toString()); logger.debug("header: {}", sb.toString()); logger.debug("character encoding: {}", response.getCharacterEncoding()); logger.debug("content type: {}", response.getContentType()); logger.debug("bufferSize: {}", response.getBufferSize()); logger.debug("locale: {}", response.getLocale()); return streamInfo; }
From source file:org.codelabor.system.file.web.struts.action.FileUploadAction.java
public ActionForward view(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { WebApplicationContext ctx = WebApplicationContextUtils .getRequiredWebApplicationContext(getServlet().getServletContext()); FileManager fileManager = (FileManager) ctx.getBean("fileManager"); Map<String, Object> paramMap = RequestUtils.getParameterMap(request); logger.debug("paramMap: {}", paramMap.toString()); String fileId = (String) paramMap.get("fileId"); StringBuilder sb = new StringBuilder(); FileDTO fileDTO;/*from ww w .ja v a 2 s. c o m*/ fileDTO = fileManager.selectFileByFileId(fileId); logger.debug("fileDTO: {}", fileDTO); String repositoryPath = fileDTO.getRepositoryPath(); String uniqueFilename = fileDTO.getUniqueFilename(); String realFilename = fileDTO.getRealFilename(); InputStream inputStream = null; if (StringUtils.isNotEmpty(repositoryPath)) { // FILE_SYSTEM sb.setLength(0); sb.append(repositoryPath); if (!repositoryPath.endsWith(File.separator)) { sb.append(File.separator); } sb.append(uniqueFilename); File file = new File(sb.toString()); inputStream = new FileInputStream(file); } else { // DATABASE byte[] bytes = new byte[] {}; if (fileDTO.getFileSize() > 0) { bytes = fileDTO.getBytes(); } inputStream = new ByteArrayInputStream(bytes); } response.setContentType(fileDTO.getContentType()); // set response contenttype, header String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8"); logger.debug("realFilename: {}", realFilename); logger.debug("encodedRealFilename: {}", encodedRealFilename); logger.debug("character encoding: {}", response.getCharacterEncoding()); logger.debug("content type: {}", response.getContentType()); logger.debug("bufferSize: {}", response.getBufferSize()); logger.debug("locale: {}", response.getLocale()); BufferedInputStream bufferdInputStream = new BufferedInputStream(inputStream); ServletOutputStream servletOutputStream = response.getOutputStream(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(servletOutputStream); int bytesRead; byte buffer[] = new byte[2048]; while ((bytesRead = bufferdInputStream.read(buffer)) != -1) { bufferedOutputStream.write(buffer, 0, bytesRead); } // flush stream bufferedOutputStream.flush(); // close stream inputStream.close(); bufferdInputStream.close(); servletOutputStream.close(); bufferedOutputStream.close(); return null; }
From source file:org.dbflute.saflute.web.servlet.filter.RequestLoggingFilter.java
protected void buildResponseInfo(StringBuilder sb, HttpServletRequest request, HttpServletResponse response) { sb.append("Response class=" + response.getClass().getName()); sb.append(", ContentType=").append(response.getContentType()); sb.append(", Committed=").append(response.isCommitted()); String exp = response.toString().trim(); if (exp != null) { exp = replaceString(exp, "\r\n", "\n"); exp = replaceString(exp, "\n", " "); final int limitLength = 120; if (exp.length() >= limitLength) { // it is possible that Response toString() show all HTML strings // so cut it to suppress too big logging here exp = exp.substring(0, limitLength) + "..."; }//from ww w . jav a 2s . c o m sb.append(LF).append(IND); sb.append(", toString()=").append(exp); // e.g. Jetty // HTTP/1.1 200 Expires: Thu, 01-Jan-1970 00:00:00 GMT Set-Cookie: ... } }
From source file:org.encuestame.core.security.CustomAuthenticationEntryPoint.java
/** * *///from www . j av a 2s .co m @Override public void commence(HttpServletRequest request, HttpServletResponse response, org.springframework.security.core.AuthenticationException authException) throws IOException, ServletException { if (authException != null) { // you can check for the spefic exception here and redirect like // this logger.debug("respnse" + response.toString()); logger.debug("respnse" + response.getContentType()); logger.debug("request" + request.toString()); logger.debug("request" + request.getContentType()); //response.sendRedirect("403.html"); } HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String redirectUrl = null; if (useForward) { if (forceHttps && "http".equals(request.getScheme())) { // First redirect the current request to HTTPS. // When that request is received, the forward to the login page // will be used. redirectUrl = buildHttpsRedirectUrlForRequest(httpRequest); } if (redirectUrl == null) { String loginForm = determineUrlToUseForThisRequest(httpRequest, httpResponse, authException); if (logger.isDebugEnabled()) { logger.debug("Server side forward to: " + loginForm); } RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(loginForm); dispatcher.forward(request, response); return; } } else { // redirect to login page. Use https if forceHttps true redirectUrl = buildRedirectUrlToLoginPage(httpRequest, httpResponse, authException); } redirectStrategy.sendRedirect(httpRequest, httpResponse, redirectUrl); }
From source file:org.exist.http.urlrewrite.XQueryURLRewrite.java
private void applyViews(ModelAndView modelView, List<URLRewrite> views, HttpServletResponse response, RequestWrapper modifiedRequest, HttpServletResponse currentResponse) throws IOException, ServletException { int status;//from w ww .j a va 2 s . c om HttpServletResponse wrappedResponse = currentResponse; for (int i = 0; i < views.size(); i++) { final URLRewrite view = (URLRewrite) views.get(i); // get data returned from last action byte[] data = ((CachingResponseWrapper) wrappedResponse).getData(); // determine request method to use for calling view String method = view.getMethod(); if (method == null) { method = "POST"; // default is POST } final RequestWrapper wrappedReq = new RequestWrapper(modifiedRequest); wrappedReq.allowCaching(false); wrappedReq.setMethod(method); wrappedReq.setBasePath(modifiedRequest.getBasePath()); wrappedReq.setCharacterEncoding(wrappedResponse.getCharacterEncoding()); wrappedReq.setContentType(wrappedResponse.getContentType()); if (data != null) { wrappedReq.setData(data); } wrappedResponse = new CachingResponseWrapper(response, true); doRewrite(view, wrappedReq, wrappedResponse); // catch errors in the view status = ((CachingResponseWrapper) wrappedResponse).getStatus(); if (status >= 400) { if (modelView != null && modelView.hasErrorHandlers()) { data = ((CachingResponseWrapper) wrappedResponse).getData(); final String msg = data == null ? "" : new String(data, UTF_8); modifiedRequest.setAttribute(RQ_ATTR_ERROR, msg); applyViews(null, modelView.errorHandlers, response, modifiedRequest, wrappedResponse); break; } else { flushError(response, wrappedResponse); } break; } else if (i == views.size() - 1) { ((CachingResponseWrapper) wrappedResponse).flush(); } } }
From source file:org.exist.http.urlrewrite.XQueryURLRewrite.java
private void flushError(HttpServletResponse response, HttpServletResponse wrappedResponse) throws IOException { if (!response.isCommitted()) { final byte[] data = ((CachingResponseWrapper) wrappedResponse).getData(); if (data != null) { response.setContentType(wrappedResponse.getContentType()); response.setCharacterEncoding(wrappedResponse.getCharacterEncoding()); response.getOutputStream().write(data); response.flushBuffer();/*from ww w .ja va2 s . c o m*/ } } }
From source file:org.gluewine.rest_server.RESTServlet.java
@Override public void service(HttpServletRequest req, HttpServletResponse resp) throws IOException { try {/*from w w w. ja v a 2s . c o m*/ RESTBean rb = new RESTBean(); rb.request = req; rb.response = resp; beans.put(Thread.currentThread(), rb); String path = getRESTPath(req); if (logger.isDebugEnabled()) logger.debug("Received REST request for : " + path); if (methods.containsKey(path)) { RESTMethod rm = methods.get(path); Map<String, FileItem> formFields = null; if (rm.isForm()) formFields = parseForm(req); String format = null; if (rm.isForm()) { FileItem item = formFields.get("format"); if (item != null) format = item.getString("UTF-8"); } else format = req.getParameter("format"); if (format == null) format = "json"; RESTSerializer serializer = serializers.get(format); if (serializer != null) { if (AnnotationUtility.getAnnotation(Unsecured.class, rm.getMethod(), rm.getObject()) == null) authenticate(req, resp, rm.getObject()); Class<?>[] paramTypes = rm.getMethod().getParameterTypes(); Object[] params = new Object[paramTypes.length]; initParamValues(rm, req, resp, params, paramTypes); if (rm.isForm()) fillParamValuesFromForm(rm, formFields, serializer, params, paramTypes); else fillParamValuesFromRequest(rm, req, serializer, params, paramTypes); try { if (rm.getMethod().getReturnType().equals(Void.TYPE) || rm.getMethod().getReturnType().equals(InputStream.class) || rm.getMethod().getReturnType().equals(OutputStream.class)) executeMethod(rm, params); else { String s = executeMethod(rm, params, serializer); if (logger.isTraceEnabled()) logger.trace("Serialized response: " + s); if (resp.getContentType() == null) { resp.setContentType(serializer.getResponseMIME()); resp.setCharacterEncoding("utf8"); } resp.getWriter().write(s); resp.getWriter().flush(); resp.getWriter().close(); } } catch (IOException e) { ErrorLogger.log(getClass(), e); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Method execution failed: " + e.getMessage()); } } else resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unsupported format"); } else { logger.warn("Request for unavailable REST method " + path); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "There is no method registered with path " + path); } } catch (AuthenticationException e) { resp.setHeader("WWW-Authenticate", "BASIC realm=\"SecureFiles\""); resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Please provide username and password"); } finally { if (sessionManager != null) sessionManager.clearCurrentSessionId(); beans.remove(Thread.currentThread()); } }