Example usage for javax.activation FileTypeMap getContentType

List of usage examples for javax.activation FileTypeMap getContentType

Introduction

In this page you can find the example usage for javax.activation FileTypeMap getContentType.

Prototype

abstract public String getContentType(String filename);

Source Link

Document

Return the type of the file passed in.

Usage

From source file:MSBodyPart.java

/**
 * Process the "begin" line to extract the filename,
 * and from it determine the Content-Type.
 *///from   ww  w .j ava2 s . c om
private void processBegin() {
    InputStream in = getContentStream();
    try {
        BufferedReader r = new BufferedReader(new InputStreamReader(in));
        String begin = r.readLine();
        // format is "begin 666 filename.txt"
        if (begin != null && begin.regionMatches(true, 0, "begin ", 0, 6)) {
            int i = begin.indexOf(' ', 6);
            if (i > 0) {
                filename = begin.substring(i + 1);
                FileTypeMap map = FileTypeMap.getDefaultFileTypeMap();
                type = map.getContentType(filename);
                if (type == null)
                    type = "application/octet-stream";
            }
        }
    } catch (IOException ex) {
        // ignore
    } finally {
        try {
            in.close();
        } catch (IOException ex) {
            // ignore it
        }
        if (filename == UNKNOWN)
            filename = null;
        if (type == UNKNOWN || type == null)
            type = "text/plain";
    }
}

From source file:com.krawler.formbuilder.servlet.FileDownloadServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from  www  . ja v  a  2 s  .  com*/

        WebApplicationContext applicationContext = WebApplicationContextUtils
                .getWebApplicationContext(getServletContext());
        ModuleBuilderService moduleBuilderService = (ModuleBuilderService) applicationContext
                .getBean("moduleBuilderService");
        mb_docs docsObj = (mb_docs) moduleBuilderService.getMBDocById(mb_docs.class,
                request.getParameter("docid"));
        String src = PropsValues.STORE_PATH + request.getParameter("url");

        File fp = new File(src);
        byte[] buff = new byte[(int) fp.length()];
        FileInputStream fis = new FileInputStream(fp);
        int read = fis.read(buff);
        javax.activation.FileTypeMap mmap = new javax.activation.MimetypesFileTypeMap();
        String fileName = docsObj.getDocname();
        response.setContentType(mmap.getContentType(fp));
        response.setContentLength((int) fp.length());
        String contentDisposition = "";
        if (request.getParameter("attachment") != null) {
            contentDisposition = "attachment";
        } else {
            contentDisposition = "inline";
        }

        response.setHeader("Content-Disposition", contentDisposition + "; filename=\"" + fileName + "\";");
        response.getOutputStream().write(buff, 0, buff.length);
        response.getOutputStream().flush();
    } catch (Exception ex) {
        logger.warn("Unable To Download File :" + ex.toString(), ex);
    }

}

From source file:com.krawler.spring.crm.caseModule.CrmCustomerCaseController.java

public ModelAndView downloadFile(HttpServletRequest request, HttpServletResponse response) {
    Map model = new HashMap();
    String responseMessage = "";

    try {//from   w ww  .  j av  a 2s. co m
        if ((String) request.getSession().getAttribute(Constants.SESSION_CUSTOMER_ID) != null) {
            String caseId = request.getParameter("caseid");
            String docid = request.getParameter("docid");
            List<Docs> dl = crmCustomerCaseService.getDocument(docid);
            Docs doc = dl.get(0);
            String src = storageHandlerImpl.GetDocStorePath();
            src = src + "/" + doc.getStorename();//ht.get("userid").toString()
            File fp = new File(src);
            byte[] buff = new byte[(int) fp.length()];
            FileInputStream fis = new FileInputStream(fp);
            int read = fis.read(buff);
            javax.activation.FileTypeMap mmap = new javax.activation.MimetypesFileTypeMap();
            response.setContentType(mmap.getContentType(src));
            response.setContentLength((int) fp.length());
            response.setHeader("Content-Disposition",
                    request.getParameter("dtype") + "; filename=\"" + doc.getDocname() + "\";");
            response.getOutputStream().write(buff);
            response.getOutputStream().flush();
            response.getOutputStream().close();

            request.setAttribute("casedetails", "true");
            request.setAttribute("caseid", caseId);

        } else {
            request.setAttribute("logout", "true");
        }
        responseMessage = "usercases/redirect";
    }

    catch (Exception e) {
        logger.warn(e.getMessage(), e);

    }
    return new ModelAndView(responseMessage, "model", model);
}

