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:CourseFileManagementSystem.Upload.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filePath = request.getParameter("fileName"); if (filePath == null || filePath.equals("")) { throw new ServletException("File Name can't be null or empty"); }//w w w . j a v a 2 s . co m File file = new File(filePath); if (!file.exists()) { throw new ServletException("File doesn't exists on server."); } ServletContext ctx = getServletContext(); try (InputStream fis = new FileInputStream(file)) { String mimeType = ctx.getMimeType(file.getAbsolutePath()); response.setContentType(mimeType != null ? mimeType : "application/octet-stream"); response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); try (ServletOutputStream os = response.getOutputStream()) { byte[] bufferData = new byte[1024]; int read = 0; while ((read = fis.read(bufferData)) != -1) { os.write(bufferData, 0, read); } os.flush(); os.close(); fis.close(); } } }
From source file:edu.lternet.pasta.datapackagemanager.dataserver.DataServerServlet.java
/** * Process a data download request using information that was generated * by the Data Package Manager service./* w w w. j a v a 2 s . c o m*/ */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException { String dataToken = request.getParameter("dataToken"); String size = request.getParameter("size"); String objectName = request.getParameter("objectName"); if (dataToken == null || dataToken.isEmpty() || size == null || size.isEmpty() || objectName == null || objectName.isEmpty()) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else { /* * Find out which directory the temporary data files are being * placed in by the Data Package Manager */ PropertiesConfiguration options = ConfigurationListener.getOptions(); String tmpDir = options.getString("datapackagemanager.tmpDir"); if (tmpDir == null || tmpDir.equals("")) { throw new ServletException("datapackagemanager.tmpDir property value was not specified."); } logger.info(String.format("Downloading: dataToken: %s; size: %s; objectName: %s", dataToken, size, objectName)); try { // reads input file from an absolute path String filePath = String.format("%s/%s", tmpDir, dataToken); File downloadFile = new File(filePath); FileInputStream inStream = new FileInputStream(downloadFile); ServletContext context = getServletContext(); // gets MIME type of the file String mimeType = context.getMimeType(filePath); if (mimeType == null) { // set to binary type if MIME mapping not found mimeType = "application/octet-stream"; } logger.debug("MIME type: " + mimeType); // modifies response response.setContentType(mimeType); long length = Long.parseLong(size); if (length <= Integer.MAX_VALUE) { response.setContentLength((int) length); } else { response.addHeader("Content-Length", Long.toString(length)); } // forces download String headerKey = "Content-Disposition"; String headerValue = String.format("attachment; filename=\"%s\"", objectName); response.setHeader(headerKey, headerValue); // obtains response's output stream OutputStream outStream = response.getOutputStream(); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytesRead); } inStream.close(); outStream.close(); /* * Delete the temporary data file after it was downloaded */ try { downloadFile.delete(); } catch (Exception e) { logger.warn(String.format("Error deleting temporary data file: %s", e.getMessage())); } } catch (FileNotFoundException e) { logger.error(e.getMessage()); e.printStackTrace(); response.setStatus(HttpServletResponse.SC_NOT_FOUND); } catch (IOException e) { logger.error(e.getMessage()); e.printStackTrace(); throw new ServletException(e.getMessage()); } } }
From source file:de.sub.goobi.export.download.ExportPdf.java
@Override public boolean startExport(Process myProcess, URI inZielVerzeichnis) throws ReadException, IOException, PreferencesException, TypeNotAllowedForParentException, WriteException { /*//ww w.ja v a 2 s . c o m * Read Document */ Fileformat gdzfile = serviceManager.getProcessService().readMetadataFile(myProcess); URI zielVerzeichnis = prepareUserDirectory(inZielVerzeichnis); this.myPrefs = serviceManager.getRulesetService().getPreferences(myProcess.getRuleset()); /* * first of all write mets-file in images-Folder of process */ URI metsTempFile = fileService.createResource(myProcess.getTitle() + ".xml"); writeMetsFile(myProcess, metsTempFile, gdzfile, true); Helper.setMeldung(null, myProcess.getTitle() + ": ", "mets file created"); Helper.setMeldung(null, myProcess.getTitle() + ": ", "start pdf generation now"); if (logger.isDebugEnabled()) { logger.debug("METS file created: " + metsTempFile); } FacesContext context = FacesContext.getCurrentInstance(); HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest(); String fullpath = req.getRequestURL().toString(); String servletpath = context.getExternalContext().getRequestServletPath(); String myBasisUrl = fullpath.substring(0, fullpath.indexOf(servletpath)); if (!ConfigCore.getBooleanParameter("pdfAsDownload")) { /* * use contentserver api for creation of pdf-file */ CreatePdfFromServletThread pdf = new CreatePdfFromServletThread(); pdf.setMetsURL(metsTempFile.toURL()); pdf.setTargetFolder(zielVerzeichnis); pdf.setInternalServletPath(myBasisUrl); if (logger.isDebugEnabled()) { logger.debug("Taget directory: " + zielVerzeichnis); logger.debug("Using ContentServer2 base URL: " + myBasisUrl); } pdf.initialize(myProcess); pdf.start(); } else { GetMethod method = null; try { /* * define path for mets and pdfs */ URL kitodoContentServerUrl = null; String contentServerUrl = ConfigCore.getParameter("kitodoContentServerUrl"); Integer contentServerTimeOut = ConfigCore.getIntParameter("kitodoContentServerTimeOut", 60000); /* * using mets file */ if (new MetadatenVerifizierung().validate(myProcess) && metsTempFile.toURL() != null) { /* * if no contentserverurl defined use internal * goobiContentServerServlet */ if (contentServerUrl == null || contentServerUrl.length() == 0) { contentServerUrl = myBasisUrl + "/gcs/gcs?action=pdf&metsFile="; } kitodoContentServerUrl = new URL(contentServerUrl + metsTempFile.toURL() + AND_TARGET_FILE_NAME_IS + myProcess.getTitle() + PDF_EXTENSION); /* * mets data does not exist or is invalid */ } else { if (contentServerUrl == null || contentServerUrl.length() == 0) { contentServerUrl = myBasisUrl + "/cs/cs?action=pdf&images="; } FilenameFilter filter = new FileNameMatchesFilter("\\d*\\.tif"); URI imagesDir = serviceManager.getProcessService().getImagesTifDirectory(true, myProcess); ArrayList<URI> meta = fileService.getSubUris(filter, imagesDir); int capacity = contentServerUrl.length() + (meta.size() - 1) + AND_TARGET_FILE_NAME_IS.length() + myProcess.getTitle().length() + PDF_EXTENSION.length(); TreeSet<String> filenames = new TreeSet<>(new MetadatenHelper(null, null)); for (URI data : meta) { String file = data.toURL().toString(); filenames.add(file); capacity += file.length(); } StringBuilder url = new StringBuilder(capacity); url.append(contentServerUrl); boolean subsequent = false; for (String f : filenames) { if (subsequent) { url.append('$'); } else { subsequent = true; } url.append(f); } url.append(AND_TARGET_FILE_NAME_IS); url.append(myProcess.getTitle()); url.append(PDF_EXTENSION); kitodoContentServerUrl = new URL(url.toString()); } /* * get pdf from servlet and forward response to file */ method = new GetMethod(kitodoContentServerUrl.toString()); method.getParams().setParameter("http.socket.timeout", contentServerTimeOut); if (!context.getResponseComplete()) { HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse(); String fileName = myProcess.getTitle() + PDF_EXTENSION; ServletContext servletContext = (ServletContext) context.getExternalContext().getContext(); String contentType = servletContext.getMimeType(fileName); response.setContentType(contentType); response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\""); response.sendRedirect(kitodoContentServerUrl.toString()); context.responseComplete(); } if (metsTempFile.toURL() != null) { File tempMets = new File(metsTempFile.toURL().toString()); tempMets.delete(); } } catch (Exception e) { /* * report Error to User as Error-Log */ String text = "error while pdf creation: " + e.getMessage(); URI uri = zielVerzeichnis.resolve(myProcess.getTitle() + ".PDF-ERROR.log"); try (BufferedWriter output = new BufferedWriter(new OutputStreamWriter(fileService.write(uri)))) { output.write(text); } catch (IOException e1) { logger.error(e1); } return false; } finally { if (method != null) { method.releaseConnection(); } } } return true; }
From source file:org.nuxeo.ecm.platform.thumbnail.factories.ThumbnailDocumentFactory.java
protected Blob getDefaultThumbnail(DocumentModel doc) { if (doc == null) { return null; }/* ww w .j av a 2 s . c o m*/ TypeInfo docType = doc.getAdapter(TypeInfo.class); String iconPath = docType.getBigIcon(); if (iconPath == null) { iconPath = docType.getIcon(); } if (iconPath == null) { return null; } ServletContext servletContext = ServletHelper.getServletContext(); String path = servletContext.getRealPath(iconPath); if (path == null) { return null; } try { File iconFile = new File(path); if (iconFile.exists()) { String mimeType = servletContext.getMimeType(path); if (mimeType == null) { MimetypeRegistry mimetypeRegistry = Framework.getService(MimetypeRegistry.class); mimeType = mimetypeRegistry.getMimetypeFromFilename(iconPath); } return Blobs.createBlob(iconFile, mimeType); } } catch (IOException e) { log.warn(String.format("Could not fetch the thumbnail blob from icon path '%s'", iconPath), e); } return null; }
From source file:cn.zhuqi.mavenssh.web.servlet.ShowPic.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w ww . j a v a2s . c o m * * @param request servlet request * @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 { response.setHeader("Pragma", "No-cache");// ????? response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expire", 0); // ?Application ServletContext application = this.getServletContext(); String sid = request.getParameter("id"); ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(application); // ?spring IOC userService = (IUserService) ctx.getBean(IUserService.class); User user = userService.findById(Integer.valueOf(sid)); String imgFile = user.getPicurl(); response.setContentType(application.getMimeType(imgFile)); FTPClientTemplate ftpClient = new FTPClientTemplate(ip, 21, username, pwd); ServletOutputStream sos = response.getOutputStream(); try { ftpClient.get(attachment + "/" + imgFile, sos); } catch (Exception ex) { } }
From source file:org.dd4t.mvc.controllers.AbstractBinaryController.java
private String getContentType(final Binary binary, final String path, final HttpServletRequest request) { String mimeType = null;// w w w .ja v a 2 s .com ServletContext servletContext = request.getSession().getServletContext(); try { mimeType = binary.getMimeType(); if (mimeType == null) { File binaryFile = new File(path); mimeType = servletContext.getMimeType(binaryFile.getName()); } } catch (Exception e) { LOG.error("Error occurred getting mime-type", e); } if (mimeType == null) { LOG.warn("Could not identify mime type for binary file '" + path + "'"); } return mimeType; }
From source file:com.pronoiahealth.olhie.server.rest.TVServiceImpl.java
/** * @see com.pronoiahealth.olhie.server.rest.TVService#getVideo(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, java.lang.String, * javax.servlet.ServletContext)//w w w .j av a2s.c o m */ @Override @GET @Path("/tv/{uniqueNumb}/{programRef}") // @Produces({"application/pdf", "application/octet-stream", "text/html"}) @Produces({ "application/octet-stream" }) @SecureAccess({ SecurityRoleEnum.ADMIN, SecurityRoleEnum.AUTHOR, SecurityRoleEnum.REGISTERED, SecurityRoleEnum.ANONYMOUS }) public InputStream getVideo(@Context HttpServletRequest request, @Context HttpServletResponse response, @PathParam("programRef") String programRef, @Context ServletContext context) throws ServletException, IOException, FileDownloadException { DataInputStream in = null; try { // Get the file contents File programFile = findFile(programRef); if (programFile == null) { throw new FileDownloadException(String.format("Could not find file for id %s", programRef)); } String fileName = programRef.substring(programRef.lastIndexOf("|")); String mimetype = context.getMimeType(fileName); // Base64 unencode byte[] fileBytes = FileUtils.readFileToByteArray(programFile); response.setContentType((mimetype != null) ? mimetype : "application/octet-stream"); // No image caching response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); // response.setContentLength(fileBytes.length); // response.setHeader("Content-Disposition", "inline; filename=" // + fileName); in = new DataInputStream(new ByteArrayInputStream(fileBytes)); return in; } catch (Exception e) { log.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e); if (e instanceof FileDownloadException) { throw (FileDownloadException) e; } else { throw new FileDownloadException(e); } } finally { if (in != null) { in.close(); } } }
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;//w ww . ja 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.apache.sling.servlets.post.impl.helper.SlingFileUploadHandler.java
/** * Uses the file(s) in the request parameter for creation of new nodes. * if the parent node is a nt:folder a new nt:file is created. otherwise * just a nt:resource. if the <code>name</code> is '*', the filename of * the uploaded file is used.//from w w w . j ava 2s .c o m * * @param parent the parent node * @param prop the assembled property info * @throws RepositoryException if an error occurs */ public void setFile(final Resource parent, final RequestProperty prop, final List<Modification> changes) throws RepositoryException, PersistenceException { for (final RequestParameter value : prop.getValues()) { // ignore if a plain form field or empty if (value.isFormField() || value.getSize() <= 0) { continue; } // get node name String name = prop.getName(); if (name.equals("*")) { name = value.getFileName(); // strip of possible path (some browsers include the entire path) name = name.substring(name.lastIndexOf('/') + 1); name = name.substring(name.lastIndexOf('\\') + 1); } name = Text.escapeIllegalJcrChars(name); // get content type String contentType = value.getContentType(); if (contentType != null) { int idx = contentType.indexOf(';'); if (idx > 0) { contentType = contentType.substring(0, idx); } } if (contentType == null || contentType.equals(MT_APP_OCTET)) { // try to find a better content type ServletContext ctx = this.servletContext; if (ctx != null) { contentType = ctx.getMimeType(value.getFileName()); } if (contentType == null || contentType.equals(MT_APP_OCTET)) { contentType = MT_APP_OCTET; } } final Node node = parent.adaptTo(Node.class); if (node == null) { this.setFile(parent, prop, value, changes, name, contentType); } else { this.setFile(parent, node, prop, value, changes, name, contentType); } } }
From source file:org.sakaiproject.nakamura.files.pool.StreamHelper.java
/** * @param resource//from w w w . j a v a 2s . c om * @param request * @param response * @param servletContext * @throws RepositoryException */ private void setHeaders(Map<String, Object> properties, Resource resource, HttpServletResponse response, String alternativeStream, ServletContext servletContext) { long modifTime = StorageClientUtils.toLong( properties.get(StorageClientUtils.getAltField(Content.LASTMODIFIED_FIELD, alternativeStream))); if (modifTime > 0) { response.setDateHeader(HEADER_LAST_MODIFIED, modifTime); } String contentType = (String) properties .get(StorageClientUtils.getAltField(Content.MIMETYPE_FIELD, alternativeStream)); if (contentType == null && servletContext != null) { final String ct = servletContext.getMimeType(resource.getPath()); if (ct != null) { contentType = ct; } } if (contentType != null) { response.setContentType(contentType); } String encoding = (String) properties .get(StorageClientUtils.getAltField(Content.ENCODING_FIELD, alternativeStream)); if (encoding != null) { response.setCharacterEncoding(encoding); } }