Example usage for java.nio.file Files probeContentType

List of usage examples for java.nio.file Files probeContentType

Introduction

In this page you can find the example usage for java.nio.file Files probeContentType.

Prototype

public static String probeContentType(Path path) throws IOException 

Source Link

Document

Probes the content type of a file.

Usage

From source file:de.fosd.jdime.common.FileArtifact.java

/**
 * Returns the MIME content type of the <code>File</code> in which this <code>FileArtifact</code> is stored. 
 * If the content type can not be determined <code>null</code> will be returned.
 *
 * @return the MIME content type /* w ww  .j a v  a 2 s  .c om*/
 *
 * @throws IOException
 *         if an I/O exception occurs while trying to determine the content type
 */
public final String getContentType() throws IOException {
    assert (exists());

    String mimeType = Files.probeContentType(file.toPath());

    if (mimeType == null) {

        // returns application/octet-stream if the type can not be determined
        mimeType = mimeMap.getContentType(file);

        if ("application/octet-stream".equals(mimeType)) {
            mimeType = null;
        }
    }

    return mimeType;
}

From source file:ste.xtest.net.StubURLConnection.java

/**
 * Sets the body, content-type (depending on file) and content-length (-1 if
 * the file does not exist or the file length if the file exists) of the 
 * request. /* ww  w  . j a  va2  s  . c  o m*/
 * 
 * @param file - MAY BE NULL
 * 
 * @return this
 */
public StubURLConnection file(final String file) {
    String type = null;

    Path path = (file == null) ? null : FileSystems.getDefault().getPath(file);
    if (path != null) {
        try {
            type = Files.probeContentType(path);
        } catch (IOException x) {
            //
            // noting to do
            //
        }
    }

    setContent(path, (type == null) ? "application/octet-stream" : type);
    return this;
}

From source file:fr.mby.opa.pics.web.controller.UploadPicturesController.java

protected List<Path> processArchive(final MultipartFile multipartFile) throws IOException {
    final List<Path> archivePictures = new ArrayList<>(128);

    // We copy the archive in a tmp file
    final File tmpFile = File.createTempFile(multipartFile.getName(), ".tmp");
    multipartFile.transferTo(tmpFile);/*  w  w w  .j a  v a 2 s . co m*/
    // final InputStream archiveInputStream = multipartFile.getInputStream();
    // Streams.copy(archiveInputStream, new FileOutputStream(tmpFile), true);
    // archiveInputStream.close();

    final Path tmpFilePath = tmpFile.toPath();
    final FileSystem archiveFs = FileSystems.newFileSystem(tmpFilePath, null);

    final Iterable<Path> rootDirs = archiveFs.getRootDirectories();
    for (final Path rootDir : rootDirs) {
        Files.walkFileTree(rootDir, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(final Path path, final BasicFileAttributes attrs)
                    throws IOException {
                final boolean isDirectory = Files.isDirectory(path);

                if (!isDirectory) {
                    final String contentType = Files.probeContentType(path);
                    if (contentType != null && contentType.startsWith("image/")) {
                        archivePictures.add(path);
                    }
                }

                return super.visitFile(path, attrs);
            }
        });
    }

    return archivePictures;
}

From source file:org.structr.web.common.FileHelper.java

/**
 * Return mime type of given file/*from   www .j a va 2s.  co m*/
 *
 * @param file
 * @param name
 * @return content type
 * @throws java.io.IOException
 */
public static String getContentMimeType(final java.io.File file, final String name) throws IOException {

    String mimeType;

    // try name first, if not null
    if (name != null) {
        mimeType = mimeTypeMap.getContentType(name);
        if (mimeType != null && !UNKNOWN_MIME_TYPE.equals(mimeType)) {
            return mimeType;
        }
    }

    // then file content
    mimeType = Files.probeContentType(file.toPath());
    if (mimeType != null && !UNKNOWN_MIME_TYPE.equals(mimeType)) {

        return mimeType;
    }

    // fallback: jmimemagic
    try {
        final MagicMatch match = Magic.getMagicMatch(file, false, true);
        if (match != null) {

            return match.getMimeType();
        }

    } catch (MagicParseException | MagicMatchNotFoundException | MagicException ignore) {
        // mex.printStackTrace();
    }

    // no success :(
    return UNKNOWN_MIME_TYPE;
}

From source file:org.silverpeas.mobile.server.servlets.FormServlet.java

