Example usage for javax.activation MimetypesFileTypeMap MimetypesFileTypeMap

List of usage examples for javax.activation MimetypesFileTypeMap MimetypesFileTypeMap

Introduction

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

Prototype

public MimetypesFileTypeMap() 

Source Link

Document

The default constructor.

Usage

From source file:gov.nist.appvet.tool.synchtest.util.ReportUtil.java

/**
 * This method returns report information to the AppVet ToolAdapter as ASCII
 * text and cannot attach a file to the response.
 *//*from   w  w  w  . j  a  v  a  2 s .  co m*/
public static boolean sendPDFInHttpResponse(HttpServletResponse response, String reportText,
        ToolStatus reportStatus) {
    try {
        File reportFile = new File(reportFilePath);
        String mimeType = new MimetypesFileTypeMap().getContentType(reportFile);
        log.debug("Sending mimetype: " + mimeType);
        response.setContentType(mimeType);
        response.setHeader("Content-Disposition", "attachment;filename=" + reportFile.getName());
        response.setStatus(HttpServletResponse.SC_OK); // HTTP 200
        response.setHeader("apprisk", reportStatus.name());

        FileInputStream inputStream = new FileInputStream(reportFile); //read the file

        try {
            int c;
            while ((c = inputStream.read()) != -1) {
                response.getWriter().write(c);
            }
        } finally {
            if (inputStream != null)
                inputStream.close();
            response.getWriter().close();
        }

        //         PrintWriter out = response.getWriter();
        //         out.println(reportText);
        //         out.flush();
        //         out.close();
        log.info("Returned report");
        return true;
    } catch (IOException e) {
        log.error("Report not sent: " + e.toString());
        return false;
    }
}

From source file:eu.planets_project.tb.gui.backing.DownloadManager.java

/**
 * /*  w ww  . ja  v  a  2 s  .  c o  m*/
 * @return
 * @throws IOException
 */
public String downloadExportedExperiment(String expExportID, String downloadName) {
    FacesContext ctx = FacesContext.getCurrentInstance();

    // Decode the file name (might contain spaces and on) and prepare file object.
    try {
        expExportID = URLDecoder.decode(expExportID, "UTF-8");
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return null;
    }
    File file = expCache.getExportedFile(expExportID);

    HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();

    // Check if file exists and can be read:
    if (!file.exists() || !file.isFile() || !file.canRead()) {
        return "fileNotFound";
    }

    // Get content type by filename.
    String contentType = new MimetypesFileTypeMap().getContentType(file);

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    // Prepare streams.
    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        // Open the file:
        input = new BufferedInputStream(new FileInputStream(file));
        int contentLength = input.available();

        // Initialise the servlet response:
        response.reset();
        response.setContentType(contentType);
        response.setContentLength(contentLength);
        response.setHeader("Content-disposition", "attachment; filename=\"" + downloadName + ".xml\"");
        output = new BufferedOutputStream(response.getOutputStream());

        // Write file out:
        for (int data; (data = input.read()) != -1;) {
            output.write(data);
        }

        // Flush the stream:
        output.flush();

        // Tell Faces that we're finished:
        ctx.responseComplete();

    } catch (IOException e) {
        // Something went wrong?
        e.printStackTrace();

    } finally {
        // Gently close streams.
        close(output);
        close(input);
    }
    return "success";
}

From source file:org.phoenicis.tools.files.FileAnalyser.java

public String getMimetype(File inputFile) {
    try {/*from ww w .ja  va  2 s. co  m*/
        final MagicMatch match = getMatch(inputFile);
        final String mimeType = match.getMimeType();
        if ("???".equals(mimeType)) {
            return guessMimeTypeFromDescription(match);
        }

        return mimeType;
    } catch (MagicMatchNotFoundException e) {
        LOGGER.debug("Failed to get Mime Type", e);
        final MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
        return mimeTypesMap.getContentType(inputFile);
    }
}

From source file:org.wso2.carbon.governance.dashboardpopulator.GadgetPopulator.java

private static void addToRegistry(String rootPath, File file, Registry tenantRegistry) {
    try {// w ww  .  j  a  v  a2 s. co  m

        // This path is used to store the file resource under registry
        String fileRegistryPath = SYSTEM_GADGETS_PATH
                + file.getAbsolutePath().substring(rootPath.length()).replaceAll("[/\\\\]+", "/");

        // Adding the file to the Registry             
        Resource fileResource = tenantRegistry.newResource();
        fileResource.setMediaType(new MimetypesFileTypeMap().getContentType(file));
        fileResource.setContentStream(new FileInputStream(file));
        tenantRegistry.put(fileRegistryPath, fileResource);

    } catch (RegistryException e) {
        log.error(e);
    } catch (FileNotFoundException e) {
        log.error(e);
    }
}

From source file:edu.si.services.sidora.rest.batch.MimeTypeTest.java

