Example usage for java.net FileNameMap getContentTypeFor

List of usage examples for java.net FileNameMap getContentTypeFor

Introduction

In this page you can find the example usage for java.net FileNameMap getContentTypeFor.

Prototype

public String getContentTypeFor(String fileName);

Source Link

Document

Gets the MIME type for the specified file name.

Usage

From source file:edu.utah.bmi.ibiomes.parse.AbstractLocalFileImpl.java

/**
 * Get file MIME type// w w w . j  ava2 s  .  c o m
 * @return MIME type
 */
public String getMimeType() {
    FileNameMap fileNameMap = URLConnection.getFileNameMap();
    String mimeType = fileNameMap.getContentTypeFor(this.getAbsolutePath());
    return mimeType;
}

From source file:me.neatmonster.spacertk.actions.FileActions.java

/**
 * Gets information about a File/* w w w .  j  av a2 s.  c  o  m*/
 * @param file File to get information about
 * @return Information about a file
 */
@Action(aliases = { "getFileInformations", "fileInformations", "informations" })
public TreeMap<String, Object> getFileInformations(final String file) {
    final TreeMap<String, Object> fileInformations = new TreeMap<String, Object>();
    final File file_ = new File(file);
    if (file_.exists()) {
        fileInformations.put("Name", file_.getName());
        fileInformations.put("Path", file_.getPath());
        fileInformations.put("Size", file_.length());
        fileInformations.put("Execute", file_.canExecute());
        fileInformations.put("Read", file_.canRead());
        fileInformations.put("Write", file_.canWrite());
        fileInformations.put("IsDirectory", file_.isDirectory());
        fileInformations.put("IsFile", file_.isFile());
        fileInformations.put("IsHidden", file_.isHidden());
        final FileNameMap fileNameMap = URLConnection.getFileNameMap();
        fileInformations.put("Mime", fileNameMap.getContentTypeFor("file://" + file_.getPath()));
        return fileInformations;
    }
    return new TreeMap<String, Object>();
}

From source file:com.openmeap.services.ApplicationManagementServlet.java

private Result handleArchiveDownload(HttpServletRequest request, HttpServletResponse response) {

    Result res = new Result();
    Error err = new Error();
    res.setError(err);/*from ww  w.  j  a v  a2  s  .  c o m*/

    GlobalSettings settings = modelManager.getGlobalSettings();
    Map properties = this.getServicesWebProperties();
    String nodeKey = (String) properties.get("clusterNodeUrlPrefix");
    ClusterNode clusterNode = settings.getClusterNode(nodeKey);
    if (nodeKey == null || clusterNode == null) {
        // TODO: create a configuration error code
        err.setCode(ErrorCode.UNDEFINED);
        err.setMessage("A configuration is missing.  Please consult the error logs.");
        logger.error(
                "For each node in the cluster, the property or environment variable OPENMEAP_CLUSTER_NODE_URL_PREFIX must match the \"Service Url Prefix\" value configured in the administrative interface.  This value is currently "
                        + nodeKey + ".");
        return res;
    }

    String pathValidation = clusterNode.validateFileSystemStoragePathPrefix();
    if (pathValidation != null) {
        err.setCode(ErrorCode.UNDEFINED);
        err.setMessage("A configuration is missing.  Please consult the error logs.");
        logger.error(
                "There is an issue with the location at \"File-system Storage Prefix\".  " + pathValidation);
        return res;
    }

    String hash = request.getParameter(UrlParamConstants.APPARCH_HASH);
    String hashAlg = request.getParameter(UrlParamConstants.APPARCH_HASH_ALG);
    String fileName = null;

    if (hash == null || hashAlg == null) {
        // look in the apps directory for the archive specified
        String appName = request.getParameter(UrlParamConstants.APP_NAME);
        String versionId = request.getParameter(UrlParamConstants.APP_VERSION);

        ApplicationVersion appVersion = modelManager.getModelService().findAppVersionByNameAndId(appName,
                versionId);
        if (appVersion == null) {
            String mesg = "The application version " + versionId + " was not found for application " + appName;
            err.setCode(ErrorCode.APPLICATION_VERSION_NOTFOUND);
            err.setMessage(mesg);
            logger.warn(mesg);
            return res;
        }

        String auth = request.getParameter(UrlParamConstants.AUTH_TOKEN);
        com.openmeap.model.dto.Application app = appVersion.getApplication();
        try {
            if (auth == null || !AuthTokenProvider.validateAuthToken(app.getProxyAuthSalt(), auth)) {
                err.setCode(ErrorCode.AUTHENTICATION_FAILURE);
                err.setMessage("The \"auth\" token presented is not recognized, missing, or empty.");
                return res;
            }
        } catch (DigestException e) {
            throw new GenericRuntimeException(e);
        }

        hash = appVersion.getArchive().getHash();
        hashAlg = appVersion.getArchive().getHashAlgorithm();
        fileName = app.getName() + " - " + appVersion.getIdentifier();
    } else {
        fileName = hashAlg + "-" + hash;
    }

    File file = ApplicationArchive.getFile(clusterNode.getFileSystemStoragePathPrefix(), hashAlg, hash);
    if (!file.exists()) {
        String mesg = "The application archive with " + hashAlg + " hash " + hash + " was not found.";
        // TODO: create an enumeration for this error
        err.setCode(ErrorCode.UNDEFINED);
        err.setMessage(mesg);
        logger.warn(mesg);
        return res;
    }

    try {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String mimeType = fileNameMap.getContentTypeFor(file.toURL().toString());
        response.setContentType(mimeType);
        response.setContentLength(Long.valueOf(file.length()).intValue());
        URLCodec codec = new URLCodec();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".zip\";");

        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(file));
            outputStream = response.getOutputStream();
            Utils.pipeInputStreamIntoOutputStream(inputStream, outputStream);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            //if(outputStream!=null) {outputStream.close();}
        }
        response.flushBuffer();
    } catch (FileNotFoundException e) {
        logger.error("Exception {}", e);
    } catch (IOException ioe) {
        logger.error("Exception {}", ioe);
    }

    return null;
}