private GenericDataRecord getGenericDataRecord(HttpServletRequest request, final Map<String, Object> data,
        final String role, final ProcessModel model, final Action action) throws Exception {
    Form form = model.getPublicationForm(action.getName(), role,
            getUserInSession(request).getUserPreferences().getLanguage());
    GenericDataRecord record = (GenericDataRecord) model.getNewActionRecord(action.getName(), role,
            getUserInSession(request).getUserPreferences().getLanguage(), null);
    for (Map.Entry<String, Object> f : data.entrySet()) {
        Field field = record.getField(f.getKey());
        if (f.getValue() == null || f.getValue().equals("null")) {
            if (field.getTypeName().equalsIgnoreCase("file") && field.getValue() != null) {
                //TODO : make work delete file
                SimpleDocument doc = AttachmentServiceProvider.getAttachmentService().searchDocumentById(
                        new SimpleDocumentPK(field.getValue()),
                        getUserInSession(request).getUserPreferences().getLanguage());
                AttachmentServiceProvider.getAttachmentService().deleteAttachment(doc);
            }//from   w w w  . ja  v a2 s . c  o  m
            field.setNull();
        } else {
            if (field.getTypeName().equalsIgnoreCase("user")) {
                UserDetail u = Administration.get().getUserDetail((String) f.getValue());
                field.setObjectValue(u);
            } else if (field.getTypeName().equalsIgnoreCase("group")) {
                GroupDetail g = Administration.get().getGroup((String) f.getValue());
                field.setObjectValue(g);
            } else if (field.getTypeName().equalsIgnoreCase("multipleUser")) {
                StringTokenizer stk = new StringTokenizer((String) f.getValue(), ",");
                UserDetail[] users = new UserDetail[stk.countTokens()];
                int i = 0;
                while (stk.hasMoreTokens()) {
                    String id = stk.nextToken().trim();
                    UserDetail u = Administration.get().getUserDetail(id);
                    users[i] = u;
                    i++;
                }
                field.setObjectValue(users);
            } else if (field.getTypeName().equalsIgnoreCase("date")) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date d = sdf.parse((String) f.getValue());
                field.setValue(DateUtil.formatDate(d));
            } else if (field.getTypeName().equalsIgnoreCase("wysiwyg")) {
                //TODO
                //WysiwygController.createFileAndAttachment();
                //WysiwygController.updateFileAndAttachment();
                //form.updateWysiwyg()
            } else if (field.getTypeName().equalsIgnoreCase("file")) {
                if (f.getValue() != null && !f.getValue().equals("null")) {
                    File file = (File) f.getValue();
                    SimpleDocumentPK simpleDocPk = new SimpleDocumentPK(null, model.getModelId());
                    Path source = Paths.get(file.toURI());
                    String mimeType = Files.probeContentType(source);
                    String foreignId = model.getModelId();
                    SimpleDocument doc = new SimpleDocument(simpleDocPk, foreignId, 0, false,
                            getUserInSession(request).getId(),
                            new SimpleAttachment(file.getName(),
                                    getUserInSession(request).getUserPreferences().getLanguage(),
                                    file.getName(), "",

                                    file.length(), mimeType, getUserInSession(request).getId(), new Date(),
                                    null));
                    doc = AttachmentServiceProvider.getAttachmentService().createAttachment(doc, file);
                    ((FileField) field).setAttachmentId(doc.getId());
                }
            } else {
                field.setValue((String) f.getValue());
            }
        }
    }
    return record;
}

From source file:de.fosd.jdime.artifact.file.FileArtifact.java

/**
 * Returns the MIME content type of the <code>File</code> in which this <code>FileArtifact</code> is stored. 
 * If the content type can not be determined <code>null</code> will be returned.
 *
 * @return the MIME content type/*from  w ww .  j  av a 2  s  .c o  m*/
 */
private String getContentType() {
    String mimeType = null;
    File file = getFile();

    try {
        mimeType = Files.probeContentType(file.toPath());
    } catch (IOException e) {
        LOG.log(Level.WARNING, e, () -> "Could not probe content type of " + file);
    }

    if (mimeType == null) {

        // returns application/octet-stream if the type can not be determined
        mimeType = mimeMap.getContentType(file);

        if ("application/octet-stream".equals(mimeType)) {
            mimeType = null;
        }
    }

    return mimeType;
}

