Example usage for javax.servlet ServletContext getMimeType

List of usage examples for javax.servlet ServletContext getMimeType

Introduction

In this page you can find the example usage for javax.servlet ServletContext getMimeType.

Prototype

public String getMimeType(String file);

Source Link

Document

Returns the MIME type of the specified file, or null if the MIME type is not known.

Usage

From source file:org.apache.wookie.WidgetAdminServlet.java

private void doDownload(HttpServletRequest req, HttpServletResponse resp, File f, String original_filename)
        throws IOException {
    int BUFSIZE = 1024;

    // File f = new File(filename);
    int length = 0;
    ServletOutputStream op = resp.getOutputStream();
    ServletContext context = getServletConfig().getServletContext();
    String mimetype = context.getMimeType(f.getAbsolutePath());

    ///*from w  w w  .  j av  a 2 s . co  m*/
    // Set the response and go!
    //
    //
    resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
    resp.setContentLength((int) f.length());
    resp.setHeader("Content-Disposition", "attachment; filename=\"" + original_filename + "\"");

    //
    // Stream to the requester.
    //
    byte[] bbuf = new byte[BUFSIZE];
    DataInputStream in = new DataInputStream(new FileInputStream(f));

    while ((in != null) && ((length = in.read(bbuf)) != -1)) {
        op.write(bbuf, 0, length);
    }

    in.close();
    op.flush();
    op.close();
}

From source file:de.sub.goobi.metadaten.FileManipulation.java

/**
 * Download file.//ww w .  j a  v a2 s.  com
 */
public void downloadFile() {
    URI downloadFile = null;

    int imageOrder = Integer.parseInt(imageSelection);
    DocStruct page = metadataBean.getDigitalDocument().getPhysicalDocStruct().getAllChildren().get(imageOrder);
    String imagename = page.getImageName();
    String filenamePrefix = imagename.substring(0, imagename.lastIndexOf("."));
    URI processSubTypeURI = serviceManager.getFileService().getProcessSubTypeURI(metadataBean.getProcess(),
            ProcessSubType.IMAGE, currentFolder);
    ArrayList<URI> filesInFolder = fileService.getSubUris(processSubTypeURI);
    for (URI currentFile : filesInFolder) {
        String currentFileName = fileService.getFileName(currentFile);
        String currentFileNamePrefix = currentFileName.substring(0, currentFileName.lastIndexOf("."));
        if (filenamePrefix.equals(currentFileNamePrefix)) {
            downloadFile = currentFile;
            break;
        }
    }

    if (downloadFile == null || !fileService.fileExist(downloadFile)) {
        List<String> paramList = new ArrayList<>();
        // paramList.add(metadataBean.getMyProzess().getTitel());
        paramList.add(filenamePrefix);
        paramList.add(currentFolder);
        Helper.setFehlerMeldung(Helper.getTranslation("MetsEditorMissingFile", paramList));
        return;
    }

    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (!facesContext.getResponseComplete()) {
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        InputStream in = null;
        ServletOutputStream out = null;
        try {
            String fileName = fileService.getFileName(downloadFile);
            ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
            String contentType = servletContext.getMimeType(fileName);
            response.setContentType(contentType);
            response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
            in = fileService.read(downloadFile);
            out = response.getOutputStream();
            byte[] buffer = new byte[4096];
            int length;
            while ((length = in.read(buffer)) != -1) {
                out.write(buffer, 0, length);
            }
            out.flush();
        } catch (IOException e) {
            logger.error("IOException while exporting run note", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
        }

        facesContext.responseComplete();
    }

}

From source file:ro.fils.angularspring.controller.ProjectsController.java

@RequestMapping(method = RequestMethod.GET, value = "/downloadXSLT")
public void downloadXSLT(HttpServletRequest request, HttpServletResponse response)
        throws FileNotFoundException, IOException, BadElementException {
    ServletContext context = request.getServletContext();
    String appPath = context.getRealPath("");
    String fullPath = appPath + "Projects.xsl";
    PDFCreator creator = new PDFCreator();
    creator.saveAsXSLT(XSLTFile.xsltString, fullPath);
    System.out.println("appPath = " + appPath);

    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";
    }//from  w ww.ja v  a  2  s .  c  o m
    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.wdeanmedical.portal.service.AppService.java

public void getFile(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext,
        String filePath, String fileName) throws Exception {
    String mime = servletContext.getMimeType(fileName);
    if (mime == null) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;/*from   w  w  w.j a  v a 2s  .  c  o  m*/
    }
    response.setContentType(mime);
    File file = new File(filePath + fileName);
    response.setContentLength((int) file.length());
    FileInputStream in = new FileInputStream(file);
    OutputStream out = response.getOutputStream();
    byte[] buf = new byte[1024];
    int count = 0;
    while ((count = in.read(buf)) >= 0) {
        out.write(buf, 0, count);
    }
    out.close();
    in.close();
}