@Test
public void mimeTypeDetectionComparison() throws IOException {
    File path = new File("src/test/resources/test-data/mimetype-test-files");

    String[] row = new String[] { "File Name", "ProbeContentType", "MimetypesFileTypeMap", "MimeUtil",
            "SimpleMagic", "Tika" };
    printRow(row);//from  w  ww .  ja v  a 2s  .com
    String line = "------------------------------";
    row = new String[] { "--------------------", line, line, line, line, line };
    printRow(row);

    File[] files = path.listFiles();

    for (int i = 0; i < files.length; i++) {
        if (files[i].isFile()) { //this line weeds out other directories/folders
            row[0] = files[i].getName().toString();
            row[1] = Files.probeContentType(files[i].toPath());
            row[2] = String.valueOf(new MimetypesFileTypeMap().getContentType(files[i]));
            row[3] = String.valueOf(MimeUtil.getMimeTypes(files[i]));
            if (!files[i].getName().contains("mkv") && !files[i].getName().contains("csv")) {
                ContentInfoUtil util = new ContentInfoUtil();
                row[4] = util.findMatch(files[i]).getMimeType();
            }
            row[5] = new Tika().detect(files[i]);

            printRow(row);
        }
    }
}

From source file:com.disney.opa.util.AttachmentUtils.java

/**
 * Based on file extension get the mime type.
 * /*from  w  w w. j a va2s . com*/
 * @param filename
 * @return mime type
 */
public static String getMimeType(String filename) {
    if (mimetypesFileTypeMap == null) {
        mimetypesFileTypeMap = new MimetypesFileTypeMap();
        mimetypesFileTypeMap.addMimeTypes("image/bmp            bmp");
        mimetypesFileTypeMap.addMimeTypes("image/gif            gif");
        mimetypesFileTypeMap.addMimeTypes("image/jpeg            jpg jpe jpeg");
        mimetypesFileTypeMap.addMimeTypes("application/pdf         pdf");
        mimetypesFileTypeMap.addMimeTypes("application/postscript   ps eps ai");
        mimetypesFileTypeMap.addMimeTypes("image/targa            tar targa");
        mimetypesFileTypeMap.addMimeTypes("image/tiff            tif tiff");
        mimetypesFileTypeMap.addMimeTypes("image/png            png");
        mimetypesFileTypeMap.addMimeTypes("application/photoshop   psd pdd");
        mimetypesFileTypeMap.addMimeTypes("application/octet-stream   img");
    }
    return mimetypesFileTypeMap.getContentType(filename);
}

From source file:eu.planets_project.tb.api.data.util.DigitalObjectRefBean.java

/**
 * Note that this only uses the extension to determine the mime-type.
 * //from w w w. j  ava2 s.c  om
 * @return The mime-type of this entity.
 */
public String getMimeType() {
    String mimetype = null;

    // File Case:
    if (this.file != null)
        mimetype = new MimetypesFileTypeMap().getContentType(file);

    // Based only on URI:
    if (this.domUri != null)
        mimetype = new MimetypesFileTypeMap().getContentType(this.domUri.getPath());

    // Digital Object Case:
    if (this.dob != null && dob.getTitle() != null)
        mimetype = new MimetypesFileTypeMap().getContentType(dob.getTitle());

    return mimetype;
}

From source file:org.osgl.storage.impl.SObject.java

/**
 * Construct an SObject with key and file specified
 * @see #of(String, java.io.File, java.util.Map)
 *///  w  w  w  . ja  v  a 2 s  .  com
public static SObject of(String key, File file) {
    if (file.canRead() && file.isFile()) {
        SObject sobj = new FileSObject(key, file);
        sobj.setAttribute(ATTR_FILE_NAME, file.getName());
        sobj.setAttribute(ATTR_CONTENT_TYPE, new MimetypesFileTypeMap().getContentType(file));
        return sobj;
    } else {
        return getInvalidObject(key, new IOException("File is a directory or not readable"));
    }
}

From source file:com.geoapi.api.server.services.implementations.WebViewService.java

@GET
@Path("textures/planets/{name}")
@Produces("image/*")
public Response planetTextures(@PathParam("name") String name) {

    ClassPathResource classPathResource = new ClassPathResource("com/geoapi/webview/planets/" + name);
    try {/*from w ww.ja  va 2s .c o m*/
        File file = classPathResource.getFile();

        if (!file.exists()) {
            throw new WebApplicationException(404);
        }

        String mt = new MimetypesFileTypeMap().getContentType(file);
        return Response.ok(file, mt).build();
    } catch (IOException e) {
        e.printStackTrace();
        throw new WebApplicationException(404);
    }
}

From source file:org.craftercms.studio.impl.v1.util.spring.mvc.BinaryView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    //Writer output = response.getWriter();
    OutputStream out = response.getOutputStream();
    Map<String, Object> responseModelMap = (Map<String, Object>) model
            .get(RestScriptsController.DEFAULT_RESPONSE_BODY_MODEL_ATTR_NAME);
    InputStream contentStream = (InputStream) responseModelMap.get(DEFAULT_CONTENT_STREAM_MODEL_ATTR_NAME);
    String contentPath = (String) responseModelMap.get(DEFAULT_CONTENT_PATH_MODEL_ATTR_NAME);

    MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();
    String contentType = mimetypesFileTypeMap.getContentType(contentPath);
    response.setContentType(contentType);
    if (contentStream != null) {
        IOUtils.write(IOUtils.toByteArray(contentStream), out);
    }//from   w  w  w. j  av  a2  s. co m
    out.flush();
    IOUtils.closeQuietly(contentStream);
    IOUtils.closeQuietly(out);
}