From source file:de.mpg.escidoc.pubman.multipleimport.processor.ZfNProcessor.java

/**
 * Converts an inputstream into a FileVO.
 * @param file/*www .  j  ava  2 s .co  m*/
 * @param name
 * @param user
 * @return FileVO
 * @throws Exception
 */
private FileVO createPubFile(InputStream in, AccountUserVO user) throws Exception {
    this.logger.debug("Creating PubFile: " + this.getCurrentFile());

    MdsFileVO mdSet = new MdsFileVO();
    FileVO fileVO = new FileVO();

    FileNameMap fileNameMap = URLConnection.getFileNameMap();
    String mimeType = fileNameMap.getContentTypeFor(this.getCurrentFile());

    URL fileURL = this.uploadFile(in, mimeType, user.getHandle());

    if (fileURL != null && !fileURL.toString().trim().equals("")) {
        fileVO.setStorage(FileVO.Storage.INTERNAL_MANAGED);
        fileVO.setVisibility(FileVO.Visibility.PUBLIC);
        fileVO.setDefaultMetadata(mdSet);
        fileVO.getDefaultMetadata().setTitle(new TextVO(this.getCurrentFile()));
        fileVO.setMimeType(mimeType);
        fileVO.setName(this.getCurrentFile());
        fileVO.setContent(fileURL.toString());
        System.out.println("SIZE:" + this.fileSize);
        fileVO.getDefaultMetadata().setSize(this.fileSize);
        String contentCategory = null;
        if (PubFileVOPresentation.getContentCategoryUri("PUBLISHER_VERSION") != null) {
            contentCategory = PubFileVOPresentation.getContentCategoryUri("PUBLISHER_VERSION");
        } else {
            Map<String, String> contentCategoryMap = PubFileVOPresentation.getContentCategoryMap();
            if (contentCategoryMap != null && !contentCategoryMap.entrySet().isEmpty()) {
                contentCategory = contentCategoryMap.values().iterator().next();
            } else {
                Logger.getLogger(PubFileVOPresentation.class)
                        .warn("WARNING: no content-category has been defined in Genres.xml");
            }
        }
        fileVO.setContentCategory(contentCategory);
        fileVO.getDefaultMetadata().setLicense(this.getConfig().get("License"));

        FormatVO formatVO = new FormatVO();
        formatVO.setType("dcterms:IMT");
        formatVO.setValue(mimeType);
        fileVO.getDefaultMetadata().getFormats().add(formatVO);
    }
    this.setCurrentFile("");
    this.fileNames.remove(0);
    return fileVO;
}

From source file:de.mpg.mpdl.inge.pubman.web.multipleimport.processor.ZfNProcessor.java

/**
 * Converts an inputstream into a FileVO.
 * //from ww  w. java  2 s.c  o  m
 * @param file
 * @param name
 * @param user
 * @return FileVO
 * @throws Exception
 */