From source file:controller.ClientController.java

@RequestMapping(value = "/facture", method = RequestMethod.POST)
//public @ResponseBody
String factureAction(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model)
        throws IOException {

    Client cli = (Client) session.getAttribute("UserConnected");
    int idvideo = Integer.parseInt(request.getParameter("idvideo"));
    Facture facture = new Facture();
    facture.Consulter(cli, vidBDD.VideoPrec(idvideo).get(0), request.getServletContext());
    //if(request.getSession()){
    //int test = Integer.parseInt(request.getParameter("select")) ;
    //request.setAttribute("Modify", this.modif.modifcontrat(id));
    //}//from ww  w  . java 2 s  . c  om
    //session.setAttribute("Modify", this.modif.modifcontrat(id));
    int BUFFER_SIZE = 4096;
    ServletContext context = request.getServletContext();
    String appPath = context.getRealPath("");
    System.out.println(appPath);

    try {

        File downloadFile = new File(appPath + "\\resources\\reports\\facture.pdf");
        FileInputStream fis = new FileInputStream(downloadFile);
        // get MIME type of the file
        String mimeType = context.getMimeType(appPath + "\\resources\\reports\\facture.pdf");
        if (mimeType == null) {
            // set to binary type if MIME mapping not found
            mimeType = "application/octet-stream";
        }
        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 = fis.read(buffer)) != -1) {
            outStream.write(buffer, 0, bytesRead);
        }

        fis.close();
        outStream.close();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return "/";
}

From source file:controller.ClientController.java

@RequestMapping(value = "/devis", method = RequestMethod.POST)
//public @ResponseBody
String devisAction(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model)
        throws IOException {

    Client cli = (Client) session.getAttribute("UserConnected");
    int idvideo = Integer.parseInt(request.getParameter("idvideo"));
    Devis devis = new Devis();
    devis.Consulter(cli, vidBDD.VideoPrec(idvideo).get(0), request.getServletContext());
    //if(request.getSession()){
    //int test = Integer.parseInt(request.getParameter("select")) ;
    //request.setAttribute("Modify", this.modif.modifcontrat(id));
    //}/* w  w  w.  j  a va2 s . c  om*/
    //session.setAttribute("Modify", this.modif.modifcontrat(id));
    // get your file as InputStream

    /**
     * Size of a byte buffer to read/write file
     */
    int BUFFER_SIZE = 4096;
    ServletContext context = request.getServletContext();
    String appPath = context.getRealPath("");
    System.out.println(appPath);

    try {

        File downloadFile = new File(appPath + "\\resources\\reports\\devis.pdf");
        FileInputStream fis = new FileInputStream(downloadFile);
        // get MIME type of the file
        String mimeType = context.getMimeType(appPath + "\\resources\\reports\\devis.pdf");
        if (mimeType == null) {
            // set to binary type if MIME mapping not found
            mimeType = "application/octet-stream";
        }
        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 = fis.read(buffer)) != -1) {
            outStream.write(buffer, 0, bytesRead);
        }

        fis.close();
        outStream.close();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return "/";
}

