List of usage examples for javax.servlet ServletContext getMimeType
public String getMimeType(String file);
null
if the MIME type is not known. From source file:com.eufar.asmm.server.DownloadFunction.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("DownloadFunction - the function started"); ServletContext context = getServletConfig().getServletContext(); request.setCharacterEncoding("UTF-8"); String dir = context.getRealPath("/tmp"); ;//from www . j a va 2 s.co m String filename = ""; File fileDir = new File(dir); try { System.out.println("DownloadFunction - create the file on server"); filename = request.getParameterValues("filename")[0]; String xmltree = request.getParameterValues("xmltree")[0]; // format xml code to pretty xml code Document doc = DocumentHelper.parseText(xmltree); StringWriter sw = new StringWriter(); OutputFormat format = OutputFormat.createPrettyPrint(); format.setIndent(true); format.setIndentSize(4); XMLWriter xw = new XMLWriter(sw, format); xw.write(doc); Writer out = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(dir + "/" + filename), "UTF-8")); out.append(sw.toString()); out.flush(); out.close(); } catch (Exception ex) { System.out.println("ERROR during rendering: " + ex); } try { System.out.println("DownloadFunction - send file to user"); ServletOutputStream out = response.getOutputStream(); File file = new File(dir + "/" + filename); String mimetype = context.getMimeType(filename); response.setContentType((mimetype != null) ? mimetype : "application/octet-stream"); response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); response.setHeader("Pragma", "private"); response.setHeader("Cache-Control", "private, must-revalidate"); DataInputStream in = new DataInputStream(new FileInputStream(file)); int length; while ((in != null) && ((length = in.read(bbuf)) != -1)) { out.write(bbuf, 0, length); } in.close(); out.flush(); out.close(); FileUtils.cleanDirectory(fileDir); } catch (Exception ex) { System.out.println("ERROR during downloading: " + ex); } System.out.println("DownloadFunction - file ready to be donwloaded"); }
From source file:BSxSB.Controllers.StudentController.java
@RequestMapping(method = RequestMethod.GET) public void doDownload(HttpServletRequest request, HttpServletResponse response) throws IOException { int BUFFER_SIZE = 4096; String filePath = "/WEB-INF/jsp/studentviewgenerated.jsp"; // get absolute path of the application ServletContext context = request.getServletContext(); String appPath = context.getRealPath(""); System.out.println("appPath = " + appPath); // construct the complete absolute path of the file String fullPath = appPath + filePath; File downloadFile = new File(fullPath); FileInputStream inputStream = new FileInputStream(downloadFile); // get MIME type of the file String mimeType = context.getMimeType(fullPath); if (mimeType == null) { // set to binary type if MIME mapping not found mimeType = "application/octet-stream"; }// w w w . j a va2 s . com System.out.println("MIME type: " + mimeType); // set content attributes for the response response.setContentType(mimeType); response.setContentLength((int) downloadFile.length()); // set headers for the response String headerKey = "Content-Disposition"; String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName()); response.setHeader(headerKey, headerValue); // get output stream of the response OutputStream outStream = response.getOutputStream(); byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; // write bytes read from the input stream into the output stream while ((bytesRead = inputStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytesRead); } inputStream.close(); outStream.close(); }
From source file:com.krawler.spring.crm.common.documentController.java
public ModelAndView reloadDocumentLuceneIndex(HttpServletRequest request, HttpServletResponse response) throws ServletException { KwlReturnObject kmsg = null;/*w w w.j a va 2 s .c om*/ StringBuilder msg = new StringBuilder(); int batchSize = 50; int i = 1; int totalIndexed = 0, totalDocs = 0; try { msg.append("LU(ENE Reload started at "); msg.append(new Date()); if (crmDocumentDAOObj.checkReloadDocumentIndex()) { String indexPath = storageHandlerImpl.GetDocIndexPath(); String storePath = storageHandlerImpl.GetDocStorePath(); ServletContext servletContext = getServletContext(); //Delete all old indexed file LuceneSearchObj.clearIndex(indexPath); ArrayList<Document> luceneDocuments = new ArrayList<Document>(); kmsg = crmDocumentDAOObj.getReloadDocumentLuceneIndex(); List<Docs> docsList = kmsg.getEntityList(); totalDocs = kmsg.getRecordTotalCount(); for (Docs doc : docsList) { try { String filePath = storePath + doc.getStorename(); File uploadFile = new File(filePath); FileInputStream fin = null; byte[] b = null; try { fin = new FileInputStream(uploadFile); b = new byte[(int) uploadFile.length()]; fin.read(b); } finally { if (fin != null) { fin.close(); } } String fileType = servletContext.getMimeType(filePath); String contentType = KrawlerApp.getContentType(fileType, filePath, b); int flag1 = 0; if (!StringUtil.isNullOrEmpty(contentType)) { if (contentType.equals("application/vnd.ms-excel") || contentType.equals("application/msword") || contentType.equals("application/vnd.ms-word") || contentType.equals("application/vnd.ms-powerpoint") || contentType.equals("text/plain") || contentType.equals("text/csv") || contentType.equals("text/xml") || contentType.equals("text/css") || contentType.equals("text/html") || contentType.equals("text/cs") || contentType.equals("text/x-javascript") || contentType.equals("File") || contentType.equals("application/pdf") || contentType.equals( "application/vnd.openxmlformats-officedocument.wordprocessingml.document") || contentType.equals( "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) { flag1 = 1; } } if (flag1 == 1) { ArrayList<String> indexNames = new ArrayList<String>(); ArrayList<Object> indexValues = new ArrayList<Object>(); String companyId = doc.getCompany().getCompanyID(); indexNames.add(LuceneSearchConstants.DOCUMENT_FileName); indexValues.add(doc.getDocname()); indexNames.add(LuceneSearchConstants.DOCUMENT_Author); indexValues.add(doc.getUserid().getUserId()); indexNames.add(LuceneSearchConstants.DOCUMENT_DocumentId); indexValues.add(doc.getDocid()); indexNames.add(LuceneSearchConstants.DOCUMENT_CompanyId); indexValues.add(companyId); String plaintext = LuceneSearchObj.parseDocument(filePath, contentType); indexNames.add(LuceneSearchConstants.DOCUMENT_PlainText); indexValues.add(plaintext); indexNames.add(LuceneSearchConstants.DOCUMENT_IndexedText); indexValues.add(plaintext.toLowerCase());//All lower case for comparision Document luceneDoc = LuceneSearchObj.createLuceneDocument(indexValues, indexNames, new ArrayList<String>()); luceneDocuments.add(luceneDoc); totalIndexed++; } } catch (Exception ex) {//Skip file if not found OR any exception } if (i % batchSize == 0) { //Index in batch LuceneSearchObj.writeIndex(luceneDocuments, indexPath); luceneDocuments = new ArrayList<Document>(); } i++; } if (luceneDocuments.size() > 0) { //Index remaining entries LuceneSearchObj.writeIndex(luceneDocuments, indexPath); } crmDocumentDAOObj.resetDocumentIndexFlag();//Make reloadIndex=0 } } catch (Exception e) { logger.warn(e.getMessage(), e); msg.append(", LU(ENE Reload Exception: "); msg.append(e.getMessage()); } msg.append(", Total Docs="); msg.append(totalDocs); msg.append(", completed at"); msg.append(new Date()); msg.append(", Indexed "); msg.append(totalIndexed); msg.append(" documents"); return new ModelAndView("jsonView", "model", msg.toString()); }
From source file:com.sundevils.web.controller.TopController.java
@RequestMapping(value = "/viewfile", method = RequestMethod.GET) public @ResponseBody void downloadFiles(HttpServletRequest request, HttpServletResponse response, HttpSession session, String ssn) { String directorypath = "C:\\AppLogs\\"; File folder = new File(directorypath); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { String filepath = directorypath + "\\" + listOfFiles[i].getName(); ServletContext context = request.getServletContext(); File downloadFile = new File(filepath); FileInputStream inputStream = null; OutputStream outStream = null; try {/*from w w w . j a v a2s. c o m*/ inputStream = new FileInputStream(downloadFile); response.setContentLength((int) downloadFile.length()); response.setContentType(context.getMimeType(filepath)); // response header String headerKey = "Content-Disposition"; String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName()); response.setHeader(headerKey, headerValue); // Write response outStream = response.getOutputStream(); IOUtils.copy(inputStream, outStream); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != inputStream) inputStream.close(); if (null != inputStream) outStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:de.sub.goobi.forms.ProzessverwaltungForm.java
/** * Create excel.//from w w w .j a v a2s . c om */ public void CreateExcel() { FacesContext facesContext = FacesContext.getCurrentInstance(); if (!facesContext.getResponseComplete()) { /* * Vorbereiten der Header-Informationen */ HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); try { ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext(); String contentType = servletContext.getMimeType("export.xls"); response.setContentType(contentType); response.setHeader("Content-Disposition", "attachment;filename=\"export.xls\""); ServletOutputStream out = response.getOutputStream(); HSSFWorkbook wb = (HSSFWorkbook) this.myCurrentTable.getExcelRenderer().getRendering(); wb.write(out); out.flush(); facesContext.responseComplete(); } catch (IOException e) { } } }
From source file:de.sub.goobi.forms.ProzessverwaltungForm.java
/** * Generate result set.//from w ww . jav a 2 s . com */ public void generateResult() { FacesContext facesContext = FacesContext.getCurrentInstance(); if (!facesContext.getResponseComplete()) { /* * Vorbereiten der Header-Informationen */ HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); try { ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext(); String contentType = servletContext.getMimeType("search.xls"); response.setContentType(contentType); response.setHeader("Content-Disposition", "attachment;filename=\"search.xls\""); ServletOutputStream out = response.getOutputStream(); SearchResultGeneration sr = new SearchResultGeneration(this.filter, this.showClosedProcesses, this.showArchivedProjects); HSSFWorkbook wb = sr.getResult(); wb.write(out); out.flush(); facesContext.responseComplete(); } catch (IOException e) { } } }
From source file:de.sub.goobi.forms.ProzessverwaltungForm.java
/** * transforms xml logfile with given xslt and provides download. */// w w w . j ava 2s .co m public void TransformXml() { FacesContext facesContext = FacesContext.getCurrentInstance(); if (!facesContext.getResponseComplete()) { String OutputFileName = "export.xml"; /* * Vorbereiten der Header-Informationen */ HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext(); String contentType = servletContext.getMimeType(OutputFileName); response.setContentType(contentType); response.setHeader("Content-Disposition", "attachment;filename=\"" + OutputFileName + "\""); response.setContentType("text/xml"); try { ServletOutputStream out = response.getOutputStream(); ExportXmlLog export = new ExportXmlLog(); export.startTransformation(out, this.myProzess, this.selectedXslt); out.flush(); } catch (ConfigurationException e) { Helper.setFehlerMeldung("could not create logfile: ", e); } catch (XSLTransformException e) { Helper.setFehlerMeldung("could not create transformation: ", e); } catch (IOException e) { Helper.setFehlerMeldung("could not create transformation: ", e); } facesContext.responseComplete(); } }
From source file:de.sub.goobi.forms.ProzessverwaltungForm.java
/** * Generate result as PDF./*from w ww. j a va 2 s. c o m*/ */ public void generateResultAsPdf() { FacesContext facesContext = FacesContext.getCurrentInstance(); if (!facesContext.getResponseComplete()) { /* * Vorbereiten der Header-Informationen */ HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); try { ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext(); String contentType = servletContext.getMimeType("search.pdf"); response.setContentType(contentType); response.setHeader("Content-Disposition", "attachment;filename=\"search.pdf\""); ServletOutputStream out = response.getOutputStream(); SearchResultGeneration sr = new SearchResultGeneration(this.filter, this.showClosedProcesses, this.showArchivedProjects); HSSFWorkbook wb = sr.getResult(); List<List<HSSFCell>> rowList = new ArrayList<List<HSSFCell>>(); HSSFSheet mySheet = wb.getSheetAt(0); Iterator<Row> rowIter = mySheet.rowIterator(); while (rowIter.hasNext()) { HSSFRow myRow = (HSSFRow) rowIter.next(); Iterator<Cell> cellIter = myRow.cellIterator(); List<HSSFCell> row = new ArrayList<HSSFCell>(); while (cellIter.hasNext()) { HSSFCell myCell = (HSSFCell) cellIter.next(); row.add(myCell); } rowList.add(row); } Document document = new Document(); Rectangle a4quer = new Rectangle(PageSize.A3.getHeight(), PageSize.A3.getWidth()); PdfWriter.getInstance(document, out); document.setPageSize(a4quer); document.open(); if (rowList.size() > 0) { Paragraph p = new Paragraph(rowList.get(0).get(0).toString()); document.add(p); PdfPTable table = new PdfPTable(9); table.setSpacingBefore(20); for (int i = 1; i < rowList.size(); i++) { List<HSSFCell> row = rowList.get(i); for (int j = 0; j < row.size(); j++) { HSSFCell myCell = row.get(j); // TODO aufhbschen und nicht toString() nutzen String stringCellValue = myCell.toString(); table.addCell(stringCellValue); } } document.add(table); } document.close(); out.flush(); facesContext.responseComplete(); } catch (Exception e) { } } }
From source file:org.kitodo.services.data.ProcessService.java
private void writeToOutputStream(FacesContext facesContext, File file, String fileName) throws IOException { HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext(); String contentType = servletContext.getMimeType(fileName); response.setContentType(contentType); response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\""); ServletOutputStream outputStream = response.getOutputStream(); FileInputStream fileInputStream = new FileInputStream(file); byte[] bytes = IOUtils.toByteArray(fileInputStream); fileInputStream.close();// ww w .j av a 2 s . c o m outputStream.write(bytes); outputStream.flush(); facesContext.responseComplete(); }
From source file:com.krawler.esp.servlets.ProfileImageServlet.java
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Get the absolute path of the image ServletContext sc = getServletContext(); String uri = req.getRequestURI(); String servletBase = req.getServletPath(); if (!StringUtil.isNullOrEmpty(req.getParameter("flag"))) { try {// w ww . j av a 2s. c om // TODO: Fix hardcoded url if (!StringUtil.isNullOrEmpty(req.getParameter("trackid"))) { String url = "/remoteapi.jsp?action=100&data={\"iscommit\":true}&trackid=" + req.getParameter("trackid"); RequestDispatcher rd = req.getRequestDispatcher(url); rd.include(req, resp); } String fileName = StorageHandler.GetProfileImgStorePath() + "blankImage.png"; File file = new File(fileName); if (file.exists()) { FileInputStream in = new FileInputStream(file); OutputStream out = resp.getOutputStream(); // Copy the contents of the file to the output stream byte[] buf = new byte[4096]; int count = 0; while ((count = in.read(buf)) >= 0) { out.write(buf, 0, count); } in.close(); out.close(); } } catch (Exception e) { logger.warn(e.getMessage(), e); } } else { boolean Companyflag = (req.getParameter("company") != null) ? true : false; String imagePath = defaultImgPath; String requestedFileName = ""; if (Companyflag) { imagePath = defaultCompanyImgPath; String companyId = null; try { companyId = sessionHandlerImpl.getCompanyid(req); } catch (Exception ee) { logger.warn(ee.getMessage(), ee); } if (StringUtil.isNullOrEmpty(companyId)) { String domain = URLUtil.getDomainName(req); if (!StringUtil.isNullOrEmpty(domain)) { //@@@ // companyId = sessionHandlerImpl.getCompanyid(domain); requestedFileName = "/original_" + companyId + ".png"; } else { requestedFileName = "logo.gif"; } } else { requestedFileName = "/" + companyId + ".png"; } } else { requestedFileName = uri.substring(uri.lastIndexOf(servletBase) + servletBase.length()); } String fileName = null; fileName = StorageHandler.GetProfileImgStorePath() + requestedFileName; // Get the MIME type of the image String mimeType = sc.getMimeType(fileName); if (mimeType == null) { sc.log("Could not get MIME type of " + fileName); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } // Set content type resp.setContentType(mimeType); // Set content size File file = new File(fileName); if (!file.exists()) { if (fileName.contains("_100.")) { file = new File(fileName.replaceAll("_100.", ".")); } if (!file.exists()) { file = new File(sc.getRealPath(imagePath)); } } resp.setContentLength((int) file.length()); // Open the file and output streams FileInputStream in = new FileInputStream(file); OutputStream out = resp.getOutputStream(); // Copy the contents of the file to the output stream byte[] buf = new byte[4096]; int count = 0; while ((count = in.read(buf)) >= 0) { out.write(buf, 0, count); } in.close(); out.close(); } }