List of usage examples for javax.servlet ServletOutputStream write
public abstract void write(int b) throws IOException;
From source file:org.opencms.frontend.templateone.form.CmsCaptchaField.java
/** * Writes a Captcha JPEG image to the servlet response output stream. * <p>/*from w w w . j a v a 2s .c o m*/ * * @param cms an initialized Cms JSP action element * @throws IOException if something goes wrong */ public void writeCaptchaImage(CmsJspActionElement cms) throws IOException { ByteArrayOutputStream captchaImageOutput = new ByteArrayOutputStream(); ServletOutputStream out = null; BufferedImage captchaImage = null; int maxTries = 10; do { try { maxTries--; String sessionId = cms.getRequest().getSession().getId(); Locale locale = cms.getRequestContext().getLocale(); captchaImage = CmsCaptchaServiceCache.getSharedInstance() .getCaptchaService(m_captchaSettings, cms.getCmsObject()) .getImageChallengeForID(sessionId, locale); } catch (CaptchaException cex) { if (LOG.isErrorEnabled()) { LOG.error(cex); LOG.error(Messages.get().getBundle().key(Messages.LOG_ERR_CAPTCHA_CONFIG_IMAGE_SIZE_2, new Object[] { m_captchaSettings.getPresetPath(), new Integer(maxTries) })); } m_captchaSettings.setImageHeight(m_captchaSettings.getImageHeight() + 40); m_captchaSettings.setImageWidth(m_captchaSettings.getImageWidth() + 80); } } while (captchaImage == null && maxTries > 0); try { ImageIO.write(captchaImage, "jpg", captchaImageOutput); CmsFlexController controller = CmsFlexController.getController(cms.getRequest()); HttpServletResponse response = controller.getTopResponse(); response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); out = cms.getResponse().getOutputStream(); out.write(captchaImageOutput.toByteArray()); out.flush(); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error(e.getLocalizedMessage(), e); } cms.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { try { if (out != null) { out.close(); } } catch (Throwable t) { // intentionally left blank } } }
From source file:net.sf.appstatus.web.pages.ServicesPage.java
@Override public void doGet(StatusWebHandler webHandler, HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException, IOException { setup(resp, "text/html"); ServletOutputStream os = resp.getOutputStream(); Map<String, String> valuesMap = new HashMap<String, String>(); List<IService> services = webHandler.getAppStatus().getServices(); Collections.sort(services);/*from w w w. jav a 2 s. c o m*/ StrBuilder sbServicesTable = new StrBuilder(); if (HtmlUtils.generateBeginTable(sbServicesTable, services.size())) { HtmlUtils.generateHeaders(sbServicesTable, "", "Group", "Name", "Hits", "Cache", "Running", "min", "max", "avg", "nested", "min (c)", "max (c)", "avg (c)", "nested (c)", "Errors", "Failures", "Hit rate"); for (IService service : services) { HtmlUtils.generateRow(sbServicesTable, Resources.STATUS_JOB, service.getGroup(), service.getName(), service.getHits(), service.getCacheHits() + getPercent(service.getCacheHits(), service.getHits()), service.getRunning(), service.getMinResponseTime(), service.getMaxResponseTime(), Math.round(service.getAvgResponseTime()), Math.round(service.getAvgNestedCalls()), service.getMinResponseTimeWithCache(), service.getMaxResponseTimeWithCache(), Math.round(service.getAvgResponseTimeWithCache()), Math.round(service.getAvgNestedCallsWithCache()), service.getErrors() + getPercent(service.getErrors(), service.getHits()), service.getFailures() + getPercent(service.getFailures(), service.getHits()), getRate(service.getCurrentRate())); } HtmlUtils.generateEndTable(sbServicesTable, services.size()); } // generating content valuesMap.put("servicesTable", sbServicesTable.toString()); String content = HtmlUtils.applyLayout(valuesMap, PAGECONTENTLAYOUT); valuesMap.clear(); valuesMap.put("content", content); // generating page os.write(getPage(webHandler, valuesMap).getBytes(ENCODING)); }
From source file:org.wso2.carbon.bpel.ui.bpel2svg.SVGGenerateServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * Handles the HTTP process request which creates the SVG graph for a bpel process * * @param request servlet request//from w w w . ja va 2 s. c om * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Log log = LogFactory.getLog(SVGGenerateServlet.class); HttpSession session = request.getSession(true); //Get the bpel process id String pid = CharacterEncoder.getSafeText(request.getParameter("pid")); ServletConfig config = getServletConfig(); String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session); ConfigurationContext configContext = (ConfigurationContext) config.getServletContext() .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); String processDef = null; ProcessManagementServiceClient client = null; SVGInterface svg = null; String svgStr = null; ServletOutputStream sos = null; sos = response.getOutputStream(); try { client = new ProcessManagementServiceClient(cookie, backendServerURL, configContext, request.getLocale()); //Gets the bpel process definition needed to create the SVG from the processId processDef = client.getProcessInfo(QName.valueOf(pid)).getDefinitionInfo().getDefinition() .getExtraElement().toString(); BPELInterface bpel = new BPELImpl(); //Converts the bpel process definition to an omElement which is how the AXIS2 Object Model (AXIOM) // represents an XML document OMElement bpelStr = bpel.load(processDef); /** * Process the OmElement containing the bpel process definition * Process the subactivites of the bpel process by iterating through the omElement * */ bpel.processBpelString(bpelStr); //Create a new instance of the LayoutManager for the bpel process LayoutManager layoutManager = BPEL2SVGFactory.getInstance().getLayoutManager(); //Set the layout of the SVG to vertical layoutManager.setVerticalLayout(true); //Get the root activity i.e. the Process Activity layoutManager.layoutSVG(bpel.getRootActivity()); svg = new SVGImpl(); //Set the root activity of the SVG i.e. the Process Activity svg.setRootActivity(bpel.getRootActivity()); //Set the content type of the HTTP response as "image/svg+xml" response.setContentType("image/svg+xml"); //Get the SVG graph created for the process as a SVG string svgStr = svg.generateSVGString(); //Checks whether the SVG string generated contains a value if (svgStr != null) { // stream to write binary data into the response sos.write(svgStr.getBytes(Charset.defaultCharset())); sos.flush(); sos.close(); } } catch (ProcessManagementException e) { log.error("SVG Generation Error", e); String errorSVG = "<svg version=\"1.1\"\n" + " xmlns=\"http://www.w3.org/2000/svg\"><text y=\"50\">Could not display SVG</text></svg>"; sos.write(errorSVG.getBytes(Charset.defaultCharset())); sos.flush(); sos.close(); } }
From source file:org.oscarehr.document.web.ManageDocumentAction.java
public ActionForward getPage(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, int pageNum) { ServletOutputStream outs = null; BufferedInputStream bfis = null; try {//from w w w. ja v a 2s . c o m String doc_no = request.getParameter("doc_no"); log.debug("Document No :" + doc_no); LogAction.addLog((String) request.getSession().getAttribute("user"), LogConst.READ, LogConst.CON_DOCUMENT, doc_no, request.getRemoteAddr()); Document d = documentDAO.getDocument(doc_no); log.debug("Document Name :" + d.getDocfilename()); outs = response.getOutputStream(); if (d.getContenttype().equals("application/pdf")) { File outfile = hasCacheVersion(d, pageNum); if (outfile == null) { log.debug("No Cache Version"); outfile = createCacheVersion(d, pageNum); } else { log.debug("THERE WAS A CACHE Version " + outfile); } response.setContentType("image/png"); //read the file name. response.setHeader("Content-Disposition", "attachment;filename=" + d.getDocfilename()); bfis = new BufferedInputStream(new FileInputStream(outfile)); int data; while ((data = bfis.read()) != -1) { outs.write(data); } bfis.close(); } else { File outfile = new File(EDocUtil.getDocumentPath(d.getDocfilename())); response.setContentType(d.getContenttype()); response.setHeader("Content-Disposition", "attachment;filename=" + d.getDocfilename()); bfis = new BufferedInputStream(new FileInputStream(outfile)); int data; while ((data = bfis.read()) != -1) { outs.write(data); } } outs.flush(); } catch (java.net.SocketException se) { MiscUtils.getLogger().error("Error", se); } catch (Exception e) { MiscUtils.getLogger().error("Error", e); } finally { if (bfis != null) try { bfis.close(); } catch (IOException e) { } if (outs != null) try { outs.close(); } catch (IOException e) { } } return null; }
From source file:org.structr.pdf.servlet.PdfServlet.java
@Override protected void renderAsyncOutput(HttpServletRequest request, HttpServletResponse response, App app, RenderContext renderContext, DOMNode rootElement) throws IOException { final AsyncContext async = request.startAsync(); final ServletOutputStream out = async.getResponse().getOutputStream(); final AtomicBoolean finished = new AtomicBoolean(false); final DOMNode rootNode = rootElement; response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "attachment;filename=\"FileName.pdf\""); threadPool.submit(new Runnable() { @Override/* w w w .j av a2s. c om*/ public void run() { try (final Tx tx = app.tx()) { // render rootNode.render(renderContext, 0); finished.set(true); tx.success(); } catch (Throwable t) { t.printStackTrace(); logger.warn("Error while rendering page {}: {}", rootNode.getName(), t.getMessage()); try { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); finished.set(true); } catch (IOException ex) { logger.warn("", ex); } } } }); // start output write listener out.setWriteListener(new WriteListener() { @Override public void onWritePossible() throws IOException { try { final Queue<String> queue = renderContext.getBuffer().getQueue(); String pageContent = ""; while (out.isReady()) { String buffer = null; synchronized (queue) { buffer = queue.poll(); } if (buffer != null) { pageContent += buffer; } else { if (finished.get()) { // TODO: implement parameters for wkhtmltopdf in settings Pdf pdf = new Pdf(); pdf.addPageFromString(pageContent); out.write(pdf.getPDF()); async.complete(); // prevent this block from being called again break; } Thread.sleep(1); } } } catch (EofException ee) { logger.warn( "Could not flush the response body content to the client, probably because the network connection was terminated."); } catch (IOException | InterruptedException t) { logger.warn("Unexpected exception", t); } } @Override public void onError(Throwable t) { if (t instanceof EofException) { logger.warn( "Could not flush the response body content to the client, probably because the network connection was terminated."); } else { logger.warn("Unexpected exception", t); } } }); }
From source file:org.oscarehr.document.web.ManageDocumentAction.java
public ActionForward viewDocPage(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {/*from ww w.j a v a2 s . com*/ log.debug("in viewDocPage"); ServletOutputStream outs = null; BufferedInputStream bfis = null; try { String doc_no = request.getParameter("doc_no"); String pageNum = request.getParameter("curPage"); if (pageNum == null) { pageNum = "0"; } Integer pn = Integer.parseInt(pageNum); log.debug("Document No :" + doc_no); LogAction.addLog((String) request.getSession().getAttribute("user"), LogConst.READ, LogConst.CON_DOCUMENT, doc_no, request.getRemoteAddr()); Document d = documentDAO.getDocument(doc_no); log.debug("Document Name :" + d.getDocfilename()); String name = d.getDocfilename() + "_" + pn + ".png"; log.debug("name " + name); File outfile = null; outs = response.getOutputStream(); if (d.getContenttype().contains("pdf")) { outfile = hasCacheVersion2(d, pn); if (outfile != null) { log.debug("got cached doc " + d.getDocfilename() + " from local cache"); } else { outfile = createCacheVersion2(d, pn); if (outfile != null) { log.debug("cache doc " + d.getDocfilename()); } } response.setContentType("image/png"); bfis = new BufferedInputStream(new FileInputStream(outfile)); int data; while ((data = bfis.read()) != -1) { outs.write(data); // outs.flush(); } } else if (d.getContenttype().contains("image")) { outfile = new File(EDocUtil.getDocumentPath(d.getDocfilename())); response.setContentType(d.getContenttype()); response.setContentLength((int) outfile.length()); response.setHeader("Content-Disposition", "inline; filename=" + d.getDocfilename()); bfis = new BufferedInputStream(new FileInputStream(outfile)); byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = bfis.read(buffer)) != -1) { outs.write(buffer, 0, bytesRead); } } response.setHeader("Content-Disposition", "attachment;filename=" + d.getDocfilename()); outs.flush(); } catch (java.net.SocketException se) { MiscUtils.getLogger().error("Error", se); } catch (Exception e) { MiscUtils.getLogger().error("Error", e); } finally { if (bfis != null) try { bfis.close(); } catch (IOException e) { } if (outs != null) try { outs.close(); } catch (IOException e) { } } return null; }
From source file:au.org.ala.biocache.web.WMSController.java
private void writeBytes(HttpServletResponse response, byte[] bytes) throws IOException { response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); ServletOutputStream outStream = response.getOutputStream(); outStream.write(bytes); outStream.flush();/*from w w w . j a va 2 s . c o m*/ outStream.close(); }
From source file:au.org.ala.biocache.web.WMSController.java
void displayBlankImage(HttpServletResponse response) { try {//from w w w.j a v a2 s . c o m ServletOutputStream outStream = response.getOutputStream(); outStream.write(blankImageBytes); outStream.flush(); outStream.close(); } catch (Exception e) { logger.error("Unable to write image", e); } }
From source file:net.sf.appstatus.web.pages.StatusPage.java
public void doGetHTML(StatusWebHandler webHandler, HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException, IOException { setup(resp, "text/html"); ServletOutputStream os = resp.getOutputStream(); Map<String, String> valuesMap = new HashMap<String, String>(); List<ICheckResult> results = webHandler.getAppStatus().checkAll(req.getLocale()); Collections.sort(results);//from www .java 2s . c o m boolean statusOk = true; int statusCode = 200; for (ICheckResult r : results) { if (r.getCode() != ICheckResult.OK && r.isFatal()) { resp.setStatus(500); statusCode = 500; statusOk = false; break; } } valuesMap.put("statusOk", String.valueOf(statusOk)); valuesMap.put("statusCode", String.valueOf(statusCode)); // STATUS TABLE StrBuilder sbStatusTable = new StrBuilder(); if (HtmlUtils.generateBeginTable(sbStatusTable, results.size())) { HtmlUtils.generateHeaders(sbStatusTable, "", "Group", "Name", "Description", "Code", "Resolution"); for (ICheckResult r : results) { HtmlUtils.generateRow(sbStatusTable, getStatus(r), r.getGroup(), r.getProbeName(), r.getDescription(), String.valueOf(r.getCode()), r.getResolutionSteps()); } HtmlUtils.generateEndTable(sbStatusTable, results.size()); } valuesMap.put("statusTable", sbStatusTable.toString()); // PROPERTIES TABLE StrBuilder sbPropertiesTable = new StrBuilder(); Map<String, Map<String, String>> properties = webHandler.getAppStatus().getProperties(); if (HtmlUtils.generateBeginTable(sbPropertiesTable, properties.size())) { HtmlUtils.generateHeaders(sbPropertiesTable, "", "Group", "Name", "Value"); for (Entry<String, Map<String, String>> cat : properties.entrySet()) { String category = cat.getKey(); for (Entry<String, String> r : cat.getValue().entrySet()) { HtmlUtils.generateRow(sbPropertiesTable, Resources.STATUS_PROP, category, r.getKey(), r.getValue()); } } HtmlUtils.generateEndTable(sbPropertiesTable, properties.size()); } valuesMap.put("propertiesTable", sbPropertiesTable.toString()); String content = HtmlUtils.applyLayout(valuesMap, PAGECONTENTLAYOUT); valuesMap.clear(); valuesMap.put("content", content); os.write(getPage(webHandler, valuesMap).getBytes(ENCODING)); }
From source file:es.juntadeandalucia.panelGestion.presentacion.controlador.impl.GeosearchController.java
/** * This method /* w w w. j a v a 2 s.co m*/ * TODO * * Para realizar la configuracin se obtienen los archivos de configuracin * se realizan las modificaciones necesarias y se le facilita al usuario * dichos archivos para que finalice l el procedimiento de configuracin. * Las ltimas versiones de Solr admiten modificaciones del Schema a travs * de un API REST pero consideramos lioso realizar por un lado la configuracin * del schema mediante API y transparente al usuario y por otro lado darle los * archivos al usuario para que los sustituya en Geosearch. * * @see https://wiki.apache.org/solr/SchemaRESTAPI */ public void downloadConfig() { String errorMessage = null; ServletOutputStream os = null; try { // checks // checks if specified a table if (tables.isEmpty()) { throw new Exception("No se ha especificado ninguna tabla"); } // checks if specified a field boolean specifiedField = false; tables_loop: for (GeosearchTableVO table : tables) { List<GeosearchFieldVO> fields = table.getFields(); for (GeosearchFieldVO field : fields) { if (field.isDefined()) { specifiedField = true; break tables_loop; } } } if (!specifiedField) { throw new Exception("No se ha configurado ningn campo de las tablas seleccionadas"); } // checks duplicated fields each table for (GeosearchTableVO table : tables) { if (tableHasDuplicatedFields(table)) { throw new Exception("Existen campos duplicados en la tabla '".concat(table.getTable().getName()) .concat("'. Revise su configuracin.")); } } // ovverides the duplicated field values overrideDuplicatedFields(); checkFieldErrors(); // gets the zip file with configuration byte[] configurationData = generateConfigurationZipData(); // configures the response HttpServletResponse response = (HttpServletResponse) externalCtx.getResponse(); response.setContentType(CONTENT_TYPE); response.addHeader("Content-disposition", "attachment; filename=\"".concat(FILE_NAME).concat("\"")); os = response.getOutputStream(); os.write(configurationData); os.flush(); os.close(); facesContext.responseComplete(); } catch (GeosearchException e) { errorMessage = "Error en la generacin de los archivos de configuracin: " + e.getLocalizedMessage(); } catch (ParserConfigurationException e) { errorMessage = "Error en la generacin de los archivos de configuracin: " + e.getLocalizedMessage(); } catch (XPathExpressionException e) { errorMessage = "Error en la generacin de los archivos de configuracin: " + e.getLocalizedMessage(); } catch (TransformerException e) { errorMessage = "Error al comprimir los archivos de configuracin: " + e.getLocalizedMessage(); } catch (IOException e) { errorMessage = "Error al comprimir los archivos de configuracin: " + e.getLocalizedMessage(); } catch (Exception e) { errorMessage = "Error en la descarga de la configuracin: " + e.getLocalizedMessage(); } finally { try { if (os != null) { os.flush(); os.close(); } } catch (IOException e) { errorMessage = "Error al comprimir los archivos de configuracin: " + e.getLocalizedMessage(); } } if (errorMessage != null) { StatusMessages.instance().add(Severity.ERROR, errorMessage); log.error(errorMessage); } else { // saves the new service for each table try { ServiceType geosearchType = serviceService.getServiceType("geobusquedas"); for (GeosearchTableVO geosearchTable : tables) { Table table = geosearchTable.getTable(); Service geosearchService = new Service(); geosearchService.setName(table.getName()); geosearchService.setServiceUrl(PanelSettings.geosearchMaster.getUrl().concat("/").concat(core)); geosearchService.setType(geosearchType); serviceService.create(geosearchService, table); } } catch (Exception e) { errorMessage = ""; StatusMessages.instance().add(Severity.ERROR, errorMessage); log.error(errorMessage); } } }