From source file:ro.fils.angularspring.controller.ProjectsController.java

@RequestMapping(method = RequestMethod.GET, value = "/downloadXML")
public void downloadXML(HttpServletRequest request, HttpServletResponse response)
        throws FileNotFoundException, IOException, BadElementException {
    ServletContext context = request.getServletContext();
    String appPath = context.getRealPath("");
    String fullPath = appPath + "Projects.xml";
    PDFCreator creator = new PDFCreator();
    creator.saveAsXML(projectsDocumentRepository.findOne(ConnectionUtils.PROJECTS_COLLECTION).getContent(),
            fullPath);/*from   www.jav  a  2  s.  com*/
    System.out.println("appPath = " + appPath);

    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";
    }
    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:net.java.dev.weblets.impl.faces.WebletsPhaseListener.java

protected void doBeforePhase(PhaseEvent event) {
    FacesContext context = FacesContext.getCurrentInstance();
    ExternalContext external = context.getExternalContext();
    // test stuff remove me once verified
    /*//  ww  w .ja  va 2 s . c o m
       * req = utils.getRequestFromPath(external.getRequest(), "/weblets-demo/faces/weblets/demo$1.0/welcome.js");
       *
       * ServletContext ctx = (ServletContext) external.getContext(); String mime = ctx.getMimeType("/faces/weblets/demo$1.0/welcome.js");
       *
       * InputStream strm = utils.getResourceAsStream(req, mime); BufferedReader istrm = new BufferedReader(new InputStreamReader(strm)); try { String line =
       * ""; while ((line = istrm.readLine() ) != null) { System.out.println(line); } istrm.close();
       *
       * } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. }
       *
       *
       * req = utils.getRequestFromPath(external.getRequest(), "/faces/weblets/demo$1.0/welcome.js"); utils.getResourceAsStream(req, mime);
       *
       * req = utils.getRequestFromPath(external.getRequest(), "http://localhost:8080/weblets-demo/faces/weblets/demo$1.0/welcome.js");
       * utils.getResourceAsStream(req, mime);
       *
       * req = utils.getRequestFromPath(external.getRequest(), "/xxx/aa/demo$1.0/welcome.js"); utils.getResourceAsStream(req, mime);
       *
       *
       * req = utils.getRequestFromPath(external.getRequest(), "/xxx/aa/demo$1.0/booga.js"); Object strobj = utils.getResourceAsStream(req, mime);
       */
    WebletContainerImpl container = (WebletContainerImpl) WebletContainer.getInstance();
    String pathInfo = external.getRequestServletPath();
    if (pathInfo != null && external.getRequestPathInfo() != null)
        pathInfo += external.getRequestPathInfo();
    if (pathInfo == null && event.getPhaseId() == PhaseId.RESTORE_VIEW) {
        // we are in a portlet environment here, since we do not get an external path info
        // we skip this phase and renter after the restore view
        event.getFacesContext().getExternalContext().getRequestMap().put(WEBLETS_PHASE_LISTENER_ENTERED,
                Boolean.FALSE);
        return;
    }
    // special portlet treatment here
    // we move to later phases here to the apply request values
    // to become portlet compatible, unfortunately
    // we lose a little bit of performance then
    // but the determination of the pathInfo over
    // the view id is more neutral than over
    // the request servlet which is rundered null
    // in some portlet environments
    if (pathInfo == null)
        pathInfo = context.getViewRoot().getViewId();
    Matcher matcher = null;
    try {
        matcher = container.getPattern().matcher(pathInfo);
    } catch (NullPointerException ex) {
        Log log = LogFactory.getLog(this.getClass());
        log.error(
                "An error has occurred no pattern or matcher has been detected, this is probably a sign that the weblets context listener has not been started. please add following lines to your web.xml \n"
                        + " <listener>\n"
                        + "       <listener-class>net.java.dev.weblets.WebletsContextListener</listener-class>\n"
                        + " </listener>");
        log.error("Details of the original Error:" + ex.toString());
        return;
    }
    if (matcher.matches()) {
        Map requestHeaders = external.getRequestHeaderMap();
        String contextPath = external.getRequestContextPath();
        String requestURI = matcher.group(1);
        String ifModifiedHeader = (String) requestHeaders.get("If-Modified-Since");
        long ifModifiedSince = -1L;
        if (ifModifiedHeader != null) {
            try {
                DateFormat rfc1123 = new HttpDateFormat();
                Date parsed = rfc1123.parse(ifModifiedHeader);
                ifModifiedSince = parsed.getTime();
            } catch (ParseException e) {
                throw new FacesException(e);
            }
        }
        try {
            String[] parsed = container.parseWebletRequest(contextPath, requestURI, ifModifiedSince);
            if (parsed != null) {
                ServletContext servletContext = (ServletContext) external.getContext();
                ServletRequest httpRequest = (ServletRequest) external.getRequest();
                ServletResponse httpResponse = (ServletResponse) external.getResponse();
                String webletName = parsed[0];
                String webletPath = parsed[1];
                String webletPathInfo = parsed[2];
                WebletRequest webRequest = new WebletRequestImpl(webletName, webletPath, contextPath,
                        webletPathInfo, ifModifiedSince, httpRequest);
                String contentName = webRequest.getPathInfo();
                String contentTypeDefault = servletContext.getMimeType(contentName);
                WebletResponse webResponse = new WebletResponseImpl(contentTypeDefault, httpResponse);
                container.service(webRequest, webResponse);
                context.responseComplete();
            }
        } catch (IOException e) {
            throw new FacesException(e);
        }
    }
}