From source file:com.krawler.spring.hrms.common.hrmsDocumentController.java

public ModelAndView downloadDocuments(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    JSONObject jobj = new JSONObject();
    JSONObject myjobj = new JSONObject();
    KwlReturnObject kmsg = null;// ww  w  . j  a va2  s.  co  m
    String details = "";
    String auditAction = "";
    try {
        String url = request.getParameter("url");
        url = StringUtil.checkForNull(url);
        String applicant = request.getParameter("applicant");
        applicant = StringUtil.checkForNull(applicant);
        Hashtable ht;
        if (applicant.equalsIgnoreCase("applicant")) {
            kmsg = hrmsExtApplDocsDAOObj.downloadDocument(url);
            ht = getExtDocumentDownloadHash(kmsg.getEntityList());
        } else {
            kmsg = documentDAOObj.downloadDocument(url);
            ht = getDocumentDownloadHash(kmsg.getEntityList());
        }

        String src = storageHandlerImplObj.GetDocStorePath();
        //            String src = "/home/trainee/";
        if (request.getParameter("mailattch") != null) {
            src = src + ht.get("svnname");
        } else {
            src = src + ht.get("userid").toString() + "/" + ht.get("svnname");
        }

        File fp = new File(src);
        byte[] buff = new byte[(int) fp.length()];
        FileInputStream fis = new FileInputStream(fp);
        int read = fis.read(buff);
        javax.activation.FileTypeMap mmap = new javax.activation.MimetypesFileTypeMap();
        response.setContentType(mmap.getContentType(src));
        response.setContentLength((int) fp.length());
        response.setHeader("Content-Disposition",
                request.getParameter("dtype") + "; filename=\"" + ht.get("Name") + "\";");
        response.getOutputStream().write(buff);
        response.getOutputStream().flush();
        response.getOutputStream().close();
        String map = ht.get("relatedto").toString();
        String refid = ht.get("recid").toString();

        myjobj.put("success", true);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    return new ModelAndView("jsonView", "model", myjobj.toString());
}

From source file:com.sun.syndication.propono.atom.server.impl.FileBasedCollection.java

private void updateMediaEntryAppLinks(Entry entry, String fileName, boolean singleEntry) {

    // TODO: figure out why PNG is missing from Java MIME types
    FileTypeMap map = FileTypeMap.getDefaultFileTypeMap();
    if (map instanceof MimetypesFileTypeMap) {
        try {/*from   w  w  w . ja v a 2s .co m*/
            ((MimetypesFileTypeMap) map).addMimeTypes("image/png png PNG");
        } catch (Exception ignored) {
        }
    }
    String contentType = map.getContentType(fileName);

    entry.setId(getEntryMediaViewURI(fileName));
    entry.setTitle(fileName);
    entry.setUpdated(new Date());

    List otherlinks = new ArrayList();
    entry.setOtherLinks(otherlinks);

    Link editlink = new Link();
    editlink.setRel("edit");
    editlink.setHref(getEntryEditURI(fileName, relativeURIs, singleEntry));
    otherlinks.add(editlink);

    Link editMedialink = new Link();
    editMedialink.setRel("edit-media");
    editMedialink.setHref(getEntryMediaEditURI(fileName, relativeURIs, singleEntry));
    otherlinks.add(editMedialink);

    Content content = (Content) entry.getContents().get(0);
    content.setSrc(getEntryMediaViewURI(fileName));
    List contents = new ArrayList();
    contents.add(content);
    entry.setContents(contents);
}

From source file:com.krawler.spring.crm.common.documentController.java

public ModelAndView downloadAttachment(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    JSONObject myjobj = new JSONObject();
    KwlReturnObject kmsg = null;/*from  w ww .j av  a 2s  .  co  m*/
    try {
        String url = request.getParameter("url");
        url = StringUtil.checkForNull(url);
        kmsg = crmDocumentDAOObj.downloadDocument(url);
        Hashtable ht = getDocumentDownloadHash(kmsg.getEntityList());
        String src = storageHandlerImplObj.GetDocStorePath();
        if (request.getParameter("mailattch") != null) {
            if (Boolean.parseBoolean(request.getParameter("mailattch"))) {
                src = storageHandlerImplObj.GetEmailUploadFilePath();
                src = src + url;
            } else
                src = src + ht.get("svnname");
        } else {
            src = src + ht.get("userid").toString() + "/" + ht.get("svnname");
        }

        File fp = new File(src);
        byte[] buff = new byte[(int) fp.length()];
        FileInputStream fis = new FileInputStream(fp);
        int read = fis.read(buff);
        javax.activation.FileTypeMap mmap = new javax.activation.MimetypesFileTypeMap();
        response.setContentType(mmap.getContentType(src));
        response.setContentLength((int) fp.length());
        response.setHeader("Content-Disposition",
                request.getParameter("dtype") + "; filename=\"" + request.getParameter("fname") + "\";");
        response.getOutputStream().write(buff);
        response.getOutputStream().flush();
        response.getOutputStream().close();
        myjobj.put("success", true);
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
    }
    return new ModelAndView("jsonView", "model", myjobj.toString());
}

From source file:com.krawler.spring.crm.common.documentController.java

public ModelAndView downloadDocuments(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    JSONObject jobj = new JSONObject();
    JSONObject myjobj = new JSONObject();
    KwlReturnObject kmsg = null;/*ww  w . j a v  a 2  s .c o m*/
    String details = "";
    String auditAction = "";
    try {
        String url = request.getParameter("url");
        url = StringUtil.checkForNull(url);
        kmsg = crmDocumentDAOObj.downloadDocument(url);
        Hashtable ht = getDocumentDownloadHash(kmsg.getEntityList());
        String src = storageHandlerImplObj.GetDocStorePath();
        //            String src = "/home/trainee/";
        if (request.getParameter("mailattch") != null) {
            src = src + ht.get("svnname");
        } else {
            src = src + ht.get("userid").toString() + "/" + ht.get("svnname");
        }

        File fp = new File(src);
        byte[] buff = new byte[(int) fp.length()];
        FileInputStream fis = new FileInputStream(fp);
        int read = fis.read(buff);
        javax.activation.FileTypeMap mmap = new javax.activation.MimetypesFileTypeMap();
        response.setContentType(mmap.getContentType(src));
        response.setContentLength((int) fp.length());
        response.setHeader("Content-Disposition",
                request.getParameter("dtype") + "; filename=\"" + ht.get("Name") + "\";");
        response.getOutputStream().write(buff);
        response.getOutputStream().flush();
        response.getOutputStream().close();
        String map = ht.get("relatedto").toString();
        String refid = ht.get("recid").toString();

        if (map.equals("0")) {
            CrmCampaign c = (CrmCampaign) hibernateTemplate.get(CrmCampaign.class, refid);
            details = " Campaign - ";
            details += StringUtil.isNullOrEmpty(c.getCampaignname()) ? "" : c.getCampaignname();
            auditAction = AuditAction.CAMPAIGN_DOC_DOWNLOAD;
        } else if (map.equals("1")) {
            CrmLead l = (CrmLead) hibernateTemplate.get(CrmLead.class, refid);
            details = " Lead - ";
            details += StringUtil.isNullOrEmpty(l.getFirstname()) ? "" : l.getFirstname() + " ";
            details += StringUtil.isNullOrEmpty(l.getLastname()) ? "" : l.getLastname();
            auditAction = AuditAction.LEAD_DOC_DOWNLOAD;
        } else if (map.equals("2")) {
            CrmContact c = (CrmContact) hibernateTemplate.get(CrmContact.class, refid);
            details = " Contact - ";
            details += StringUtil.isNullOrEmpty(c.getFirstname()) ? "" : c.getFirstname() + " ";
            details += StringUtil.isNullOrEmpty(c.getLastname()) ? "" : c.getLastname();
            auditAction = AuditAction.CONTACT_DOC_DOWNLOAD;
        } else if (map.equals("3")) {
            CrmProduct p = (CrmProduct) hibernateTemplate.get(CrmProduct.class, refid);
            details = " Product - ";
            details += StringUtil.isNullOrEmpty(p.getProductname()) ? "" : p.getProductname();
            auditAction = AuditAction.PRODUCT_DOC_DOWNLOAD;
        } else if (map.equals("4")) {
            CrmAccount a = (CrmAccount) hibernateTemplate.get(CrmAccount.class, refid);
            details = " Account - ";
            details += StringUtil.isNullOrEmpty(a.getAccountname()) ? "" : a.getAccountname();
            auditAction = AuditAction.ACCOUNT_DOC_DOWNLOAD;
        } else if (map.equals("5")) {
            CrmOpportunity o = (CrmOpportunity) hibernateTemplate.get(CrmOpportunity.class, refid);
            details = " Opportunity - ";
            details += StringUtil.isNullOrEmpty(o.getOppname()) ? "" : o.getOppname();
            auditAction = AuditAction.OPPORTUNITY_DOC_DOWNLOAD;
        } else if (map.equals("6")) {
            CrmCase c = (CrmCase) hibernateTemplate.get(CrmCase.class, refid);
            details = " Case - ";
            details += StringUtil.isNullOrEmpty(c.getSubject()) ? "" : c.getSubject();
            auditAction = AuditAction.CASE_DOC_DOWNLOAD;
        } else if (map.equals("7")) {
            CrmActivityMaster am = (CrmActivityMaster) hibernateTemplate.get(CrmActivityMaster.class, refid);
            details = " Activity - ";
            details += StringUtil.isNullOrEmpty(am.getFlag()) ? "" : am.getFlag() + " ";
            details += StringUtil.isNullOrEmpty(am.getCrmCombodataByStatusid().getValue()) ? ""
                    : am.getCrmCombodataByStatusid().getValue();
            auditAction = AuditAction.ACTIVITY_DOC_DOWNLOAD;
        } else if (map.equals("-1")) {
            details = " My - Document ";
            auditAction = AuditAction.MY_DOC_DOWNLOAD;
        }

        auditTrailDAOObj.insertAuditLog(auditAction,
                " Document - '" + ht.get("Name").toString() + "' downloaded for " + details + " ", request,
                ht.get("docid").toString());

        myjobj.put("success", true);
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
    }
    return new ModelAndView("jsonView", "model", myjobj.toString());
}

From source file:org.bonitasoft.console.common.server.servlet.ResourceServlet.java

/**
 * Get resource file//from   ww w .j  av  a 2  s . c o m
 *
 * @param request
 * @param response
 * @param resourceName
 * @param fileName
 * @throws ServletException
 * @throws UnsupportedEncodingException
 */
protected void getResourceFile(final HttpServletRequest request, final HttpServletResponse response,
        String resourceName, String fileName) throws ServletException, UnsupportedEncodingException {
    byte[] content = null;
    String contentType = null;
    if (resourceName == null) {
        final String errorMessage = "Error while using the servlet to get a resource: the parameter "
                + getResourceParameterName() + " is null.";
        if (LOGGER.isLoggable(Level.WARNING)) {
            LOGGER.log(Level.WARNING, errorMessage);
        }
        throw new ServletException(errorMessage);
    }
    if (fileName == null) {
        final String errorMessage = "Error while using the servlet to get a resource: the parameter "
                + LOCATION_PARAM + " is null.";
        if (LOGGER.isLoggable(Level.WARNING)) {
            LOGGER.log(Level.WARNING, errorMessage);
        }
        throw new ServletException(errorMessage);
    }
    resourceName = URLDecoder.decode(resourceName, "UTF-8");
    fileName = URLDecoder.decode(fileName, "UTF-8");
    response.setCharacterEncoding("UTF-8");

    final File resourcesParentFolder = getResourcesParentFolder(request);
    final String subFolderName = getSubFolderName();
    String subFolderSuffix;
    if (subFolderName != null) {
        subFolderSuffix = File.separator + subFolderName;
    } else {
        subFolderSuffix = "";
    }

    try {
        final File resourceFolder = new File(resourcesParentFolder, resourceName + subFolderSuffix);
        final File file = new File(resourceFolder, fileName);
        final BonitaHomeFolderAccessor tenantFolder = new BonitaHomeFolderAccessor();
        if (!tenantFolder.isInFolder(resourceFolder, resourcesParentFolder)) {
            throw new ServletException("For security reasons, access to this file paths"
                    + resourceFolder.getAbsolutePath() + " is restricted.");
        }
        if (!tenantFolder.isInFolder(file, resourceFolder)) {
            throw new ServletException("For security reasons, access to this file paths"
                    + file.getAbsolutePath() + " is restricted.");
        }
        final String lowerCaseFileName = fileName.toLowerCase();
        if (lowerCaseFileName.endsWith(".jpg")) {
            contentType = "image/jpeg";
        } else if (lowerCaseFileName.endsWith(".jpeg")) {
            contentType = "image/jpeg";
        } else if (lowerCaseFileName.endsWith(".gif")) {
            contentType = "image/gif";
        } else if (lowerCaseFileName.endsWith(".png")) {
            contentType = "image/png";
        } else if (lowerCaseFileName.endsWith(".css") || lowerCaseFileName.endsWith(".less")) {
            contentType = "text/css";
        } else if (lowerCaseFileName.endsWith(".js")) {
            contentType = "application/x-javascript";
        } else if (lowerCaseFileName.endsWith(".html")) {
            contentType = "text/html; charset=UTF-8";
        } else if (lowerCaseFileName.endsWith(".htc")) {
            contentType = "text/x-component";
        } else if (lowerCaseFileName.endsWith(".svg")) {
            contentType = "image/svg+xml";
        } else if (lowerCaseFileName.endsWith(".eot")) {
            contentType = "application/vnd.ms-fontobject";
        } else if (lowerCaseFileName.endsWith(".woff")) {
            contentType = "application/x-font-woff";
        } else if (lowerCaseFileName.endsWith(".ttf")) {
            contentType = "application/x-font-ttf";
        } else if (lowerCaseFileName.endsWith(".otf")) {
            contentType = "application/x-font-opentype";
        } else {
            final FileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();
            contentType = mimetypesFileTypeMap.getContentType(file);
        }
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        content = FileUtils.readFileToByteArray(file);
        response.setContentType(contentType);
        response.setContentLength(content.length);
        response.setBufferSize(content.length);
        final OutputStream out = response.getOutputStream();
        out.write(content, 0, content.length);
        response.flushBuffer();
        out.close();
    } catch (final IOException e) {
        if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, "Error while generating the response.", e);
        }
        throw new ServletException(e.getMessage(), e);
    }
}

