List of usage examples for javax.servlet ServletOutputStream close
public void close() throws IOException
From source file:org.oscarehr.document.web.ManageDocumentAction.java
public ActionForward view2(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // TODO: NEED TO CHECK FOR ACCESS 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()); // TODO: Right now this assumes it's a pdf which it shouldn't response.setContentType("image/png"); // response.setHeader("Content-Disposition", "attachment;filename=\"" + filename+ "\""); // read the file name. File file = new File(EDocUtil.getDocumentPath(d.getDocfilename())); RandomAccessFile raf = new RandomAccessFile(file, "r"); FileChannel channel = raf.getChannel(); ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()); PDFFile pdffile = new PDFFile(buf); // draw the first page to an image PDFPage ppage = pdffile.getPage(0);//from w ww .j a va 2 s.c o m log.debug("WIDTH " + (int) ppage.getBBox().getWidth() + " height " + (int) ppage.getBBox().getHeight()); // get the width and height for the doc at the default zoom Rectangle rect = new Rectangle(0, 0, (int) ppage.getBBox().getWidth(), (int) ppage.getBBox().getHeight()); log.debug("generate the image"); Image img = ppage.getImage(rect.width, rect.height, // width & height rect, // clip rect null, // null for the ImageObserver true, // fill background with white true // block until drawing is done ); log.debug("about to Print to stream"); ServletOutputStream outs = response.getOutputStream(); RenderedImage rendImage = (RenderedImage) img; ImageIO.write(rendImage, "png", outs); outs.flush(); outs.close(); return null; }
From source file:org.oscarehr.document.web.ManageDocumentAction.java
public ActionForward display(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String temp = request.getParameter("remoteFacilityId"); Integer remoteFacilityId = null; if (temp != null) remoteFacilityId = Integer.parseInt(temp); String doc_no = request.getParameter("doc_no"); log.debug("Document No :" + doc_no); String docxml = null;// w w w. j a v a 2s . c o m String contentType = null; byte[] contentBytes = null; String filename = null; // local document if (remoteFacilityId == null) { CtlDocument ctld = documentDAO.getCtrlDocument(Integer.parseInt(doc_no)); if (ctld.isDemographicDocument()) { LogAction.addLog((String) request.getSession().getAttribute("user"), LogConst.READ, LogConst.CON_DOCUMENT, doc_no, request.getRemoteAddr(), "" + ctld.getModuleId()); } else { 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()); docxml = d.getDocxml(); contentType = d.getContenttype(); File file = new File(EDocUtil.getDocumentPath(d.getDocfilename())); filename = d.getDocfilename(); if (file.exists()) contentBytes = FileUtils.readFileToByteArray(file); } else // remote document { FacilityIdIntegerCompositePk remotePk = new FacilityIdIntegerCompositePk(); remotePk.setIntegratorFacilityId(remoteFacilityId); remotePk.setCaisiItemId(Integer.parseInt(doc_no)); LoggedInInfo loggedInInfo = LoggedInInfo.loggedInInfo.get(); CachedDemographicDocument remoteDocument = null; CachedDemographicDocumentContents remoteDocumentContents = null; try { if (!CaisiIntegratorManager.isIntegratorOffline()) { DemographicWs demographicWs = CaisiIntegratorManager.getDemographicWs(); remoteDocument = demographicWs.getCachedDemographicDocument(remotePk); remoteDocumentContents = demographicWs.getCachedDemographicDocumentContents(remotePk); } } catch (Exception e) { MiscUtils.getLogger().error("Unexpected error.", e); CaisiIntegratorManager.checkForConnectionError(e); } if (CaisiIntegratorManager.isIntegratorOffline()) { Integer demographicId = IntegratorFallBackManager.getDemographicNoFromRemoteDocument(remotePk); MiscUtils.getLogger().debug("got demographic no from remote document " + demographicId); List<CachedDemographicDocument> remoteDocuments = IntegratorFallBackManager .getRemoteDocuments(demographicId); for (CachedDemographicDocument demographicDocument : remoteDocuments) { if (demographicDocument.getFacilityIntegerPk().getIntegratorFacilityId() == remotePk .getIntegratorFacilityId() && demographicDocument.getFacilityIntegerPk().getCaisiItemId() == remotePk .getCaisiItemId()) { remoteDocument = demographicDocument; remoteDocumentContents = IntegratorFallBackManager.getRemoteDocument(demographicId, remotePk); break; } MiscUtils.getLogger().error("End of the loop and didn't find the remoteDocument"); } } docxml = remoteDocument.getDocXml(); contentType = remoteDocument.getContentType(); filename = remoteDocument.getDocFilename(); contentBytes = remoteDocumentContents.getFileContents(); } if (docxml != null && !docxml.trim().equals("")) { ServletOutputStream outs = response.getOutputStream(); outs.write(docxml.getBytes()); outs.flush(); outs.close(); return null; } // TODO: Right now this assumes it's a pdf which it shouldn't if (contentType == null) { contentType = "application/pdf"; } response.setContentType(contentType); response.setContentLength(contentBytes.length); response.setHeader("Content-Disposition", "inline; filename=" + filename); log.debug("about to Print to stream"); ServletOutputStream outs = response.getOutputStream(); outs.write(contentBytes); outs.flush(); outs.close(); return null; }
From source file:org.webguitoolkit.ui.util.export.ExcelTableExport.java
public void writeTo(Table table, HttpServletResponse response) { TableExportOptions exportOptions = table.getExportOptions(); try {/*from w ww. ja v a 2s .co m*/ String filename = exportOptions.getFileName(); if (StringUtils.isEmpty(filename)) { filename = StringUtils.isNotEmpty(table.getTitle()) ? table.getTitle() : "sheet"; } ServletOutputStream out = response.getOutputStream(); response.setContentType("application/vnd.ms-excel"); response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + ".xls\""); try { writeTo(table, out); } catch (RuntimeException e1) { logger.error(e1); response.sendError(500, e1.getMessage()); return; } finally { out.close(); } } catch (IOException e) { logger.error(e.getMessage()); } }
From source file:com.portfolio.data.attachment.XSLService.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { /**/* www .j a v a 2 s . c o m*/ * Format demand: * <convert> * <portfolioid>{uuid}</portfolioid> * <portfolioid>{uuid}</portfolioid> * <nodeid>{uuid}</nodeid> * <nodeid>{uuid}</nodeid> * <documentid>{uuid}</documentid> * <xsl>{rpertoire}{fichier}</xsl> * <format>[pdf rtf xml ...]</format> * <parameters> * <maVar1>lala</maVar1> * ... * </parameters> * </convert> */ try { //On initialise le dataProvider Connection c = null; //On initialise le dataProvider if (ds == null) // Case where we can't deploy context.xml { c = getConnection(); } else { c = ds.getConnection(); } dataProvider.setConnection(c); credential = new Credential(c); } catch (Exception e) { e.printStackTrace(); } String origin = request.getRequestURL().toString(); /// Variable stuff int userId = 0; int groupId = 0; String user = ""; HttpSession session = request.getSession(true); if (session != null) { Integer val = (Integer) session.getAttribute("uid"); if (val != null) userId = val; val = (Integer) session.getAttribute("gid"); if (val != null) groupId = val; user = (String) session.getAttribute("user"); } /// TODO: A voire si un form get ne ferait pas l'affaire aussi /// On lis le xml /* BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while( (line = rd.readLine()) != null ) sb.append(line); DocumentBuilderFactory documentBuilderFactory =DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = null; Document doc=null; try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); doc = documentBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes("UTF-8"))); } catch( Exception e ) { e.printStackTrace(); } /// On lit les paramtres NodeList portfolioNode = doc.getElementsByTagName("portfolioid"); NodeList nodeNode = doc.getElementsByTagName("nodeid"); NodeList documentNode = doc.getElementsByTagName("documentid"); NodeList xslNode = doc.getElementsByTagName("xsl"); NodeList formatNode = doc.getElementsByTagName("format"); NodeList parametersNode = doc.getElementsByTagName("parameters"); //*/ // String xslfile = xslNode.item(0).getTextContent(); String xslfile = request.getParameter("xsl"); String format = request.getParameter("format"); // String format = formatNode.item(0).getTextContent(); String parameters = request.getParameter("parameters"); String documentid = request.getParameter("documentid"); String portfolios = request.getParameter("portfolioids"); String[] portfolioid = null; if (portfolios != null) portfolioid = portfolios.split(";"); String nodes = request.getParameter("nodeids"); String[] nodeid = null; if (nodes != null) nodeid = nodes.split(";"); System.out.println("PARAMETERS: "); System.out.println("xsl: " + xslfile); System.out.println("format: " + format); System.out.println("user: " + userId); System.out.println("portfolioids: " + portfolios); System.out.println("nodeids: " + nodes); System.out.println("parameters: " + parameters); boolean redirectDoc = false; if (documentid != null) { redirectDoc = true; System.out.println("documentid @ " + documentid); } boolean usefop = false; String ext = ""; if (MimeConstants.MIME_PDF.equals(format)) { usefop = true; ext = ".pdf"; } else if (MimeConstants.MIME_RTF.equals(format)) { usefop = true; ext = ".rtf"; } //// Paramtre portfolio-uuid et file-xsl // String uuid = request.getParameter("uuid"); // String xslfile = request.getParameter("xsl"); StringBuilder aggregate = new StringBuilder(); try { int portcount = 0; int nodecount = 0; // On aggrge les donnes if (portfolioid != null) { portcount = portfolioid.length; for (int i = 0; i < portfolioid.length; ++i) { String p = portfolioid[i]; String portfolioxml = dataProvider .getPortfolio(new MimeType("text/xml"), p, userId, groupId, "", null, null, 0) .toString(); aggregate.append(portfolioxml); } } if (nodeid != null) { nodecount = nodeid.length; for (int i = 0; i < nodeid.length; ++i) { String n = nodeid[i]; String nodexml = dataProvider.getNode(new MimeType("text/xml"), n, true, userId, groupId, "") .toString(); aggregate.append(nodexml); } } // Est-ce qu'on a eu besoin d'aggrger les donnes? String input = aggregate.toString(); String pattern = "<\\?xml[^>]*>"; // Purge previous xml declaration input = input.replaceAll(pattern, ""); input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<!DOCTYPE xsl:stylesheet [" + "<!ENTITY % lat1 PUBLIC \"-//W3C//ENTITIES Latin 1 for XHTML//EN\" \"" + servletDir + "xhtml-lat1.ent\">" + "<!ENTITY % symbol PUBLIC \"-//W3C//ENTITIES Symbols for XHTML//EN\" \"" + servletDir + "xhtml-symbol.ent\">" + "<!ENTITY % special PUBLIC \"-//W3C//ENTITIES Special for XHTML//EN\" \"" + servletDir + "xhtml-special.ent\">" + "%lat1;" + "%symbol;" + "%special;" + "]>" + // For the pesky special characters "<root>" + input + "</root>"; // System.out.println("INPUT WITH PROXY:"+ input); /// Rsolution des proxys DocumentBuilder documentBuilder; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(input)); Document doc = documentBuilder.parse(is); /// Proxy stuff XPath xPath = XPathFactory.newInstance().newXPath(); String filterRes = "//asmResource[@xsi_type='Proxy']"; String filterCode = "./code/text()"; NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET); XPathExpression codeFilter = xPath.compile(filterCode); for (int i = 0; i < nodelist.getLength(); ++i) { Node res = nodelist.item(i); Node gp = res.getParentNode(); // resource -> context -> container Node ggp = gp.getParentNode(); Node uuid = (Node) codeFilter.evaluate(res, XPathConstants.NODE); /// Fetch node we want to replace String returnValue = dataProvider .getNode(new MimeType("text/xml"), uuid.getTextContent(), true, userId, groupId, "") .toString(); Document rep = documentBuilder.parse(new InputSource(new StringReader(returnValue))); Element repNode = rep.getDocumentElement(); Node proxyNode = repNode.getFirstChild(); proxyNode = doc.importNode(proxyNode, true); // adoptNode have some weird side effect. To be banned // doc.replaceChild(proxyNode, gp); ggp.insertBefore(proxyNode, gp); // replaceChild doesn't work. ggp.removeChild(gp); } try // Convert XML document to string { DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); writer.flush(); input = writer.toString(); } catch (TransformerException ex) { ex.printStackTrace(); } // System.out.println("INPUT DATA:"+ input); // Setup a buffer to obtain the content length ByteArrayOutputStream stageout = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); //// Setup Transformer (1st stage) /// Base path String basepath = xslfile.substring(0, xslfile.indexOf(File.separator)); String firstStage = baseDir + File.separator + basepath + File.separator + "karuta" + File.separator + "xsl" + File.separator + "html2xml.xsl"; System.out.println("FIRST: " + firstStage); Source xsltSrc1 = new StreamSource(new File(firstStage)); Transformer transformer1 = transFactory.newTransformer(xsltSrc1); StreamSource stageSource = new StreamSource(new ByteArrayInputStream(input.getBytes())); Result stageRes = new StreamResult(stageout); transformer1.transform(stageSource, stageRes); // Setup Transformer (2nd stage) String secondStage = baseDir + File.separator + xslfile; Source xsltSrc2 = new StreamSource(new File(secondStage)); Transformer transformer2 = transFactory.newTransformer(xsltSrc2); // Configure parameter from xml String[] table = parameters.split(";"); for (int i = 0; i < table.length; ++i) { String line = table[i]; int var = line.indexOf(":"); String par = line.substring(0, var); String val = line.substring(var + 1); transformer2.setParameter(par, val); } // Setup input StreamSource xmlSource = new StreamSource(new ByteArrayInputStream(stageout.toString().getBytes())); // StreamSource xmlSource = new StreamSource(new File(baseDir+origin, "projectteam.xml") ); Result res = null; if (usefop) { /// FIXME: Might need to include the entity for html stuff? //Setup FOP //Make sure the XSL transformation's result is piped through to FOP Fop fop = fopFactory.newFop(format, out); res = new SAXResult(fop.getDefaultHandler()); //Start the transformation and rendering process transformer2.transform(xmlSource, res); } else { res = new StreamResult(out); //Start the transformation and rendering process transformer2.transform(xmlSource, res); } if (redirectDoc) { // /resources/resource/file/{uuid}[?size=[S|L]&lang=[fr|en]] String urlTarget = "http://" + server + "/resources/resource/file/" + documentid; System.out.println("Redirect @ " + urlTarget); HttpClientBuilder clientbuilder = HttpClientBuilder.create(); CloseableHttpClient client = clientbuilder.build(); HttpPost post = new HttpPost(urlTarget); post.addHeader("referer", origin); String sessionid = request.getSession().getId(); System.out.println("Session: " + sessionid); post.addHeader("Cookie", "JSESSIONID=" + sessionid); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); ByteArrayBody body = new ByteArrayBody(out.toByteArray(), "generated" + ext); builder.addPart("uploadfile", body); HttpEntity entity = builder.build(); post.setEntity(entity); HttpResponse ret = client.execute(post); String stringret = new BasicResponseHandler().handleResponse(ret); int code = ret.getStatusLine().getStatusCode(); response.setStatus(code); ServletOutputStream output = response.getOutputStream(); output.write(stringret.getBytes(), 0, stringret.length()); output.close(); client.close(); /* HttpURLConnection connection = CreateConnection( urlTarget, request ); /// Helping construct Json connection.setRequestProperty("referer", origin); /// Send post data ServletInputStream inputData = request.getInputStream(); DataOutputStream writer = new DataOutputStream(connection.getOutputStream()); byte[] buffer = new byte[1024]; int dataSize; while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 ) { writer.write(buffer, 0, dataSize); } inputData.close(); writer.close(); RetrieveAnswer(connection, response, origin); //*/ } else { response.reset(); response.setHeader("Content-Disposition", "attachment; filename=generated" + ext); response.setContentType(format); response.setContentLength(out.size()); response.getOutputStream().write(out.toByteArray()); response.getOutputStream().flush(); } } catch (Exception e) { String message = e.getMessage(); response.setStatus(500); response.getOutputStream().write(message.getBytes()); response.getOutputStream().close(); e.printStackTrace(); } finally { dataProvider.disconnect(); } }
From source file:ub.botiga.ServletDispatcher.java
private void controlProduct(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String location = request.getRequestURI(); String prod = URLDecoder.decode(location.split("/")[3], "UTF-8"); Product p = data.getProductes().get(prod); User u = (User) request.getSession().getAttribute("user"); if (u == null || p == null) { response.sendRedirect("/Botiga"); return;//from www .j a v a 2 s .c om } if (!u.getProducts().containsKey(p.getName())) { showPage(request, response, "error403.jsp"); return; } ServletContext context = getServletContext(); String realpath = context.getRealPath("/WEB-INF/products" + p.getPath()); File file = new File(realpath); int length; ServletOutputStream outStream = response.getOutputStream(); String mimetype = context.getMimeType(realpath); if (mimetype == null) { mimetype = "application/octet-stream"; } response.setContentType(mimetype); response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); byte[] byteBuffer = new byte[1024]; DataInputStream in = new DataInputStream(new FileInputStream(file)); while ((length = in.read(byteBuffer)) != -1) { outStream.write(byteBuffer, 0, length); } in.close(); outStream.close(); }
From source file:org.inbio.ait.web.ajax.controller.TableController.java
/** * Return the XML with the results//from w w w . j av a2s . co m * @param request * @param response * @param species * @param matchesByPolygon * @return * @throws java.lang.Exception */ private ModelAndView writeReponse(HttpServletRequest request, HttpServletResponse response, Long[][] matrix, List<SpeciesNode> species) throws Exception { response.setCharacterEncoding("ISO-8859-1"); response.setContentType("text/xml"); ServletOutputStream out = response.getOutputStream(); StringBuilder result = new StringBuilder(); result.append("<?xml version='1.0' encoding='ISO-8859-1'?><response>"); result.append("<speciesList>"); for (SpeciesNode sp : species) { result.append("<species>" + sp.getName() + "</species>"); } result.append("</speciesList>"); if (matrix.length > 0) { int rows = matrix.length; int columns = matrix[0].length; for (int i = 0; i < rows; i++) { result.append("<row>"); for (int j = 0; j < columns; j++) { result.append("<column>" + matrix[i][j] + "</column>"); } result.append("</row>"); } } result.append("</response>"); out.println(result.toString()); out.flush(); out.close(); return null; }
From source file:com.globalsight.connector.mindtouch.MindTouchCreateJobHandler.java
@ActionHandler(action = "initTree", formClass = "") public void initTree(HttpServletRequest p_request, HttpServletResponse p_response, Object form) throws Exception { ServletOutputStream out = p_response.getOutputStream(); try {//from w ww . j a va 2 s . co m String mtcId = p_request.getParameter("mtcId"); MindTouchConnector mtc = MindTouchManager.getMindTouchConnectorById(Long.parseLong(mtcId)); MindTouchHelper helper = new MindTouchHelper(mtc); String treeXml = helper.getTreeXml("home"); MindTouchPage mtp = helper.parseTreeXml(treeXml); helper.shutdownHttpClient(); out.write(getJSON(mtp).getBytes("UTF-8")); } catch (Exception e) { logger.error("Fail to init the sitemap tree.", e); } finally { out.close(); pageReturn(); } }
From source file:com.alfaariss.oa.helper.stylesheet.handler.StreamHandler.java
/** * @see com.alfaariss.oa.helper.stylesheet.handler.AbstractStyleSheetHandler#process(com.alfaariss.oa.api.session.ISession, javax.servlet.http.HttpServletResponse, boolean) *///from www. jav a2 s . c o m public void process(ISession session, HttpServletResponse response, boolean isWireless) throws StyleSheetException { BufferedReader streamInput = null; ServletOutputStream responseOutputStream = null; try { String sStyleSheet = super.resolveStyleSheetLocation(session, isWireless); if (sStyleSheet != null) { URL oURL = new URL(sStyleSheet); streamInput = new BufferedReader(new InputStreamReader(oURL.openStream())); responseOutputStream = response.getOutputStream(); String sInput = null; while ((sInput = streamInput.readLine()) != null) { sInput += "\r\n"; responseOutputStream.write(sInput.getBytes(CHARSET)); } } } catch (Exception e) { _logger.error("Could not stream stylesheet", e); throw new StyleSheetException(SystemErrors.ERROR_INTERNAL); } finally { try { if (responseOutputStream != null) { responseOutputStream.flush(); responseOutputStream.close(); } } catch (Exception e) { _logger.error("Could not close output stream", e); } try { if (streamInput != null) streamInput.close(); } catch (Exception e) { _logger.error("Could not close input stream", e); } } }
From source file:org.fao.geonet.api.registries.vocabularies.KeywordsApi.java
/** * Gets the thesaurus./*from ww w. ja v a2 s . c o m*/ * * @param thesaurus the thesaurus * @param request the request * @param response the response * @return the thesaurus * @throws Exception the exception */ @ApiOperation(value = "Download a thesaurus by name", nickname = "getThesaurus", notes = "Download the thesaurus in SKOS format.") @RequestMapping(value = "/{thesaurus:.+}", method = RequestMethod.GET, produces = { MediaType.TEXT_XML_VALUE }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Thesaurus in SKOS format."), @ApiResponse(code = 404, message = ApiParams.API_RESPONSE_RESOURCE_NOT_FOUND) }) @ResponseBody @ResponseStatus(HttpStatus.OK) public void getThesaurus( @ApiParam(value = "Thesaurus to download.", required = true) @PathVariable(value = "thesaurus") String thesaurus, HttpServletRequest request, HttpServletResponse response) throws Exception { ServiceContext context = ApiUtils.createServiceContext(request); GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME); ThesaurusManager manager = gc.getBean(ThesaurusManager.class); Thesaurus directory = manager.getThesaurusByName(thesaurus); if (directory == null) throw new IllegalArgumentException("Thesaurus not found --> " + thesaurus); Path directoryFile = directory.getFile(); if (!Files.exists(directoryFile)) throw new IllegalArgumentException("Thesaurus file not found --> " + thesaurus); response.setContentType("text/xml"); response.setHeader("Content-Disposition", "attachment;filename=" + directoryFile.getFileName()); ServletOutputStream out = response.getOutputStream(); BufferedReader reader1 = new BufferedReader( new InputStreamReader(new FileInputStream(directoryFile.toFile()), Charset.forName("UTF-8"))); IOUtils.copy(reader1, out); out.flush(); out.close(); }
From source file:com.fufang.bi.controllers.ChainReportController.java
@ApiOperation(value = "Excel", notes = "Excel") @ApiResponses(value = { @ApiResponse(code = 200, message = RETURNMESSAGE) }) @RequestMapping(value = "/jxctzh/downExcel", method = RequestMethod.POST) //, method = RequestMethod.POST public void downExcel(HttpServletRequest request, HttpServletResponse response, @ApiParam(required = false, value = excels) @RequestParam String query) { String path = request.getSession().getServletContext().getRealPath("/"); try {/*from w w w . j av a 2s . c o m*/ User user = (User) request.getSession().getAttribute("user"); String role = ""; role = (String) request.getSession().getAttribute("mark"); Integer chaintype = user.getChainType(); logger.debug("chaintype:" + chaintype); String data = request.getParameter("query"); System.out.println("query:" + data); JSONObject object = JSONObject.fromObject(data); Map<String, Comparable> querymap = new HashMap<String, Comparable>(); querymap = (Map) object; Integer select = (Integer) querymap.get("select");//?? String way = ""; if (null != querymap.get("way")) { way = (String) querymap.get("way").toString().trim(); } else { return; } Integer type = (Integer) querymap.get("type"); String sourcefilePath = path + "/" + "down/taizhang" + select + ".xls"; List<?> list = new ArrayList(); querymap.put("mark", role); if (type == 0) { querymap.put("amount", "t.notaxAmount");// } else { querymap.put("amount", "t.amount"); } InputStream inputStream; inputStream = new FileInputStream(sourcefilePath); String fileName = "tmp.xls"; Object obj = null; if (select == 1) { fileName = "?_.xls"; Integer id = user.getPharmacyId(); querymap.put("id", id); list = chainService.findAllCpharmacyExcel(querymap); StorageTotal sumData = new StorageTotal(); sumData = chainService.findAllCpharmacySum(querymap); obj = sumData; } else if (select == 2) { fileName = "?_?.xls"; if (way.equals("0")) {// Integer id = (Integer) querymap.get("id"); if (id == null) { logger.error("/jxctzh/downExcel id==null error"); return; } querymap.put("needs", 0); querymap.put("parent", 8); } else if (way.equals("1")) {// Integer id = null; if (user != null && (querymap.get("id") == null || "".equals(querymap.get("id")))) { id = user.getPharmacyId(); querymap.put("id", id); } String pharmacyCode = ""; String name = ""; String pinyin = ""; pharmacyCode = (String) querymap.get("pharmacyCode"); name = (String) querymap.get("name"); pinyin = (String) querymap.get("pinyin"); if ((pharmacyCode == null && name == null && pinyin == null) || ("".equals(pharmacyCode) && "".equals(name) && "".equals(pinyin))) { querymap.put("parent", 9);// ? if (0 == chaintype) { querymap.put("needs", 2); } else { querymap.put("needs", 3); } } else { querymap.put("needs", 1);//? ? } } StorageMilde sumData = new StorageMilde(); list = chainService.findAllCpharmacyMildeExcel(querymap); sumData = chainService.findAllCpharmacyMildeSum(querymap); obj = sumData; } else if (select == 3) { fileName = "?_.xls"; if (way.equals("0")) { querymap.put("needs", 0); querymap.put("parent", 8); } else if (way.equals("1")) { Integer id = null; if (user != null && (querymap.get("id") == null || "".equals(querymap.get("id")))) { id = user.getPharmacyId(); querymap.put("pharmacyid", id); } String pharmacyCode = ""; String name = ""; String pinyin = ""; pharmacyCode = (String) querymap.get("pharmacyCode"); name = (String) querymap.get("name"); pinyin = (String) querymap.get("pinyin"); if ((pharmacyCode == null && name == null && pinyin == null) || ("".equals(pharmacyCode) && "".equals(name) && "".equals(pinyin))) { querymap.put("parent", 9);// ? if (0 == chaintype) { querymap.put("needs", 2); } else { querymap.put("needs", 3); } } else { querymap.put("needs", 1);//? ? } querymap.put("pharmacyid", id); } StorageDetail sumData = new StorageDetail(); list = chainService.findAllCpharmacyDetailExcel(querymap); sumData = chainService.findAllCpharmacyDetailSum(querymap); obj = sumData; } fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1"); HSSFWorkbook workbook = createUploadSplitExcel(list, inputStream, select, obj); response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); // ? ServletOutputStream fOut = response.getOutputStream(); workbook.write(fOut); fOut.flush(); fOut.close(); } catch (FileNotFoundException e) { logger.error("/jxctzh/downExcel FileNotFoundException error"); e.printStackTrace(); } catch (UnsupportedEncodingException e) { logger.error("/jxctzh/downExcel UnsupportedEncodingException error"); e.printStackTrace(); } catch (IOException e) { logger.error("/jxctzh/downExcel IOException error"); e.printStackTrace(); } }