From source file:biz.taoconsulting.dominodav.resource.DAVResourceFile.java

/**
 * (non-Javadoc)/*from   ww w  .  j a va2  s  .  c  o m*/
 * 
 * @see biz.taoconsulting.dominodav.resource.DAVAbstractResource#getMimeType(javax.servlet.ServletContext)
 */
public String getMimeType(ServletContext context) {
    // TODO: can we keep the mimetype from Domino
    String curName = this.file.getAbsolutePath();
    String curNameLower = curName.toLowerCase();
    String returnType = "application/octet-stream"; // Default value if
    // things go wrong
    try {
        // Hack to make sure xslt and xsl go as text/xml
        // To avoid funny errors on machines that don't know that file
        // type to serve
        if (curNameLower.endsWith(".xsl") || curNameLower.endsWith(".xslt") || curNameLower.endsWith(".xml")) {
            returnType = "text/xml";
        } else {
            if (context != null) {
                returnType = context.getMimeType(curName);
            } else {
                returnType = "application/octet-stream";
            }
        }
        LOGGER.debug("File " + curName + " is of type \"" + returnType + "\"");
    } catch (Exception e) {
        LOGGER.error("Mime Type retrieval failed", e);
    }

    return returnType;
}

From source file:ro.fils.angularspring.controller.ProjectsController.java

@RequestMapping(method = RequestMethod.GET, value = "/downloadPDF")
public void downloadPDF(HttpServletRequest request, HttpServletResponse response)
        throws FileNotFoundException, IOException, BadElementException {
    ServletContext context = request.getServletContext();
    String appPath = context.getRealPath("");
    String fullPath = appPath + "Projects.pdf";
    PDFCreator creator = new PDFCreator();
    projectConverter = new ProjectConverter();
    creator.saveAsPDF(/*  w  w  w.  j  a v a  2  s  .  co m*/
            projectConverter.readAll(
                    projectsDocumentRepository.findOne(ConnectionUtils.PROJECTS_COLLECTION).getContent()),
            fullPath);
    System.out.println("appPath = " + appPath);

    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";
    }
    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();

}