From source file:org.bonitasoft.forms.server.ApplicationResourceServlet.java

/**
 * {@inheritDoc}//from  w ww .  ja va  2  s.  co m
 */
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException {

    final String processUUIDStr = request.getParameter(PROCESS_ID_PARAM);
    final String resourcePath = request.getParameter(RESOURCE_PATH_PARAM);
    String resourceFileName = null;
    byte[] content = null;
    String contentType = null;
    if (resourcePath == null) {
        final String errorMessage = "Error while using the servlet ApplicationResourceServlet to get a resource: the parameter "
                + RESOURCE_PATH_PARAM + " is undefined.";
        if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, errorMessage);
        }
        throw new ServletException(errorMessage);
    }
    if (processUUIDStr == null) {
        final String errorMessage = "Error while using the servlet ApplicationResourceServlet to get a resource: the parameter "
                + PROCESS_ID_PARAM + " is undefined.";
        if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, errorMessage);
        }
        throw new ServletException(errorMessage);
    }
    try {
        final long tenantID = getTenantID(request);
        final File processDir = new File(WebBonitaConstantsUtils.getInstance(tenantID).getFormsWorkFolder(),
                processUUIDStr);
        if (processDir.exists()) {
            final File[] directories = processDir.listFiles(new FileFilter() {

                @Override
                public boolean accept(final File pathname) {
                    return pathname.isDirectory();
                }
            });
            long lastDeployementDate = 0L;
            for (final File directory : directories) {
                try {
                    final long deployementDate = Long.parseLong(directory.getName());
                    if (deployementDate > lastDeployementDate) {
                        lastDeployementDate = deployementDate;
                    }
                } catch (final Exception e) {
                    if (LOGGER.isLoggable(Level.WARNING)) {
                        LOGGER.log(Level.WARNING,
                                "Process application resources deployment folder contains a directory that does not match a process deployment timestamp: "
                                        + directory.getName(),
                                e);
                    }
                }
            }
            if (lastDeployementDate == 0L) {
                if (LOGGER.isLoggable(Level.WARNING)) {
                    LOGGER.log(Level.WARNING,
                            "Process application resources deployment folder contains no directory that match a process deployment timestamp.");
                }
            } else {
                final File file = new File(processDir, lastDeployementDate + File.separator + WEB_RESOURCES_DIR
                        + File.separator + resourcePath);

                final BonitaHomeFolderAccessor tenantFolder = new BonitaHomeFolderAccessor();
                if (!tenantFolder.isInFolder(file, processDir)) {
                    throw new ServletException("For security reasons, access to this file paths"
                            + file.getAbsolutePath() + " is restricted.");
                }

                resourceFileName = file.getName();
                content = FileUtils.readFileToByteArray(file);
                if (resourceFileName.endsWith(".css")) {
                    contentType = "text/css";
                } else if (resourceFileName.endsWith(".js")) {
                    contentType = "application/x-javascript";
                } else {
                    final FileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();
                    contentType = mimetypesFileTypeMap.getContentType(file);
                }
            }
        } else {
            if (LOGGER.isLoggable(Level.WARNING)) {
                LOGGER.log(Level.WARNING,
                        "The Process application resources deployment directory does not exist.");
            }
        }
    } catch (final Exception e) {
        final String errorMessage = "Error while getting the resource " + resourcePath;
        if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, errorMessage, e);
        }
        throw new ServletException(errorMessage, e);
    }
    if (contentType == null) {
        contentType = "application/octet-stream";
    }
    response.setContentType(contentType);
    response.setCharacterEncoding("UTF-8");
    try {
        final String encodedfileName = URLEncoder.encode(resourceFileName, "UTF-8");
        final String userAgent = request.getHeader("User-Agent");
        if (userAgent != null && userAgent.contains("Firefox")) {
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedfileName);
        } else {
            response.setHeader("Content-Disposition", "attachment; filename=\""
                    + encodedfileName.replaceAll("\\+", " ") + "\"; filename*=UTF-8''" + encodedfileName);
        }
        response.setContentLength(content.length);
        final OutputStream out = response.getOutputStream();
        out.write(content);
        out.close();
    } catch (final IOException e) {
        if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, "Error while generating the response.", e);
        }
        throw new ServletException(e.getMessage(), e);
    }
}