From source file:org.xsystem.sql2.http.PageServlet2.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //  response.setHeader("Pragma", "No-cache");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    //response.setHeader("Cache-Control", "no-cache");

    response.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json;charset=UTF-8");

    String path = request.getPathInfo();
    ErrorHandler errorHansdler = null;
    try (ServletOutputStream out = response.getOutputStream();
            ServletInputStream input = request.getInputStream()) {
        try {/*from w w  w  .  j  a v  a2  s  .  c o m*/

            if (path == null) {
                loadRepository();
                if (errorReport != null) {
                    Map error = Auxilary.makeJsonError("Loading error-" + errorReport);
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    writeJson(error, out);
                } else {
                    writeJson(Auxilary.makeJsonSuccess(), out);
                }
                return;
            }
            if (errorReport != null) {
                Map error = Auxilary.makeJsonError("Loading error-" + errorReport);
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                writeJson(error, out);
                return;
            }
            Config cofig = getConfig();
            errorHansdler = cofig.getErrorHandler();

            Matcher matcher = Pattern.compile("").matcher(path);
            List<ActionExecuter> lstActions = cofig.getActions();
            Optional<ActionExecuter> opt = lstActions.stream()
                    .filter(action -> matcher.reset().usePattern(action.getPattern()).find()).findFirst();
            if (opt.isPresent()) {
                ActionExecuter action = opt.get();

                List groups = HttpHelper.getGroups(matcher);

                Map params = Collections.emptyMap();
                Object json = Collections.emptyMap();
                Long skip = null;
                Integer total = null;

                if (action.isMultipart()) {
                    json = HttpHelper.getMultipartJson(request);
                } else {
                    params = HttpHelper.getParams(request);
                    skip = HttpHelper.getParamSkip(request);
                    total = HttpHelper.getParamTotal(request);
                    if (!action.isForm()) {
                        json = getJson(input);
                    }
                }

                Map<String, Object> context = Auxilary.newMap("groups", groups, "params", params, "json", json,
                        "request", request);

                Map<String, String> evals = action.getContextParams();
                FileFormat fileFormat = action.getFileFormat();
                int thumb = HttpHelper.getThumb(fileFormat, context);
                context = getContext(evals, context);
                if (skip != null) {
                    context.put("skip", skip);
                }
                if (total != null) {
                    context.put("total", total);
                }
                Object rezult = execute(request, cofig, action, context);
                if (fileFormat == null) {
                    writeJson(Auxilary.makeJsonSuccess("data", rezult), out);
                } else {
                    FileTransfer fileTransfer = HttpHelper.getFileTransfer(fileFormat, rezult,
                            (format, data) -> {
                                return getContent(format, data, "defualt");
                            });

                    if (fileTransfer == null && !fileFormat.isDownload()
                            && !Auxilary.isEmptyOrNull(fileFormat.getNotfound())) {
                        String fname = fileFormat.getNotfound();
                        if (fname.startsWith(FILEPRFX)) {
                            fname = fname.substring(FILEPRFX.length());
                            fname = config.getServletContext().getRealPath(fname);
                            File f = new File(fname);
                            if (f.exists()) {
                                fileTransfer = new FileTransfer();
                                String contentType = Files.probeContentType(Paths.get(fname));
                                String fileType = Auxilary.getFileExtention(fname);
                                byte[] b = Auxilary.readBinaryFile(f);
                                fileTransfer.setContentType(contentType);
                                fileTransfer.setFileType(fileType);
                                fileTransfer.setData(b);
                            }
                        }
                    }

                    if (fileTransfer == null) {

                        Map error = Auxilary.makeJsonError("File not found ");
                        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                        writeJson(error, out);
                    } else {
                        boolean isDownload = fileFormat.isDownload();

                        HttpHelper.writeFile(fileTransfer, isDownload, thumb, request, response, out);
                    }
                }
            } else {
                Map error = Auxilary.makeJsonError("Page not found [" + path + "]");
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                writeJson(error, out);
            }

        } catch (Throwable err) {

            // response.setStatus();
            if (errorHansdler == null) {
                error(err, out);
            } else {
                Object error = errorHansdler.handler(err);
                writeJson(error, out);
            }
        }
    }
}

From source file:au.org.ands.vocabs.toolkit.db.AccessPointUtils.java

/** Create an access point for a version, for a file. Don't duplicate it,
 * if it already exists./*from w  w w . j av  a  2  s .  c  o m*/
 * @param version The version for which the access point is to be created.
 * @param format The format of the access point. If null, attempt
 * to deduce a format from the filename.
 * @param targetPath The path to the existing file.
 */
