List of usage examples for javax.servlet.http HttpServletResponse flushBuffer
public void flushBuffer() throws IOException;
From source file:net.sourceforge.fenixedu.presentationTier.Action.phd.academicAdminOffice.PhdIndividualProgramProcessDA.java
public ActionForward generateReport(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException { SearchPhdIndividualProgramProcessBean searchBean = (SearchPhdIndividualProgramProcessBean) getObjectFromViewState( "searchProcessBean"); HSSFWorkbook workbook = new HSSFWorkbook(); PhdIndividualProgramProcessesReport report = new PhdIndividualProgramProcessesReport(workbook); report.build(searchBean);// w w w . j ava 2 s. c o m PhdGuidersReport guidersReport = new PhdGuidersReport(workbook); guidersReport.build(searchBean); EPFLCandidatesReport epflReport = new EPFLCandidatesReport(workbook); epflReport.build(searchBean); RecommendationLetterReport recommendationLetterReport = new RecommendationLetterReport(workbook); recommendationLetterReport.build(searchBean); response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment; filename=phd.xls"); workbook.write(response.getOutputStream()); response.getOutputStream().flush(); response.flushBuffer(); return null; }
From source file:Highcharts.ExportController.java
@RequestMapping(method = RequestMethod.POST) public void exporter(@RequestParam(value = "svg", required = false) String svg, @RequestParam(value = "type", required = false) String type, @RequestParam(value = "filename", required = false) String filename, @RequestParam(value = "width", required = false) String width, @RequestParam(value = "scale", required = false) String scale, @RequestParam(value = "options", required = false) String options, @RequestParam(value = "constr", required = false) String constructor, @RequestParam(value = "callback", required = false) String callback, HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException, InterruptedException, SVGConverterException, NoSuchElementException, PoolException, TimeoutException { long start1 = System.currentTimeMillis(); MimeType mime = getMime(type); filename = getFilename(filename); Float parsedWidth = widthToFloat(width); Float parsedScale = scaleToFloat(scale); options = sanitize(options);//from ww w . ja v a 2 s . c o m String input; boolean convertSvg = false; if (options != null) { // create a svg file out of the options input = options; callback = sanitize(callback); } else { // assume SVG conversion if (svg == null) { throw new ServletException("The manadatory svg POST parameter is undefined."); } else { svg = sanitize(svg); if (svg == null) { throw new ServletException("The manadatory svg POST parameter is undefined."); } convertSvg = true; input = svg; } } ByteArrayOutputStream stream = null; if (convertSvg && mime.equals(MimeType.SVG)) { // send this to the client, without converting. stream = new ByteArrayOutputStream(); stream.write(input.getBytes()); } else { //stream = SVGCreator.getInstance().convert(input, mime, constructor, callback, parsedWidth, parsedScale); stream = converter.convert(input, mime, constructor, callback, parsedWidth, parsedScale); } if (stream == null) { throw new ServletException("Error while converting"); } logger.debug(request.getHeader("referer") + " Total time: " + (System.currentTimeMillis() - start1)); response.reset(); response.setCharacterEncoding("utf-8"); response.setContentLength(stream.size()); response.setStatus(HttpStatus.OK.value()); response.setHeader("Content-disposition", "attachment; filename=\"" + filename + "." + mime.name().toLowerCase() + "\""); IOUtils.write(stream.toByteArray(), response.getOutputStream()); response.flushBuffer(); }
From source file:io.apiman.gateway.platforms.servlet.GatewayServlet.java
/** * Generic handler for all types of http actions/verbs. * @param req/* w ww . j a v a 2 s.c o m*/ * @param resp * @param action */ protected void doAction(final HttpServletRequest req, final HttpServletResponse resp, String action) { try { ServiceRequest srequest = readRequest(req); srequest.setType(action); IServiceRequestExecutor executor = getEngine().executor(srequest, new IAsyncResultHandler<IEngineResult>() { @Override public void handle(IAsyncResult<IEngineResult> asyncResult) { if (asyncResult.isSuccess()) { IEngineResult engineResult = asyncResult.getResult(); if (engineResult.isResponse()) { try { writeResponse(resp, engineResult.getServiceResponse()); final ServletOutputStream outputStream = resp.getOutputStream(); engineResult.bodyHandler(new IAsyncHandler<IApimanBuffer>() { public void handle(IApimanBuffer chunk) { try { if (chunk instanceof ByteBuffer) { byte[] buffer = (byte[]) chunk.getNativeBuffer(); outputStream.write(buffer, 0, chunk.length()); } else { outputStream.write(chunk.getBytes()); } } catch (IOException e) { // This will get caught by the service connector, which will abort the // connection to the back-end service. throw new RuntimeException(e); } } }); engineResult.endHandler(new IAsyncHandler<Void>() { @Override public void handle(Void result) { try { resp.flushBuffer(); } catch (IOException e) { // This will get caught by the service connector, which will abort the // connection to the back-end service. throw new RuntimeException(e); } } }); } catch (IOException e) { // this would mean we couldn't get the output stream from the response, so we // need to abort the engine result (which will let the back-end connection // close down). engineResult.abort(); throw new RuntimeException(e); } } else { writeFailure(resp, engineResult.getPolicyFailure()); } } else { writeError(resp, asyncResult.getError()); } } }); executor.streamHandler(new IAsyncHandler<ISignalWriteStream>() { @Override public void handle(ISignalWriteStream connectorStream) { try { final InputStream is = req.getInputStream(); ByteBuffer buffer = new ByteBuffer(2048); int numBytes = buffer.readFrom(is); while (numBytes != -1) { connectorStream.write(buffer); numBytes = buffer.readFrom(is); } connectorStream.end(); } catch (IOException e) { connectorStream.abort(); throw new RuntimeException(e); } } }); executor.execute(); } catch (Throwable e) { writeError(resp, e); } finally { GatewayThreadContext.reset(); } }
From source file:org.andromda.presentation.gui.FileDownloadServlet.java
/** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *//* w w w. ja v a2 s.c o 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.jlibrary.web.servlet.JLibraryContentLoaderServlet.java
private void processContent(HttpServletRequest req, HttpServletResponse resp) { try {//from w ww . j a v a 2 s . co m resp.setCharacterEncoding("ISO-8859-1"); req.setCharacterEncoding("ISO-8859-1"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } String appURL = req.getContextPath(); String uri = req.getRequestURI(); String path = StringUtils.difference(appURL + "/repositories", uri); if (path.equals("") || path.equals("/")) { // call to /repositories try { Ticket ticket = TicketService.getTicketService().getSystemTicket(); List repoInfo = repositoryService.findAllRepositoriesInfo(ticket); Iterator it = repoInfo.iterator(); List<RepositoryInfo> repositories = new ArrayList<RepositoryInfo>(); while (it.hasNext()) { RepositoryInfo info = (RepositoryInfo) it.next(); if (info.getName().equals("system") || info.getName().equals("default")) { continue; } repositories.add(info); } RequestDispatcher rd = getServletContext().getRequestDispatcher("/repositories.jsp"); req.setAttribute("repositories", repositories); rd.forward(req, resp); return; } catch (Exception e) { logger.error(e.getMessage(), e); //TODO: mandar a una pgina de error esttica } } String[] pathElements = StringUtils.split(path, "/"); String repositoryName = getRepositoryName(req); Ticket ticket = TicketService.getTicketService().getTicket(req, repositoryName); Repository repository = null; try { repository = loadRepository(repositoryName, ticket); if (pathElements.length > 1) { if (pathElements[1].equals("categories")) { String categoryPath = StringUtils .difference(appURL + "/repositories/" + repositoryName + "/categories", uri); Category category = findCategory(repository, pathElements); if (category == null) { resp.setStatus(HttpServletResponse.SC_NOT_FOUND); resp.flushBuffer(); } else { String output = exportCategory(req, resp, ticket, repository, category); resp.getOutputStream().write(output.getBytes()); resp.flushBuffer(); } return; } } Node node = null; String nodePath = StringUtils.difference(appURL + "/repositories/" + repositoryName, uri); if (pathElements.length == 1) { node = repository.getRoot(); } else { node = findNode(ticket, repositoryService, nodePath); } if (node == null) { logger.debug("Node could not be found"); } else { req.setAttribute("node", node); /* resp.setDateHeader("Last-Modified", node.getDate().getTime()); resp.setDateHeader("Age", 86400); // cache a day */ if (node.isDocument()) { Document document = (Document) node; byte[] output; if ("true".equals(req.getParameter("download"))) { output = repositoryService.loadDocumentContent(document.getId(), ticket); if (document.isImage()) { resp.setContentType( Types.getMimeTypeForExtension(FileUtils.getExtension(document.getPath()))); } else { resp.setContentType("application/octet-stream"); } } else { output = exportDocument(req, ticket, repository, node).getBytes(); } resp.getOutputStream().write(output); resp.flushBuffer(); } else if (node.isDirectory()) { // Search for a root document (index.html) String output = exportDirectory(req, resp, ticket, repository, node); resp.getOutputStream().write(output.getBytes()); resp.flushBuffer(); } else if (node.isResource()) { exportResouce(req, resp, repositoryService, ticket, node); } } } catch (NodeNotFoundException nnfe) { logErrorAndForward(req, resp, repositoryName, nnfe, "The requested page could not be found."); } catch (SecurityException se) { logErrorAndForward(req, resp, repositoryName, se, "You do not have enough rights for accessing to the requested page."); } catch (Exception e) { //TODO:mandar a pgina de error esttica e.printStackTrace(); } }
From source file:net.sf.farrago.server.FarragoServletCommandSink.java
private void handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException { ObjectInputStream ois = null; ObjectOutputStream oos = null; try {/* w ww . j a va 2 s . co m*/ // Get the method to execute String method = httpServletRequest.getHeader(ServletCommandSinkIdentifier.METHOD_IDENTIFIER); if (method != null) { ois = new ObjectInputStream(httpServletRequest.getInputStream()); // And initialize the output OutputStream os = httpServletResponse.getOutputStream(); oos = new ObjectOutputStream(os); Object objectToReturn = null; try { // Some command to process ? if (method.equals(ServletCommandSinkIdentifier.PROCESS_COMMAND)) { // Read parameter objects Long connuid = (Long) ois.readObject(); Long uid = (Long) ois.readObject(); Command cmd = (Command) ois.readObject(); CallingContext ctx = (CallingContext) ois.readObject(); // Delegate execution to the CommandProcessor objectToReturn = processor.process(connuid, uid, cmd, ctx); } else if (method.equals(ServletCommandSinkIdentifier.CONNECT_COMMAND)) { String url = ois.readUTF(); Properties props = (Properties) ois.readObject(); Properties clientInfo = (Properties) ois.readObject(); CallingContext ctx = (CallingContext) ois.readObject(); ConnectionConfiguration connectionConfiguration = VJdbcConfiguration.singleton() .getConnection(url); if (connectionConfiguration != null) { Connection conn = connectionConfiguration.create(props); objectToReturn = processor.registerConnection(conn, connectionConfiguration, clientInfo, ctx); } else { objectToReturn = new SQLException("VJDBC-Connection " + url + " not found"); } } } catch (Throwable t) { // Wrap any exception so that it can be transported back to // the client objectToReturn = SQLExceptionHelper.wrap(t); } // Write the result in the response buffer oos.writeObject(objectToReturn); oos.flush(); httpServletResponse.flushBuffer(); } else { // No VJDBC-Method ? Then we redirect the stupid browser user to // some information page :-) httpServletResponse.sendRedirect("index.html"); } } catch (Exception e) { logger.error("Unexpected Exception", e); throw new ServletException(e); } finally { StreamCloser.close(ois); StreamCloser.close(oos); } }
From source file:org.jasig.cas.support.pac4j.web.flow.ClientLogoutAction.java
/** * {@inheritDoc}/*w w w . ja v a 2 s . com*/ */ @Override protected Event doExecute(final RequestContext context) throws Exception { final HttpServletRequest request = WebUtils.getHttpServletRequest(context); final HttpServletResponse response = WebUtils.getHttpServletResponse(context); final WebContext webContext = new J2EContext(request, response); //action is like a filter mapping String action = request.getParameter("action"); if (action == null) { action = (String) request.getAttribute("action"); } // in login's webflow : we can get the value from context as it has already been stored String tgtId = WebUtils.getTicketGrantingTicketId(context); // for logout, we need to get the cookie's value if (tgtId == null) { tgtId = this.ticketGrantingTicketCookieGenerator.retrieveCookieValue(request); } final TicketGrantingTicket ticketGrantingTicket = this.ticketRegistry.getTicket(tgtId, TicketGrantingTicket.class); Authentication authentication = ticketGrantingTicket.getAuthentication(); Object externalAuth = null; if (authentication == null) { //let cas standard go on return success(); } else { logAuthentication(authentication); Object client = null; // get pac4j client name String clientName = (String) authentication.getAttributes().get("clientName"); logger.debug("TGT(" + tgtId + "), pac4j client: " + clientName); if (StringUtils.isNotBlank(clientName)) { // get pac4j client client = (BaseClient<Credentials, CommonProfile>) this.clients.findClient(clientName); externalAuth = getExtAuthentication(authentication); if (externalAuth != null) { boolean dologout = false; if (client instanceof Saml2ClientWrapper) { Saml2ClientWrapper saml2ClientWrapper = (Saml2ClientWrapper) client; logExtAuthentication(client, externalAuth, action, clientName, tgtId); if (action == null) { //stop flow, redirect post to idp saml2ClientWrapper.browserLogoutRedirectToIdp(webContext, (org.springframework.security.core.Authentication) externalAuth); dologout = false; response.flushBuffer(); final ExternalContext externalContext = ExternalContextHolder.getExternalContext(); externalContext.recordResponseComplete(); return new Event(this, "stop"); } else { if (action.equals("SingleLogout")) { //validate browser redirect assertion and then proceed with the standard logout //to do: back channel saml also is executed here, but the flow must be stopped //browser post redirect --> ok, invalid (print to jsp/go on logout flow) //back channel --> ok, invalid (stop flow) logger.debug("pac4j client: " + clientName + " processing logout saml assertion"); dologout = saml2ClientWrapper.processLogout(webContext, (org.springframework.security.core.Authentication) externalAuth); logger.debug("dologout: " + dologout); } else { logger.error("pac4j client: " + clientName + " action: " + action + " isnt supported, incoming assertion not mappet to cas logout flow"); } } } if (client instanceof CasClientWrapper) { CasClientWrapper clientWrapper = (CasClientWrapper) client; logExtAuthentication(client, externalAuth, action, clientName, tgtId); if (action == null) { logger.debug("pac4j client: " + clientName + " redirect to idp for remote logout and wait to be redirected here at /logout?action=SingleLogout"); dologout = clientWrapper.browserLogoutRedirectToIdp(webContext, (org.springframework.security.core.Authentication) externalAuth); return new Event(this, "clientRedirect"); } else { if (action.equals("SingleLogout")) { logger.debug("pac4j client: " + clientName + " redirect here from remote server. carry on standard web flow"); return success(); } else { logger.error("pac4j client: " + clientName + " action: " + action + " isnt supported, incoming assertion not mappet to cas logout flow"); } } } if (dologout) { logger.warn("pac4j client: " + clientName + " authorized logout proceed cas logout flow"); return success(); } else { logger.error("pac4j client: " + clientName + " has not authorized logout, throw error"); return error(); } } else { logger.warn("pac4j client: " + clientName + " doesnt support logout"); return success(); } } else { logger.debug("non a client pac4j auth, carry on cas webflow"); return success(); } } }
From source file:com.genscript.gsscm.order.web.OrderAction.java
public void createTxt4OrderItems() { StringBuffer sb = new StringBuffer(); allitemsDetail = this.orderService.getAllItemsDetail(sessOrderNo, 1); long r1 = System.currentTimeMillis(); String fileName = "orderNo-" + this.sessOrderNo + r1 + ".txt"; try {//from ww w. j a va 2 s .c om HttpServletRequest request = ServletActionContext.getRequest(); File tempFile = new File(getDocumentItemStorage(request) + separator + fileName); if (tempFile.exists()) { if (tempFile.delete()) { System.out.println("delete the ...." + tempFile.getName()); } } FileOutputStream fos = null; FileUtils.forceMkdir(tempFile.getParentFile()); System.out.println(">>>>>>>" + allitemsDetail.toString()); fos = new FileOutputStream(tempFile, true); if (allitemsDetail == null || "".equals(allitemsDetail)) { allitemsDetail = "Sorry! there has none allitemsDetail about the order Items \r\n"; } sb.append(allitemsDetail); fos.write((sb.toString()).getBytes()); fos.flush(); fos.close(); HttpServletResponse response = Struts2Util.getResponse(); response.setCharacterEncoding("utf-8"); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); java.io.OutputStream os = response.getOutputStream(); String file = getDocumentItemStorage(request) + separator + fileName; java.io.FileInputStream fis = new java.io.FileInputStream(file); byte[] b = new byte[1024]; int i = 0; while ((i = fis.read(b)) > 0) { os.write(b, 0, i); } fis.close(); os.flush(); response.flushBuffer(); os.close(); } catch (Exception e) { WSException exDTO = exceptionUtil.getExceptionDetails(e); exceptionUtil.logException(exDTO, this.getClass(), e, new Exception().getStackTrace()[0].getMethodName(), "INTF0203", SessionUtil.getUserId()); Struts2Util.renderText(exDTO.getMessageDetail() + "\n" + exDTO.getAction()); e.printStackTrace(); } }
From source file:com.genscript.gsscm.order.web.OrderAction.java
public void createDocument4OrderItems() { StringBuffer sb = new StringBuffer(); allitemsDetail = this.orderService.getAllItemsDetail(sessOrderNo, 1); long r1 = System.currentTimeMillis(); String fileName = "orderNo-" + this.sessOrderNo + r1 + ".doc"; try {/*www .j a v a 2s .co m*/ HttpServletRequest request = ServletActionContext.getRequest(); File tempFile = new File(getDocumentItemStorage(request) + separator + fileName); if (tempFile.exists()) { if (tempFile.delete()) { System.out.println("delete the ...." + tempFile.getName()); } } FileOutputStream fos = null; FileUtils.forceMkdir(tempFile.getParentFile()); System.out.println(">>>>>>>" + allitemsDetail.toString()); fos = new FileOutputStream(tempFile, true); if (allitemsDetail == null || "".equals(allitemsDetail)) { allitemsDetail = "Sorry! there has none allitemsDetail about the order Items \r\n"; sb.append(allitemsDetail); } sb.append(allitemsDetail); fos.write((sb.toString()).getBytes()); fos.flush(); fos.close(); sb = null; HttpServletResponse response = Struts2Util.getResponse(); response.setCharacterEncoding("utf-8"); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); java.io.OutputStream os = response.getOutputStream(); String file = getDocumentItemStorage(request) + separator + fileName; java.io.FileInputStream fis = new java.io.FileInputStream(file); byte[] b = new byte[1024]; int i = 0; while ((i = fis.read(b)) > 0) { os.write(b, 0, i); } fis.close(); os.flush(); response.flushBuffer(); os.close(); } catch (Exception e) { System.out.println("Error exec!"); WSException exDTO = exceptionUtil.getExceptionDetails(e); exceptionUtil.logException(exDTO, this.getClass(), e, new Exception().getStackTrace()[0].getMethodName(), "INTF0203", SessionUtil.getUserId()); Struts2Util.renderText(exDTO.getMessageDetail() + "\n" + exDTO.getAction()); e.printStackTrace(); } }
From source file:com.genscript.gsscm.order.web.OrderAction.java
public String download() { String fileName = "Oligo_Batch_Order.xls"; HttpServletRequest request = ServletActionContext.getRequest(); try {/*from ww w . j a va 2 s . c o m*/ HttpServletResponse response = Struts2Util.getResponse(); response.setContentType("APPLICATION/DOWNLOAD;charset=utf-8"); response.setCharacterEncoding("utf-8"); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); java.io.OutputStream os = response.getOutputStream(); String file = getDocumentItemStorage(request) + separator + fileName; System.out.println(file); java.io.FileInputStream fis = new java.io.FileInputStream(file); byte[] b = new byte[1024]; int i = 0; while ((i = fis.read(b)) > 0) { os.write(b, 0, i); } fis.close(); os.flush(); response.flushBuffer(); os.close(); } catch (IOException e) { e.printStackTrace(); } return null; }