List of usage examples for javax.servlet ServletOutputStream write
public void write(byte b[], int off, int len) throws IOException
len
bytes from the specified byte array starting at offset off
to this output stream. From source file:ec.gob.ceaaces.controller.MallasController.java
public void presentarReporteXls() { HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext() .getResponse();/*w w w . ja v a2 s. c om*/ try { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy"); response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment; filename=mallas_" + simpleDateFormat.format(new Date()) + ".xls"); response.setContentLength(reporteBytes.length); ServletOutputStream out = response.getOutputStream(); out.write(reporteBytes, 0, reporteBytes.length); out.flush(); FacesContext.getCurrentInstance().responseComplete(); } catch (Exception e) { e.printStackTrace(); JsfUtil.msgError("Error al generar el reporte, comunquese con el administrador del sistema"); } }
From source file:de.unigoettingen.sub.commons.contentlib.servlet.controller.GetImageAction.java
/************************************************************************************ * exectute all image actions (rotation, scaling etc.) and send image back to output stream of the servlet, after setting correct mime type * /*from w ww. j av a2s . c o m*/ * @param request {@link HttpServletRequest} of ServletRequest * @param response {@link HttpServletResponse} for writing to response output stream * @throws IOException * @throws ImageInterpreterException * @throws ServletException * @throws ContentLibException * @throws URISyntaxException * @throws ContentLibPdfException ************************************************************************************/ @Override public void run(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response) throws IOException, URISyntaxException, ContentLibException { long startTime = System.currentTimeMillis(); super.run(servletContext, request, response); /* * -------------------------------- get central configuration -------------------------------- */ URI sourceImageUrl = null; ContentServerConfiguration config = ContentServerConfiguration.getInstance(); if (!request.getParameter("sourcepath").startsWith("file:") && !request.getParameter("sourcepath").startsWith("http:")) { sourceImageUrl = new URI(config.getRepositoryPathImages() + request.getParameter("sourcepath")); } else { sourceImageUrl = new URI(request.getParameter("sourcepath")); } try { Cache cc = null; ServletOutputStream output = response.getOutputStream(); if (request.getParameter("thumbnail") != null) { cc = ContentServer.getThumbnailCache(); } else { cc = ContentServer.getContentCache(); } // String myUniqueID = getContentCacheIdForRequest(request, config); String myUniqueID = getContentCacheIdForParamMap(request.getParameterMap(), config); String targetExtension = request.getParameter("format"); boolean ignoreCache = false; /* check if cache should be ignored */ if (request.getParameter("ignoreCache") != null) { String ignore = request.getParameter("ignoreCache").trim(); ignoreCache = Boolean.parseBoolean(ignore); } boolean useCache = false; if (request.getParameter("thumbnail") != null) { useCache = config.getThumbnailCacheUse(); } else { useCache = config.getContentCacheUse(); } if (request.getParameterMap().containsKey("highlight")) { useCache = false; } if (cc == null || !useCache) { ignoreCache = true; cc = null; LOGGER.debug("cache deactivated via configuration"); } if (!ignoreCache && cc.isKeyInCache(myUniqueID + "." + targetExtension)) { LOGGER.debug("get file from cache: " + myUniqueID + "." + targetExtension); CacheObject co; try { co = (CacheObject) cc.get(myUniqueID + "." + targetExtension).getObjectValue(); ByteArrayInputStream in = new ByteArrayInputStream(co.getData()); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { output.write(buf, 0, len); } in.close(); output.flush(); output.close(); return; } catch (NullPointerException e) { LOGGER.debug("element not in cache anymore: " + myUniqueID + "." + targetExtension); } } else if (!ignoreCache) { LOGGER.debug("file not found in cache: " + myUniqueID + "." + targetExtension); } // if (!ignoreCache && cc.cacheContains(myUniqueID, targetExtension)) { // LOGGER.debug("get file from cache: " + myUniqueID); // cc.writeToStream(output, myUniqueID, targetExtension); // output.flush(); // output.close(); // return; // } else if (ignoreCache == false) { // LOGGER.debug("file not found in cache: " + myUniqueID); // } // /* // * -------------------------------- if there is an internal request from goobiContentServer, you have to overwrite the // sourcepath with // * given attribute for image url -------------------------------- // */ // if (request.getAttribute("sourcepath") != null) { // sourceImageUrl = new URI((String) request.getAttribute("sourcepath")); // } LOGGER.debug("source image:" + sourceImageUrl); /* * -------------------------------- retrieve source image from url -------------------------------- */ ImageManager sourcemanager = new ImageManager(sourceImageUrl.toURL()); LOGGER.trace("imageManager initialized"); /* * -------------------------------- set the defaults -------------------------------- */ int angle = 0; int scaleX = 100; int scaleY = 100; int scaleType = ImageManager.SCALE_BY_PERCENT; LinkedList<String> highlightCoordinateList = null; Color highlightColor = null; Watermark myWatermark = null; LOGGER.trace("Variables set"); /* * -------------------------------- rotate -------------------------------- */ if (request.getParameterMap().containsKey("rotate")) { angle = Integer.parseInt(request.getParameter("rotate")); LOGGER.trace("rotate image:" + angle); } /* * -------------------------------- scale: scale the image to some percent value -------------------------------- */ if (request.getParameterMap().containsKey("scale")) { scaleX = Integer.parseInt(request.getParameter("scale")); scaleY = scaleX; scaleType = ImageManager.SCALE_BY_PERCENT; LOGGER.trace("scale image to percent:" + scaleX); } if (request.getParameterMap().containsKey("width") && request.getParameterMap().containsKey("height")) { scaleX = Integer.parseInt(request.getParameter("width")); scaleY = Integer.parseInt(request.getParameter("height")); scaleType = ImageManager.SCALE_TO_BOX; } /* * -------------------------------- width: scale image to fixed width -------------------------------- */ else if (request.getParameterMap().containsKey("width")) { scaleX = Integer.parseInt(request.getParameter("width")); scaleY = 0; scaleType = ImageManager.SCALE_BY_WIDTH; LOGGER.trace("scale image to width:" + scaleX); } /* * -------------------------------- height: scale image to fixed height -------------------------------- */ else if (request.getParameterMap().containsKey("height")) { scaleY = Integer.parseInt(request.getParameter("height")); scaleX = 0; scaleType = ImageManager.SCALE_BY_HEIGHT; LOGGER.trace("scale image to height:" + scaleY); } /* * -------------------------------- highlight -------------------------------- */ if (request.getParameterMap().containsKey("highlight")) { highlightCoordinateList = new LinkedList<String>(); String highlight = request.getParameter("highlight"); StrTokenizer areas = new StrTokenizer(highlight, "$"); for (String area : areas.getTokenArray()) { StrTokenizer coordinates = new StrTokenizer(area, ","); highlightCoordinateList.add(coordinates.getContent()); } highlightColor = config.getDefaultHighlightColor(); } /* * -------------------------------- insert watermark, if it should be used -------------------------------- */ if (!request.getParameterMap().containsKey("ignoreWatermark") && config.getWatermarkUse()) { File watermarkfile = new File(new URI(config.getWatermarkConfigFilePath())); myWatermark = Watermark.generateWatermark(request, watermarkfile); } /* * -------------------------------- prepare target -------------------------------- */ // change to true if watermark should scale RenderedImage targetImage = null; if (config.getScaleWatermark()) { targetImage = sourcemanager.scaleImageByPixel(scaleX, scaleY, scaleType, angle, highlightCoordinateList, highlightColor, myWatermark, true, ImageManager.BOTTOM); } else { targetImage = sourcemanager.scaleImageByPixel(scaleX, scaleY, scaleType, angle, highlightCoordinateList, highlightColor, myWatermark, false, ImageManager.BOTTOM); } LOGGER.trace("Creating ImageInterpreter"); ImageFileFormat targetFormat = ImageFileFormat.getImageFileFormatFromFileExtension(targetExtension); ImageInterpreter wi = targetFormat.getInterpreter(targetImage); // read file LOGGER.trace("Image stored in " + wi.getClass().toString()); /* * -------------------------------- set file name and attachment header from parameter or from configuration * -------------------------------- */ LOGGER.trace("Creating target file"); StringBuilder targetFileName = new StringBuilder(); if (config.getSendImageAsAttachment()) { targetFileName.append("attachment; "); } targetFileName.append("filename="); if (request.getParameter("targetFileName") != null) { targetFileName.append(request.getParameter("targetFileName")); } else { String filename = ContentLibUtil.getCustomizedFileName(config.getDefaultFileNameImages(), "." + targetFormat.getFileExtension()); targetFileName.append(filename); } LOGGER.trace("Adding targetFile " + targetFileName.toString() + " to response"); response.setHeader("Content-Disposition", targetFileName.toString()); response.setContentType(targetFormat.getMimeType()); /* * -------------------------------- resolution -------------------------------- */ LOGGER.trace("Setting image resolution values"); if (request.getParameter("resolution") != null) { wi.setXResolution(Float.parseFloat(request.getParameter("resolution"))); wi.setYResolution(Float.parseFloat(request.getParameter("resolution"))); } else { wi.setXResolution(config.getDefaultResolution()); wi.setYResolution(config.getDefaultResolution()); } LOGGER.trace("Setting image compression"); if (request.getParameter("compression") != null) { String value = request.getParameter("compression"); try { int intvalue = Integer.parseInt(value); wi.setWriterCompressionValue(intvalue); } catch (Exception e) { LOGGER.trace("value is not a number, use default value"); } } /* * -------------------------------- write target image to stream -------------------------------- */ // cc.put(new Element(myUniqueID + "." + targetExtension, wi.getRenderedImage())); if (cc != null) { byte[] data = wi.writeToStreamAndByteArray(output); cc.putIfAbsent(new Element(myUniqueID + "." + targetExtension, new CacheObject(data))); } else { LOGGER.trace("writing file to servlet response"); wi.writeToStream(null, output); } LOGGER.trace("Done writing ImageInterpreter to stream"); wi.clear(); LOGGER.trace("Done clearing ImageInterpreter"); } catch (Exception e) { LOGGER.error("CacheException", e); } long endTime = System.currentTimeMillis(); LOGGER.trace("Content server time to process request: " + (endTime - startTime) + " ms"); // try { // CommonUtils.appendTextFile("Image request for file " + new File(sourceImageUrl).getAbsolutePath() + "; Time to process: " + (endTime - // startTime) // + " ms\n", new File(de.unigoettingen.sub.commons.contentlib.servlet.Util.getBaseFolderAsFile(), "timeConsumptionLog.txt")); // // } catch (IOException e) { // LOGGER.info("Unable to write time log file due to IOException " + e.toString()); // } }
From source file:org.apache.catalina.servlets.DefaultServlet.java
/** * Copy the contents of the specified input stream to the specified * output stream, and ensure that both streams are closed before returning * (even in the face of an exception)./*from w w w . jav a2s.c om*/ * * @param ostream The output stream to write to * @param resourceInfo Description of the Parameter * @throws IOException if an input/output error occurs */ private void copy(ResourceInfo resourceInfo, ServletOutputStream ostream) throws IOException { IOException exception = null; // Optimization: If the binary content has already been loaded, send // it directly if (resourceInfo.file != null) { byte buffer[] = resourceInfo.file.getContent(); if (buffer != null) { ostream.write(buffer, 0, buffer.length); return; } } InputStream resourceInputStream = resourceInfo.getStream(); InputStream istream = new BufferedInputStream(resourceInputStream, input); // Copy the input stream to the output stream exception = copyRange(istream, ostream); // Clean up the input stream try { istream.close(); } catch (Throwable t) { ; } // Rethrow any exception that has occurred if (exception != null) { throw exception; } }
From source file:org.apache.catalina.servlets.DefaultServlet.java
/** * Copy the contents of the specified input stream to the specified * output stream, and ensure that both streams are closed before returning * (even in the face of an exception).//from www .ja va 2s . c o m * * @param istream The input stream to read from * @param ostream The output stream to write to * @return Exception which occurred during processing */ private IOException copyRange(InputStream istream, ServletOutputStream ostream) { // Copy the input stream to the output stream IOException exception = null; byte buffer[] = new byte[input]; int len = buffer.length; while (true) { try { len = istream.read(buffer); if (len == -1) { break; } ostream.write(buffer, 0, len); } catch (IOException e) { exception = e; len = -1; break; } } return exception; }
From source file:org.apache.catalina.servlets.DefaultServlet.java
/** * Copy the contents of the specified input stream to the specified * output stream, and ensure that both streams are closed before returning * (even in the face of an exception)./*from ww w.j a v a 2 s.c o m*/ * * @param istream The input stream to read from * @param ostream The output stream to write to * @param start Start of the range which will be copied * @param end End of the range which will be copied * @return Exception which occurred during processing */ private IOException copyRange(InputStream istream, ServletOutputStream ostream, long start, long end) { if (debug > 10) { log("Serving bytes:" + start + "-" + end); } try { istream.skip(start); } catch (IOException e) { return e; } IOException exception = null; long bytesToRead = end - start + 1; byte buffer[] = new byte[input]; int len = buffer.length; while ((bytesToRead > 0) && (len >= buffer.length)) { try { len = istream.read(buffer); if (bytesToRead >= len) { ostream.write(buffer, 0, len); bytesToRead -= len; } else { ostream.write(buffer, 0, (int) bytesToRead); bytesToRead = 0; } } catch (IOException e) { exception = e; len = -1; } if (len < buffer.length) { break; } } return exception; }
From source file:ispyb.client.mx.results.ViewResultsAction.java
public ActionForward displayCorrectionFile(ActionMapping mapping, ActionForm actForm, HttpServletRequest request, HttpServletResponse response) { ActionMessages errors = new ActionMessages(); String filename = ""; String fullFilePath = ""; try {// w w w. ja v a 2 s . c o m if (request.getParameter("fileName") != null) filename = new String(request.getParameter("fileName")); Integer dataCollectionId = null; if (BreadCrumbsForm.getIt(request).getSelectedDataCollection() != null) dataCollectionId = BreadCrumbsForm.getIt(request).getSelectedDataCollection().getDataCollectionId(); else { dataCollectionId = new Integer(request.getParameter(Constants.SESSION_ID)); } if (dataCollectionId != null) { DataCollection3VO dataCollection = dataCollectionService.findByPk(dataCollectionId, false, false); String beamLineName = dataCollection.getDataCollectionGroupVO().getSessionVO().getBeamlineName(); String[] correctionFiles = ESRFBeamlineEnum.retrieveCorrectionFilesNameWithName(beamLineName); if (correctionFiles != null) { for (int k = 0; k < correctionFiles.length; k++) { String correctionFileName = correctionFiles[k]; if (correctionFileName != null && correctionFileName.equals(filename)) { String dir = ESRFBeamlineEnum.retrieveDirectoryNameWithName(beamLineName); if (dir != null) { String correctionFilePath = "/data/pyarch/" + dir + "/" + correctionFileName; fullFilePath = PathUtils.FitPathToOS(correctionFilePath); java.io.FileInputStream in; in = new java.io.FileInputStream(new File(fullFilePath)); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + filename); ServletOutputStream out = response.getOutputStream(); byte[] buf = new byte[4096]; int bytesRead; while ((bytesRead = in.read(buf)) != -1) { out.write(buf, 0, bytesRead); } in.close(); out.flush(); out.close(); return null; } } } } } } catch (java.io.IOException e) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", "Unable to download file: " + fullFilePath)); saveErrors(request, errors); e.printStackTrace(); return mapping.findForward("error"); } catch (Exception e) { e.printStackTrace(); return mapping.findForward("error"); } errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", "Unable to download file: " + filename)); saveErrors(request, errors); return mapping.findForward("error"); }
From source file:org.fcrepo.server.access.FedoraAccessServlet.java
/** * <p>//from w w w. ja va2s . c om * This method calls the Fedora Access Subsystem to retrieve a MIME-typed * stream corresponding to the dissemination request. * </p> * * @param context * The read only context of the request. * @param PID * The persistent identifier of the Digital Object. * @param sDefPID * The persistent identifier of the Service Definition object. * @param methodName * The method name. * @param userParms * An array of user-supplied method parameters. * @param asOfDateTime * The version datetime stamp of the digital object. * @param response * The servlet response. * @param request * The servlet request. * @throws IOException * If an error occurrs with an input or output operation. * @throws ServerException * If an error occurs in the Access Subsystem. */ public void getDissemination(Context context, String PID, String sDefPID, String methodName, Property[] userParms, Date asOfDateTime, HttpServletResponse response, HttpServletRequest request) throws IOException, ServerException { ServletOutputStream out = null; MIMETypedStream dissemination = null; dissemination = m_access.getDissemination(context, PID, sDefPID, methodName, userParms, asOfDateTime); out = response.getOutputStream(); try { // testing to see what's in request header that might be of interest if (logger.isDebugEnabled()) { for (Enumeration<?> e = request.getHeaderNames(); e.hasMoreElements();) { String name = (String) e.nextElement(); Enumeration<?> headerValues = request.getHeaders(name); StringBuffer sb = new StringBuffer(); while (headerValues.hasMoreElements()) { sb.append((String) headerValues.nextElement()); } String value = sb.toString(); logger.debug("FEDORASERVLET REQUEST HEADER CONTAINED: {} : {}", name, value); } } // Dissemination was successful; // Return MIMETypedStream back to browser client if (dissemination.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) { String location = ""; for (Property prop : dissemination.header) { if (prop.name.equalsIgnoreCase(HttpHeaders.LOCATION)) { location = prop.value; break; } } response.sendRedirect(location); } else { response.setContentType(dissemination.getMIMEType()); Property[] headerArray = dissemination.header; if (headerArray != null) { for (int i = 0; i < headerArray.length; i++) { if (headerArray[i].name != null && !headerArray[i].name.equalsIgnoreCase("transfer-encoding") && !headerArray[i].name.equalsIgnoreCase("content-type")) { response.addHeader(headerArray[i].name, headerArray[i].value); logger.debug( "THIS WAS ADDED TO FEDORASERVLET RESPONSE HEADER FROM ORIGINATING PROVIDER {} : {}", headerArray[i].name, headerArray[i].value); } } } int byteStream = 0; logger.debug("Started reading dissemination stream"); InputStream dissemResult = dissemination.getStream(); byte[] buffer = new byte[BUF]; while ((byteStream = dissemResult.read(buffer)) != -1) { out.write(buffer, 0, byteStream); } buffer = null; dissemResult.close(); dissemResult = null; out.flush(); out.close(); logger.debug("Finished reading dissemination stream"); } } finally { dissemination.close(); } }
From source file:org.fcrepo.server.access.FedoraAccessServlet.java
public void getDatastreamDissemination(Context context, String PID, String dsID, Date asOfDateTime, HttpServletResponse response, HttpServletRequest request) throws IOException, ServerException { ServletOutputStream out = null; MIMETypedStream dissemination = null; dissemination = m_access.getDatastreamDissemination(context, PID, dsID, asOfDateTime); try {/*from w ww. j a v a 2 s . co m*/ // testing to see what's in request header that might be of interest if (logger.isDebugEnabled()) { for (Enumeration<?> e = request.getHeaderNames(); e.hasMoreElements();) { String name = (String) e.nextElement(); Enumeration<?> headerValues = request.getHeaders(name); StringBuffer sb = new StringBuffer(); while (headerValues.hasMoreElements()) { sb.append((String) headerValues.nextElement()); } String value = sb.toString(); logger.debug("FEDORASERVLET REQUEST HEADER CONTAINED: {} : {}", name, value); } } // Dissemination was successful; // Return MIMETypedStream back to browser client if (dissemination.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) { String location = ""; for (Property prop : dissemination.header) { if (prop.name.equalsIgnoreCase(HttpHeaders.LOCATION)) { location = prop.value; break; } } response.sendRedirect(location); } else { int status = dissemination.getStatusCode(); response.setStatus(status); if (status == HttpStatus.SC_OK) { response.setContentType(dissemination.getMIMEType()); } Property[] headerArray = dissemination.header; if (headerArray != null) { for (int i = 0; i < headerArray.length; i++) { if (headerArray[i].name != null && !headerArray[i].name.equalsIgnoreCase("transfer-encoding") && !headerArray[i].name.equalsIgnoreCase("content-type")) { response.addHeader(headerArray[i].name, headerArray[i].value); logger.debug( "THIS WAS ADDED TO FEDORASERVLET RESPONSE HEADER FROM ORIGINATING PROVIDER {} : {}", headerArray[i].name, headerArray[i].value); } } } out = response.getOutputStream(); int byteStream = 0; logger.debug("Started reading dissemination stream"); InputStream dissemResult = dissemination.getStream(); byte[] buffer = new byte[BUF]; while ((byteStream = dissemResult.read(buffer)) != -1) { out.write(buffer, 0, byteStream); } buffer = null; dissemResult.close(); dissemResult = null; out.flush(); out.close(); logger.debug("Finished reading dissemination stream"); } } finally { dissemination.close(); } }
From source file:org.gss_project.gss.server.rest.Webdav.java
/** * Copy the contents of the specified input stream to the specified output * stream, and ensure that both streams are closed before returning (even in * the face of an exception)./*from w w w. ja v a 2s. c o m*/ * * @param istream The input stream to read from * @param ostream The output stream to write to * @return Exception which occurred during processing */ private IOException copyRange(InputStream istream, ServletOutputStream ostream) { // Copy the input stream to the output stream IOException exception = null; byte buffer[] = new byte[input]; int len = buffer.length; while (true) try { len = istream.read(buffer); if (len == -1) break; ostream.write(buffer, 0, len); } catch (IOException e) { exception = e; len = -1; break; } return exception; }
From source file:org.opencms.webdav.CmsWebdavServlet.java
/** * Copy the contents of the specified input stream to the specified * output stream, and ensure that both streams are closed before returning * (even in the face of an exception).<p> * * @param istream the input stream to read from * @param ostream the output stream to write to * //w ww . j ava2 s .c o m * @return the exception which occurred during processing */ protected IOException copyRange(InputStream istream, ServletOutputStream ostream) { // Copy the input stream to the output stream IOException exception = null; byte[] buffer = new byte[m_input]; int len = buffer.length; while (true) { try { len = istream.read(buffer); if (len == -1) { break; } ostream.write(buffer, 0, len); } catch (IOException e) { exception = e; len = -1; break; } } return exception; }