private FileVO createPubFile(InputStream in, AccountUserVO user) throws Exception {
    this.logger.debug("Creating PubFile: " + this.getCurrentFile());

    MdsFileVO mdSet = new MdsFileVO();
    FileVO fileVO = new FileVO();

    FileNameMap fileNameMap = URLConnection.getFileNameMap();
    String mimeType = fileNameMap.getContentTypeFor(this.getCurrentFile());

    URL fileURL = this.uploadFile(in, mimeType, user.getHandle());

    if (fileURL != null && !fileURL.toString().trim().equals("")) {
        fileVO.setStorage(FileVO.Storage.INTERNAL_MANAGED);
        fileVO.setVisibility(FileVO.Visibility.PUBLIC);
        fileVO.setDefaultMetadata(mdSet);
        fileVO.getDefaultMetadata().setTitle(this.getCurrentFile());
        fileVO.setMimeType(mimeType);
        fileVO.setName(this.getCurrentFile());
        fileVO.setContent(fileURL.toString());
        System.out.println("SIZE:" + this.fileSize);
        fileVO.getDefaultMetadata().setSize(this.fileSize);
        String contentCategory = null;
        if (PubFileVOPresentation.getContentCategoryUri("PUBLISHER_VERSION") != null) {
            contentCategory = PubFileVOPresentation.getContentCategoryUri("PUBLISHER_VERSION");
        } else {
            Map<String, String> contentCategoryMap = PubFileVOPresentation.getContentCategoryMap();
            if (contentCategoryMap != null && !contentCategoryMap.entrySet().isEmpty()) {
                contentCategory = contentCategoryMap.values().iterator().next();
            } else {
                Logger.getLogger(PubFileVOPresentation.class)
                        .warn("WARNING: no content-category has been defined in Genres.xml");
            }
        }
        fileVO.setContentCategory(contentCategory);
        fileVO.getDefaultMetadata().setLicense(this.getConfig().get("License"));

        FormatVO formatVO = new FormatVO();
        formatVO.setType("dcterms:IMT");
        formatVO.setValue(mimeType);
        fileVO.getDefaultMetadata().getFormats().add(formatVO);
    }
    this.setCurrentFile("");
    this.fileNames.remove(0);
    return fileVO;
}

From source file:org.fao.unredd.portal.ApplicationController.java

@RequestMapping("/static/**")
public void getCustomStaticFile(HttpServletRequest request, HttpServletResponse response) throws IOException {

    // Get path to file
    String fileName = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);

    // Verify file exists
    File file = new File(config.getDir() + "/static/" + fileName);
    if (!file.isFile()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/*from  www . jav a 2s .  c o  m*/
    }

    // Manage cache headers: Last-Modified and If-Modified-Since
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    long lastModified = file.lastModified();
    if (ifModifiedSince >= (lastModified / 1000 * 1000)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }
    response.setDateHeader("Last-Modified", lastModified);

    // Set content type
    FileNameMap fileNameMap = URLConnection.getFileNameMap();
    String type = fileNameMap.getContentTypeFor(fileName);
    response.setContentType(type);

    // Send contents
    try {
        InputStream is = new FileInputStream(file);
        IOUtils.copy(is, response.getOutputStream());
        response.flushBuffer();
    } catch (IOException e) {
        logger.error("Error reading file", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.minws.frame.sdk.webqq.service.ApacheHttpService.java

private String getMimeType(File file) {
    FileNameMap fileNameMap = URLConnection.getFileNameMap();
    return fileNameMap.getContentTypeFor(file.toString());
}

From source file:com.odoo.base.ir.Attachment.java

@SuppressWarnings("deprecation")
private Notification setFileIntent(Uri uri) {
    Log.v(TAG, "setFileIntent()");
    Intent intent = new Intent(Intent.ACTION_VIEW);
    FileNameMap mime = URLConnection.getFileNameMap();
    String mimeType = mime.getContentTypeFor(uri.getPath());
    intent.setDataAndType(uri, mimeType);
    mNotificationResultIntent = PendingIntent.getActivity(mContext, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    mNotificationBuilder.addAction(R.drawable.ic_odoo_o, "Download attachment", mNotificationResultIntent);
    mNotificationBuilder.setOngoing(false);
    mNotificationBuilder.setAutoCancel(true);
    mNotificationBuilder.setContentTitle("Attachment downloaded");
    mNotificationBuilder.setContentText("Download Complete");
    mNotificationBuilder.setProgress(0, 0, false);
    mNotification = mNotificationBuilder.build();
    mNotification.setLatestEventInfo(mContext, "Attachment downloaded", "Download complete",
            mNotificationResultIntent);//from  w  w w  . ja  v a2 s.  c  om
    return mNotification;

}

From source file:com.openerp.base.ir.Attachment.java

private void requestIntent(Uri uri) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    FileNameMap mime = URLConnection.getFileNameMap();
    String mimeType = mime.getContentTypeFor(uri.getPath());
    intent.setDataAndType(uri, mimeType);
    mContext.startActivity(intent);/*www. jav a2  s.  co m*/
}

From source file:org.apache.ofbiz.base.util.UtilHttp.java

public static String getContentTypeByFileName(String fileName) {
    FileNameMap mime = URLConnection.getFileNameMap();
    return mime.getContentTypeFor(fileName);
}