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.arcadian.loginservlet.CourseContentServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getParameter("filename") != null) { String fileName = request.getParameter("filename"); File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileName); System.out.println("File location on server::" + file.getAbsolutePath()); ServletContext ctx = getServletContext(); InputStream fis = new FileInputStream(file); String mimeType = ctx.getMimeType(file.getAbsolutePath()); System.out.println("mime type=" + mimeType); response.setContentType(mimeType != null ? mimeType : "application/octet-stream"); response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); ServletOutputStream os = response.getOutputStream(); byte[] bufferData = new byte[102400]; int read = 0; while ((read = fis.read(bufferData)) != -1) { os.write(bufferData, 0, read); }/*from ww w .j a v a 2 s . com*/ os.flush(); os.close(); fis.close(); System.out.println("File downloaded at client successfully"); } processRequest(request, response); }
From source file:com.arcadian.loginservlet.StudentAssignmentServlet.java
/** * Handles the HTTP//from ww w . ja v a 2 s . c om * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getParameter("filename") != null) { String fileName = request.getParameter("filename"); File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileName); System.out.println("File location on server::" + file.getAbsolutePath()); ServletContext ctx = getServletContext(); InputStream fis = new FileInputStream(file); String mimeType = ctx.getMimeType(file.getAbsolutePath()); System.out.println("mime type=" + mimeType); response.setContentType(mimeType != null ? mimeType : "application/octet-stream"); response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); ServletOutputStream os = response.getOutputStream(); byte[] bufferData = new byte[102400]; int read = 0; while ((read = fis.read(bufferData)) != -1) { os.write(bufferData, 0, read); } os.flush(); os.close(); fis.close(); System.out.println("File downloaded at client successfully"); } processRequest(request, response); }
From source file:UploadDownloadFile.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response);//w w w . j a v a 2s . c o m System.out.println("--> doGet -->"); String filePath; String fileName = request.getParameter("fileName"); if (fileName == null || fileName.equals("")) { throw new ServletException("File Name can't be null or empty"); } final String clientip = request.getRemoteAddr().replace(":", "_"); filePath = "/Users/" + currentuser + "/GlassFish_Server/glassfish/domains/domain1/tmpfiles/Uploaded/" + clientip + "/"; File file = new File(filePath + File.separator + fileName); System.out.println("download file = " + file); if (!file.exists()) { throw new ServletException("File doesn't exists on server."); } System.out.println("File location on server::" + file.getAbsolutePath()); ServletContext ctx = getServletContext(); 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 + "\""); 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(); System.out.println("File downloaded at client successfully"); }
From source file:com.arcadian.loginservlet.LecturesServlet.java
/** * Handles the HTTP//from w w w . ja v a 2 s . co m * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getParameter("filename") != null) { String fileName = request.getParameter("filename"); File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileName); System.out.println("File location on server::" + file.getAbsolutePath()); ServletContext ctx = getServletContext(); InputStream fis = new FileInputStream(file); String mimeType = ctx.getMimeType(file.getAbsolutePath()); System.out.println("mime type=" + mimeType); response.setContentType(mimeType != null ? mimeType : "application/octet-stream"); response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); ServletOutputStream os = response.getOutputStream(); byte[] bufferData = new byte[102400]; int read = 0; while ((read = fis.read(bufferData)) != -1) { os.write(bufferData, 0, read); } os.flush(); os.close(); fis.close(); System.out.println("File downloaded at client successfully"); } processRequest(request, response); }
From source file:de.yaio.services.webshot.server.controller.WebshotProvider.java
public void downloadResultFile(HttpServletRequest request, HttpServletResponse response, File downloadFile) throws IOException { // construct the complete absolute path of the file FileInputStream inputStream = new FileInputStream(downloadFile); // get MIME type of the file ServletContext context = request.getServletContext(); String mimeType = context.getMimeType(downloadFile.getAbsolutePath()); if (mimeType == null) { // set to binary type if MIME mapping not found mimeType = "application/octet-stream"; }/* www. j ava2s. c om*/ if (LOGGER.isDebugEnabled()) { LOGGER.debug("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:edu.csudh.goTorosBank.WithdrawServlet.java
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //File blueCheck = new File("blank-blue-check.jpg"); File blueCheck = new File(request.getParameter("filename")); String pathToWeb = getServletContext().getRealPath("/" + blueCheck); ServletContext cntx = request.getServletContext(); String mime = cntx.getMimeType(pathToWeb); response.setContentType(mime);//w w w . java2 s .co m try { File file = new File(pathToWeb); response.setContentLength((int) file.length()); FileInputStream in = new FileInputStream(file); OutputStream out = response.getOutputStream(); // Copy the contents of the file to the output stream byte[] buf = new byte[1024]; int count; while ((count = in.read(buf)) >= 0) { out.write(buf, 0, count); } out.close(); in.close(); response.setHeader("Content-Transfer-Encoding", "binary"); response.setHeader("Content-Disposition", "attachment; filename=\"" + blueCheck.getName() + "\"");//fileName; } catch (Exception e) { response.getWriter().write(e.getMessage()); } }
From source file:wicket.protocol.http.request.WebExternalResourceRequestTarget.java
/** * Respond by trying to delegate getting the resource from the * {@link ServletContext} object and stream that to the client. If such a * resource is not found, a warning will be logged, and a 404 will be * issued.//from www.java 2 s. com * * @see wicket.IRequestTarget#respond(wicket.RequestCycle) */ public void respond(RequestCycle requestCycle) { try { WebResponse webResponse = ((WebRequestCycle) requestCycle).getWebResponse(); final ServletContext context = ((WebApplication) requestCycle.getApplication()).getServletContext(); // Set content type webResponse.setContentType(context.getMimeType(url)); final InputStream in = context.getResourceAsStream(url); if (in != null) { try { // Copy resource input stream to servlet output stream Streams.copy(in, webResponse.getHttpServletResponse().getOutputStream()); } finally { // NOTE: We only close the InputStream. The servlet // container should close the output stream. in.close(); } } else { log.warn("the resource requested by request " + requestCycle.getRequest() + " was not found"); HttpServletResponse httpServletResponse = webResponse.getHttpServletResponse(); httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } } catch (IOException e) { throw new WicketRuntimeException("Cannot load static content for request " + requestCycle.getRequest(), e); } }
From source file:com.francelabs.datafari.servlets.URL.java
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response)//from w ww. ja va 2 s . c om */ @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); final String protocol = request.getScheme() + ":"; final Map<String, String[]> requestMap = new HashMap<>(); requestMap.putAll(request.getParameterMap()); final IndexerQuery query = IndexerServerManager.createQuery(); query.addParams(requestMap); // get the AD domain String domain = ""; HashMap<String, String> h; try { h = RealmLdapConfiguration.getConfig(request); if (h.get(RealmLdapConfiguration.ATTR_CONNECTION_NAME) != null) { final String userBase = h.get(RealmLdapConfiguration.ATTR_DOMAIN_NAME).toLowerCase(); final String[] parts = userBase.split(","); domain = ""; for (int i = 0; i < parts.length; i++) { if (parts[i].indexOf("dc=") != -1) { // Check if the current // part is a domain // component if (!domain.isEmpty()) { domain += "."; } domain += parts[i].substring(parts[i].indexOf('=') + 1); } } } // Add authentication if (request.getUserPrincipal() != null) { String AuthenticatedUserName = request.getUserPrincipal().getName().replaceAll("[^\\\\]*\\\\", ""); if (AuthenticatedUserName.contains("@")) { AuthenticatedUserName = AuthenticatedUserName.substring(0, AuthenticatedUserName.indexOf("@")); } if (!domain.equals("")) { AuthenticatedUserName += "@" + domain; } query.setParam("AuthenticatedUserName", AuthenticatedUserName); } } catch (final Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } StatsPusher.pushDocument(query, protocol); // String surl = URLDecoder.decode(request.getParameter("url"), // "ISO-8859-1"); final String surl = request.getParameter("url"); if (ScriptConfiguration.getProperty("ALLOWLOCALFILEREADING").equals("true") && !surl.startsWith("file://///")) { final int BUFSIZE = 4096; String fileName = null; /** * File Display/Download --> <!-- Written by Rick Garcia --> */ if (SystemUtils.IS_OS_LINUX) { // try to open the file locally final String fileNameA[] = surl.split(":"); fileName = URLDecoder.decode(fileNameA[1], "UTF-8"); } else if (SystemUtils.IS_OS_WINDOWS) { fileName = URLDecoder.decode(surl, "UTF-8").replaceFirst("file:/", ""); } final File file = new File(fileName); int length = 0; final ServletOutputStream outStream = response.getOutputStream(); final ServletContext context = getServletConfig().getServletContext(); String mimetype = context.getMimeType(fileName); // sets response content type if (mimetype == null) { mimetype = "application/octet-stream"; } response.setContentType(mimetype); response.setContentLength((int) file.length()); // sets HTTP header response.setHeader("Content-Disposition", "inline; fileName=\"" + fileName + "\""); final byte[] byteBuffer = new byte[BUFSIZE]; final DataInputStream in = new DataInputStream(new FileInputStream(file)); // reads the file's bytes and writes them to the response stream while (in != null && (length = in.read(byteBuffer)) != -1) { outStream.write(byteBuffer, 0, length); } in.close(); outStream.close(); } else { final RequestDispatcher rd = request.getRequestDispatcher(redirectUrl); rd.forward(request, response); } }
From source file:org.kuali.student.core.document.ui.server.upload.UploadServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DocumentInfo info = null;//from ww w. j a v a 2s.c o m try { info = documentService.getDocument(request.getParameter("docId"), ContextUtils.getContextInfo()); } catch (Exception e) { LOG.error("Exception occurred", e); } if (info != null && info.getDocumentBinary() != null && info.getDocumentBinary().getBinary() != null && !(info.getDocumentBinary().getBinary().isEmpty())) { ServletOutputStream op = response.getOutputStream(); try { byte[] fileBytes = Base64.decodeBase64(info.getDocumentBinary().getBinary().getBytes()); int length = fileBytes.length; ServletContext context = getServletConfig().getServletContext(); String mimetype = context.getMimeType(info.getFileName()); response.setContentType((mimetype != null) ? mimetype : "application/octet-stream"); response.setContentLength(length); response.setHeader("Content-Disposition", "attachment; filename=\"" + info.getFileName() + "\""); // // Stream to the requester. // op.write(fileBytes, 0, length); } catch (Exception e) { LOG.error("Exception occurred", e); } finally { op.flush(); op.close(); } } else { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println( "Sorry, the file could not be retrieved. It may not exist, or the server could not be contacted."); } }
From source file:edu.lternet.pasta.datapackagemanager.dataserver.DataServerServlet.java
/** * Process a data download HEAD request using information that was generated * by the Data Package Manager service./*from w ww. j a v a 2 s. c o m*/ */ protected void doHead(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."); } try { // reads input file from an absolute path String filePath = String.format("%s/%s", tmpDir, dataToken); File downloadFile = new File(filePath); if (!downloadFile.exists()) { String message = String.format("File not found: %s", filePath); throw new FileNotFoundException(message); } 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"; } // 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); } catch (FileNotFoundException e) { logger.error(e.getMessage()); e.printStackTrace(); response.setStatus(HttpServletResponse.SC_NOT_FOUND); } } }