List of usage examples for javax.servlet.http HttpServletResponse setBufferSize
public void setBufferSize(int size);
From source file:gov.nih.nci.ncicb.cadsr.ocbrowser.struts.actions.ObjectClassAction.java
/** * * * @param mapping The ActionMapping used to select this instance. * @param form The optional ActionForm bean for this request. * @param request The HTTP Request we are processing. * @param response The HTTP Response we are processing. * * @return/*from w ww . j a v a 2 s. c om*/ * * @throws IOException * @throws ServletException */ public ActionForward viewReferenceDocAttchment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { OutputStream out = null; InputStream is = null; out = response.getOutputStream(); String attachmentName = request.getParameter(CaDSRConstants.REFERENCE_DOC_ATTACHMENT_NAME); response.addHeader("Content-Disposition", "inline;filename=" + attachmentName); response.addHeader("Pragma", "cache"); response.addHeader("Cache-Control", "private"); response.addHeader("Expires", "0"); // first find out if the attachment is new and saved in the session Map attMap = (Map) getSessionObject(request, CaDSRConstants.REFDOC_ATTACHMENT_MAP); Attachment attachment = getAttachmentFromSession(attMap, attachmentName); if (attachment != null) { FormFile attFile = (FormFile) attMap.get(attachment); is = attFile.getInputStream(); response.setContentType(attachment.getMimeType()); } else { Blob theBlob = null; Connection conn = null; ResultSet rs = null; PreparedStatement ps = null; try { DBUtil dbUtil = new DBUtil(); //String dsName = CDEBrowserParams.getInstance("cdebrowser").getSbrDSN(); dbUtil.getOracleConnectionFromContainer(); String sqlStmt = "SELECT blob_content, mime_type, doc_size from reference_blobs where name = ?"; log.info(sqlStmt); conn = dbUtil.getConnection(); ps = conn.prepareStatement(sqlStmt); ps.setString(1, attachmentName); rs = ps.executeQuery(); boolean exists = false; if (rs.next()) { exists = true; String mimeType = rs.getString(2); // (mimeType); response.setContentType(mimeType); //theBlob = ((OracleResultSet)rs).getBLOB(1); theBlob = rs.getBlob(1); is = theBlob.getBinaryStream(); response.setContentLength(rs.getInt(3)); response.setBufferSize(4 * 1024); //Writing to the OutputStream if (is != null) { byte[] buf = new byte[4 * 1024]; // 4K buffer int bytesRead; while ((bytesRead = is.read(buf)) != -1) { out.write(buf, 0, bytesRead); } } response.setStatus(HttpServletResponse.SC_OK); } } catch (Exception ex) { log.error("Exception Caught in ObjectClassAction.viewReferenceDocAttchment:", ex); } finally { try { if (is != null) is.close(); if (out != null) out.close(); try { if (ps != null) ps.close(); } catch (Exception e) { } try { if (rs != null) rs.close(); } catch (Exception e) { } try { if (conn != null) conn.close(); } catch (Exception e) { } //if (db != null) db.closeDB(); } catch (Exception ex) { log.error("Exception Caught in ObjectClassAction during cleaning up :", ex); } } } return null; }
From source file:org.andromda.presentation.gui.FileDownloadServlet.java
/** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *///from w w w .j a v a 2s . co m @Override public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { try { final String action = request.getParameter(ACTION); final FacesContext context = FacesContextUtils.getFacesContext(request, response); if (action != null && action.trim().length() > 0) { final MethodBinding methodBinding = context.getApplication() .createMethodBinding("#{" + action + "}", null); methodBinding.invoke(context, null); } final Object form = context.getApplication().getVariableResolver().resolveVariable(context, "form"); final Boolean prompt = Boolean.valueOf(request.getParameter(PROMPT)); final String fileNameProperty = request.getParameter(FILE_NAME); final String outputProperty = request.getParameter(OUTPUT); if (form != null && outputProperty != null && fileNameProperty.trim().length() > 0) { final OutputStream stream = response.getOutputStream(); // - reset the response to clear out any any headers (i.e. so // the user doesn't get "unable to open..." when using IE.) response.reset(); Object output = PropertyUtils.getProperty(form, outputProperty); final String fileName = ObjectUtils.toString(PropertyUtils.getProperty(form, fileNameProperty)); final String contentType = this.getContentType(context, request.getParameter(CONTENT_TYPE), fileName); if (prompt.booleanValue() && fileName != null && fileName.trim().length() > 0) { response.addHeader("Content-disposition", "attachment; filename=\"" + fileName + '"'); } // - for IE we need to set the content type, content length and buffer size and // then the flush the response right away because it seems as if there is any lag time // IE just displays a blank page. With mozilla based clients reports display correctly regardless. if (contentType != null && contentType.length() > 0) { response.setContentType(contentType); } if (output instanceof String) { output = ((String) output).getBytes(); } if (output instanceof byte[]) { byte[] file = (byte[]) output; response.setBufferSize(file.length); response.setContentLength(file.length); response.flushBuffer(); stream.write(file); } else if (output instanceof InputStream) { final InputStream report = (InputStream) output; final byte[] buffer = new byte[BUFFER_SIZE]; response.setBufferSize(BUFFER_SIZE); response.flushBuffer(); for (int ctr = 0; (ctr = report.read(buffer)) > 0;) { stream.write(buffer, 0, ctr); } } stream.flush(); } if (form != null) { // - remove the output now that we're done with it (in case its large) PropertyUtils.setProperty(form, outputProperty, null); } } catch (Throwable throwable) { throw new ServletException(throwable); } }
From source file:org.mycore.common.content.util.MCRServletContentHelper.java
/** * Serve the specified content, optionally including the data content. * This method handles both GET and HEAD requests. *///from w w w . ja v a2 s . c o m public static void serveContent(final MCRContent content, final HttpServletRequest request, final HttpServletResponse response, final ServletContext context, final Config config, final boolean withContent) throws IOException { boolean serveContent = withContent; final String path = getRequestPath(request); if (LOGGER.isDebugEnabled()) { if (serveContent) { LOGGER.debug("Serving '" + path + "' headers and data"); } else { LOGGER.debug("Serving '" + path + "' headers only"); } } if (response.isCommitted()) { //getContent has access to response return; } final boolean isError = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST; if (content == null && !isError) { response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI()); return; } //Check if all conditional header validate if (!isError && !checkIfHeaders(request, response, content)) { return; } // Find content type. String contentType = content.getMimeType(); final String filename = getFileName(request, content); if (contentType == null) { contentType = context.getMimeType(filename); content.setMimeType(contentType); } String enc = content.getEncoding(); if (enc != null) { contentType = String.format(Locale.ROOT, "%s; charset=%s", contentType, enc); } String eTag = null; ArrayList<Range> ranges = null; if (!isError) { eTag = content.getETag(); if (config.useAcceptRanges) { response.setHeader("Accept-Ranges", "bytes"); } ranges = parseRange(request, response, content); response.setHeader("ETag", eTag); long lastModified = content.lastModified(); if (lastModified >= 0) { response.setDateHeader("Last-Modified", lastModified); } if (serveContent) { String dispositionType = request.getParameter("dl") == null ? "inline" : "attachment"; response.setHeader("Content-Disposition", dispositionType + ";filename=\"" + filename + "\""); } } final long contentLength = content.length(); //No Content to serve? if (contentLength == 0) { serveContent = false; } if (content.isUsingSession()) { response.addHeader("Cache-Control", "private, max-age=0, must-revalidate"); response.addHeader("Vary", "*"); } try (ServletOutputStream out = serveContent ? response.getOutputStream() : null) { if (serveContent) { try { response.setBufferSize(config.outputBufferSize); } catch (final IllegalStateException e) { //does not matter if we fail } } if (response instanceof ServletResponseWrapper) { if (request.getHeader("Range") != null) { LOGGER.warn("Response is wrapped by ServletResponseWrapper, no 'Range' requests supported."); } ranges = FULL; } if (isError || (ranges == null || ranges.isEmpty()) && request.getHeader("Range") == null || ranges == FULL) { //No ranges if (contentType != null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("contentType='" + contentType + "'"); } response.setContentType(contentType); } if (contentLength >= 0) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("contentLength=" + contentLength); } setContentLengthLong(response, contentLength); } if (serveContent) { copy(content, out, config.inputBufferSize, config.outputBufferSize); } } else { if (ranges == null || ranges.isEmpty()) { return; } // Partial content response. response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); if (ranges.size() == 1) { final Range range = ranges.get(0); response.addHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length); final long length = range.end - range.start + 1; setContentLengthLong(response, length); if (contentType != null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("contentType='" + contentType + "'"); } response.setContentType(contentType); } if (serveContent) { copy(content, out, range, config.inputBufferSize, config.outputBufferSize); } } else { response.setContentType("multipart/byteranges; boundary=" + MIME_BOUNDARY); if (serveContent) { copy(content, out, ranges.iterator(), contentType, config.inputBufferSize, config.outputBufferSize); } } } } }
From source file:org.kaaproject.kaa.server.admin.controller.KaaAdminController.java
/** * Get log record schema with header and log schema inside by record key. * * @param key// www . j a v a 2s. c o m * the key * @param request * the request * @param response * the response * @throws KaaAdminServiceException * the kaa admin service exception */ @RequestMapping(value = "logRecordSchema", method = RequestMethod.POST) @ResponseStatus(value = HttpStatus.OK) public void getRecordSchema(@RequestBody RecordKey key, HttpServletRequest request, HttpServletResponse response) throws KaaAdminServiceException { try { FileData file = cacheService.getRecordSchema(key); response.setContentType("text/plain"); ServletUtils.prepareDisposition(request, response, file.getFileName()); response.setContentLength(file.getFileData().length); response.setBufferSize(BUFFER); response.getOutputStream().write(file.getFileData()); response.flushBuffer(); } catch (Exception e) { throw Utils.handleException(e); } }
From source file:org.kaaproject.kaa.server.admin.controller.KaaAdminController.java
/** * Generate log library by record key.// w w w . j a v a 2s. com * * @param key * the key * @param request * the request * @param response * the response * @throws KaaAdminServiceException * the kaa admin service exception */ @RequestMapping(value = "logLibrary", method = RequestMethod.POST) @ResponseStatus(value = HttpStatus.OK) public void getRecordLibrary(@RequestBody RecordKey key, HttpServletRequest request, HttpServletResponse response) throws KaaAdminServiceException { try { FileData file = cacheService.getRecordLibrary(key); response.setContentType("application/java-archive"); ServletUtils.prepareDisposition(request, response, file.getFileName()); response.setContentLength(file.getFileData().length); response.setBufferSize(BUFFER); response.getOutputStream().write(file.getFileData()); response.flushBuffer(); } catch (Exception e) { throw Utils.handleException(e); } }
From source file:org.flowerplatform.communication.public_resources.PublicResourcesServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String requestedFile = request.getPathInfo(); if (logger.isTraceEnabled()) { logger.trace("Resource requested: {}", requestedFile); }//from www. j av a 2s.c o m // Check if file is actually supplied to the request URI. if (requestedFile == null) { send404(request, response); return; } // Decode the file name (might contain spaces and on) and prepare file // object. requestedFile = URLDecoder.decode(requestedFile, "UTF-8"); if (requestedFile.startsWith(PATH_PREFIX)) { requestedFile = requestedFile.substring(PATH_PREFIX.length()); } // this may be an attempt to see files that are not public, i.e. to go to the // parent. From my tests, when you put in the browser (or even telnet) something like // parent1/parent2/../bla, it seems to be automatically translated to parent1/bla. However, // I wanted to make sure that we are all right if (requestedFile.contains("..")) { send404(request, response); return; } // we need something like /plugin/file.... int indexOfSecondSlash = requestedFile.indexOf('/', 1); // 1, i.e. skip the first index if (indexOfSecondSlash < 0) { send404(request, response); return; } // both variables are prefixed with / String plugin = requestedFile.substring(0, indexOfSecondSlash); String file = requestedFile.substring(indexOfSecondSlash); // if | is supplied => the file is a zip, and we want what's in it int indexOfZipSeparator = file.indexOf('|'); String fileInsideZipArchive = null; if (indexOfZipSeparator >= 0 && indexOfZipSeparator < file.length() - 1) { // has | and | is not the last char in the string fileInsideZipArchive = file.substring(indexOfZipSeparator + 1); file = file.substring(0, indexOfZipSeparator); } requestedFile = "platform:/plugin" + plugin + "/" + AbstractFlowerJavaPlugin.PUBLIC_RESOURCES_DIR + file; // Get content type by filename from the file or file inside zip String contentType = getServletContext() .getMimeType(fileInsideZipArchive != null ? fileInsideZipArchive : file); // 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"; } // Init servlet response. response.reset(); response.setBufferSize(DEFAULT_BUFFER_SIZE); response.setContentType(contentType); // response.setHeader("Content-Length", String.valueOf(file.length())); // response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); // Prepare streams. URL url; InputStream input = null; Closeable inputCloseable = null; OutputStream output = null; try { url = new URL(requestedFile); try { input = url.openConnection().getInputStream(); inputCloseable = input; } catch (IOException e) { // may fail if the resource is not available send404(request, response); return; } if (fileInsideZipArchive != null) { // we need to look for a file in the archive Pair<InputStream, Closeable> pair = getInputStreamForFileWithinZip(input, fileInsideZipArchive); if (pair == null) { // the file was not found; the input streams are closed in this case send404(request, response); return; } input = pair.a; inputCloseable = pair.b; } output = response.getOutputStream(); // according to the doc, no need to use Buffered..., because the method buffers internally IOUtils.copy(input, output); } finally { // Gently close streams. close(output); close(inputCloseable); } }
From source file:org.kaaproject.kaa.server.admin.controller.KaaAdminController.java
/** * Exports a CTL schema and, depending on the export method specified, all * of its dependencies.// w w w . j a va2 s .c o m * * @param fqn * - the schema fqn * @param version * - the schema version * @param method * - the schema export method * @param applicationId * id of the application * @param request * - the http request * @param response * - the http response * * @see CTLSchemaExportMethod * * @throws KaaAdminServiceException * the kaa admin service exception * @deprecated As of release 0.9.0, replaced by {@link #exportCTLSchemaByAppToken(String, int, String, String, HttpServletRequest, HttpServletResponse)} */ @Deprecated @RequestMapping(value = "CTL/exportSchema", params = { "fqn", "version", "method" }, method = RequestMethod.POST) @ResponseStatus(value = HttpStatus.OK) public void exportCTLSchema(@RequestParam String fqn, @RequestParam int version, @RequestParam String method, @RequestParam(required = false) String applicationId, HttpServletRequest request, HttpServletResponse response) throws KaaAdminServiceException { try { FileData output = kaaAdminService.exportCTLSchema(fqn, version, applicationId, CTLSchemaExportMethod.valueOf(method.toUpperCase())); ServletUtils.prepareDisposition(request, response, output.getFileName()); response.setContentType(output.getContentType()); response.setContentLength(output.getFileData().length); response.setBufferSize(BUFFER); response.getOutputStream().write(output.getFileData()); response.flushBuffer(); } catch (Exception cause) { throw Utils.handleException(cause); } }
From source file:org.kaaproject.kaa.server.admin.controller.KaaAdminController.java
/** * Exports a CTL schema and, depending on the export method specified, all * of its dependencies./*from w w w .j a va 2 s . c o m*/ * * @param fqn * - the schema fqn * @param version * - the schema version * @param method * - the schema export method * @param applicationToken * the application token * @param request * - the http request * @param response * - the http response * * @see CTLSchemaExportMethod * * @throws KaaAdminServiceException * the kaa admin service exception */ @RequestMapping(value = "CTL/appToken/exportSchema", params = { "fqn", "version", "method" }, method = RequestMethod.POST) @ResponseStatus(value = HttpStatus.OK) public void exportCTLSchemaByAppToken(@RequestParam String fqn, @RequestParam int version, @RequestParam String method, @RequestParam(required = false) String applicationToken, HttpServletRequest request, HttpServletResponse response) throws KaaAdminServiceException { try { FileData output = kaaAdminService.exportCTLSchemaByAppToken(fqn, version, applicationToken, CTLSchemaExportMethod.valueOf(method.toUpperCase())); ServletUtils.prepareDisposition(request, response, output.getFileName()); response.setContentType(output.getContentType()); response.setContentLength(output.getFileData().length); response.setBufferSize(BUFFER); response.getOutputStream().write(output.getFileData()); response.flushBuffer(); } catch (Exception cause) { throw Utils.handleException(cause); } }
From source file:org.dmb.trueprice.servlets.Download_servlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* Rcupration du chemin du fichier demand au sein de l'URL de la requte */ String fichierRequis = request.getPathInfo(); /* Vrifie qu'un fichier a bien t fourni */ if (fichierRequis == null || "/".equals(fichierRequis)) { /* Si non, alors on envoie une erreur 404, qui signifie que la ressource demande n'existe pas */ response.sendError(HttpServletResponse.SC_NOT_FOUND); return;/*www .j av a2 s.c o m*/ } if (iconPathIsOK == false) { buildIconURL(request); } log.info("File asked [" + fichierRequis + "]"); String parentFolder = xmlDataFolder; // Si c'est un fichier dans un dossier personnel d'un user if (fichierRequis.startsWith(xmlMemberDataPath)) { HttpSession session = request.getSession(false); Membre mb = (Membre) session.getAttribute(ATT_SESSION_USER); parentFolder = xmlMemberDataFolder + File.separator + mb.getMbMail(); } // Si c'est un fichier dans le dossier XMl public else if (fichierRequis.startsWith(xmlPublicDataPath)) { parentFolder = xmlPublicDataFolder; } // else if (fichierRequis.startsWith(iconDataPath)) { parentFolder = iconFolder ;} log.info("Parent folder : [" + parentFolder + "]"); /* Dcode le nom de fichier rcupr, susceptible de contenir des espaces et autres caractres spciaux, et prpare l'objet File */ fichierRequis = URLDecoder.decode(fichierRequis, "UTF-8"); log.info("Decoded File asked : [" + fichierRequis + "]"); /* Ne retenir que le nom du fichier + extension */ fichierRequis = FilenameUtils.getName(fichierRequis); log.info("Finally, file name is : [" + fichierRequis + "]"); File fichier = new File(parentFolder, fichierRequis); /* Vrifie que le fichier existe bien */ if (!fichier.exists()) { log.info("Can't find : [" + fichierRequis + "] in folder [" + parentFolder + "]"); /* Si non, alors on envoie une erreur 404, qui signifie que la ressource demande n'existe pas */ response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } /* Rcupre le type du fichier */ String type = getServletContext().getMimeType(fichier.getName()); /* Si le type de fichier est inconnu, alors on initialise un type par dfaut */ if (type == null) { type = "application/octet-stream"; } else { InitContextListener.getLogger(this.getClass()) .info(" Found MimeType for asked ressource [" + type + "]"); } /* Initialise la rponse HTTP */ response.reset(); response.setBufferSize(DEFAULT_BUFFER_SIZE); response.setContentType(type); response.setHeader("Content-Length", String.valueOf(fichier.length())); response.setHeader("Content-Disposition", "attachment; filename=\"" + fichier.getName() + "\""); /* Prpare les flux */ BufferedInputStream entree = null; BufferedOutputStream sortie = null; try { /* Ouvre les flux */ entree = new BufferedInputStream(new FileInputStream(fichier), TAILLE_TAMPON); sortie = new BufferedOutputStream(response.getOutputStream(), TAILLE_TAMPON); /* ... */ /* Lit le fichier et crit son contenu dans la rponse HTTP */ byte[] tampon = new byte[TAILLE_TAMPON]; int longueur; while ((longueur = entree.read(tampon)) > 0) { sortie.write(tampon, 0, longueur); } } finally { try { sortie.close(); } catch (IOException ignore) { } try { entree.close(); } catch (IOException ignore) { } } InitContextListener.getLogger(this.getClass()).info("File sent [" + fichierRequis + "]"); }