public static void createFileAccessPoint(final Version version, final String format, final Path targetPath) {
    String targetPathString;
    try {
        targetPathString = targetPath.toRealPath().toString();
    } catch (IOException e) {
        LOGGER.error("createFileAccessPoint failed calling " + "toRealPath() on file: " + targetPath.toString(),
                e);
        // Try toAbsolutePath() instead.
        targetPathString = targetPath.toAbsolutePath().toString();
    }
    List<AccessPoint> aps = getAccessPointsForVersionAndType(version, AccessPoint.FILE_TYPE);
    for (AccessPoint ap : aps) {
        if (targetPathString.equals(getToolkitPath(ap))) {
            // Already exists. Check the format.
            if (format != null && !format.equals(getFormat(ap))) {
                // Format changed.
                updateFormat(ap, format);
            }
            return;
        }
    }
    // No existing access point for this file, so create a new one.
    AccessPoint ap = new AccessPoint();
    ap.setVersionId(version.getId());
    ap.setType(AccessPoint.FILE_TYPE);
    JsonObjectBuilder jobPortal = Json.createObjectBuilder();
    JsonObjectBuilder jobToolkit = Json.createObjectBuilder();
    jobToolkit.add("path", targetPathString);
    // toolkitData is now done.
    ap.setToolkitData(jobToolkit.build().toString());
    ap.setPortalData("");
    // Persist what we have ...
    AccessPointUtils.saveAccessPoint(ap);
    // ... so that now we can get access to the
    // ID of the persisted object with ap.getId().
    String baseFilename = targetPath.getFileName().toString();
    jobPortal.add("uri", downloadPrefixProperty + ap.getId() + "/" + baseFilename);
    // Now work on the format. The following is messy. It's really very
    // much for the best if the portal provides the format.
    String deducedFormat;
    if (format == null) {
        // The format was not provided to us, so try to deduce it.
        // First, try the extension.
        String extension = FilenameUtils.getExtension(baseFilename);
        deducedFormat = EXTENSION_TO_FILE_FORMAT_MAP.get(extension);
        if (deducedFormat == null) {
            // No luck with the extension, so try probing.
            try {
                String mimeType = Files.probeContentType(targetPath);
                if (mimeType == null) {
                    // Give up.
                    deducedFormat = "Unknown";
                } else {
                    deducedFormat = MIMETYPE_TO_FILE_FORMAT_MAP.get(mimeType);
                    if (deducedFormat == null) {
                        // Give up.
                        deducedFormat = "Unknown";
                    }
                }
            } catch (IOException e) {
                LOGGER.error("createFileAccessPoint failed to get " + "MIME type of file: " + targetPathString,
                        e);
                // Give up.
                deducedFormat = "Unknown";
            }
        }
    } else {
        // The format was provided to us, so use that. Much easier.
        deducedFormat = format;
    }
    jobPortal.add("format", deducedFormat);
    // portalData is now complete.
    ap.setPortalData(jobPortal.build().toString());
    AccessPointUtils.updateAccessPoint(ap);
}

From source file:org.codice.ddf.catalog.content.impl.FileSystemStorageProvider.java

private ContentItem readContent(URI uri) throws StorageException {
    Path file = getContentFilePath(uri);

    if (file == null) {
        throw new StorageException("Unable to find file for content ID: " + uri.getSchemeSpecificPart());
    }/* w  w  w. jav a2 s .  c om*/

    String extension = FilenameUtils.getExtension(file.getFileName().toString());

    String mimeType;

    try (InputStream fileInputStream = Files.newInputStream(file)) {
        mimeType = mimeTypeMapper.guessMimeType(fileInputStream, extension);
    } catch (Exception e) {
        LOGGER.warn("Could not determine mime type for file extension = {}; defaulting to {}", extension,
                DEFAULT_MIME_TYPE);
        mimeType = DEFAULT_MIME_TYPE;
    }
    if (mimeType == null || DEFAULT_MIME_TYPE.equals(mimeType)) {
        try {
            mimeType = Files.probeContentType(file);
        } catch (IOException e) {
            LOGGER.warn("Unable to determine mime type using Java Files service.", e);
            mimeType = DEFAULT_MIME_TYPE;
        }
    }

    LOGGER.debug("mimeType = {}", mimeType);
    long size = 0;
    try {
        size = Files.size(file);
    } catch (IOException e) {
        LOGGER.warn("Unable to retrieve size of file: {}", file.toAbsolutePath().toString(), e);
    }
    return new ContentItemImpl(uri.getSchemeSpecificPart(), uri.getFragment(),
            com.google.common.io.Files.asByteSource(file.toFile()), mimeType, file.getFileName().toString(),
            size, null);
}

From source file:bjerne.gallery.service.impl.GalleryServiceImpl.java

private String getContentType(File file) throws IOException {
    return Files.probeContentType(file.toPath());
}