All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.springframework.util.FileUtils Maven / Gradle / Ivy

package org.springframework.util;

import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;

import javax.activation.FileTypeMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tika.Tika;
import org.apache.tika.config.TikaConfig;
import org.apache.tika.mime.MimeTypeException;
import org.springframework.core.io.Resource;
import org.springframework.http.InvalidMediaTypeException;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.util.DigestUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

public final class FileUtils {
  private static final Log logger = LogFactory.getLog(FileUtils.class);

  private static final TikaConfig TIKA_CONFIG = TikaConfig.getDefaultConfig();

  private static Map getMimeType() {
    Map map = new LinkedHashMap();
    // map.put("image/x-ms-bmp", "image/bmp");
    return map;
  }

  private static final Tika TIKA = new Tika(TIKA_CONFIG);

  private static final FileTypeMap FILE_TYPE_MAP = FileTypeMap.getDefaultFileTypeMap();

  public static File getFile(File file, String... pathSegments) {
    Assert.notNull(file, "file must not be null");
    Path path = Paths.get(file.toURI());
    for (String pathSegment : pathSegments) {
      path = path.resolve(pathSegment);
    }
    return path.toFile();
  }

  // static {
  // Tika tika;
  // try {
  // tika = new Tika(new TikaConfig(new
  // ClassPathResource("org/apache/tika/mime/custom-mimetypes.xml").getURL()));
  // }
  // catch (TikaException | IOException | SAXException e) {
  // tika = new Tika();
  // }
  // TIKA = tika;
  // }
  public static File getUploadFile(MultipartFile multipartFile, File file, String filename, String... pathSegments) {
    Assert.notNull(file, "file must not be null");
    Path path = Paths.get(file.toURI());
    for (String pathSegment : pathSegments) {
      path = path.resolve(pathSegment);
    }
    path.resolve(filename);
    return getUploadFile(multipartFile, path.toFile(), true);
  }

  // https://github.com/DhyanB/Open-Imaging
  public static String getExtension(Resource resource) {
    try (InputStream inputStream = resource.getInputStream()) {
      String detect = getDetect(inputStream, resource.getFilename());
      return getExtension(detect);
    }
    catch (IOException | InvalidMediaTypeException e) {
      if (logger.isTraceEnabled()) {
        logger.trace("Get Extension fail... from: " + resource, e);
      }
      else if (logger.isWarnEnabled()) {
        logger.warn("Get Extension fail... from: " + resource + " (" + e.getMessage() + ")");
      }
    }
    return null;
  }

  public static String getExtension(String name) {
    try {
      return TIKA_CONFIG.getMimeRepository().forName(name).getExtension();
    }
    catch (MimeTypeException e) {
      if (logger.isTraceEnabled()) {
        logger.trace("Get Extension fail... from: " + name, e);
      }
      else if (logger.isWarnEnabled()) {
        logger.warn("Get Extension fail... from: " + name + " (" + e.getMessage() + ")");
      }
      return null;
    }
  }

  private static String getDetect(InputStream inputStream, String filename) throws IOException {
    return StringUtils.hasText(filename) ? TIKA.detect(inputStream, filename) : TIKA.detect(inputStream);
  }

  // private static String getDetect(byte[] data, String filename) throws IOException {
  // return StringUtils.hasText(filename) ? TIKA.detect(data, filename) :
  // TIKA.detect(data);
  // }

  /**
   * 
   * https://issues.liferay.com/browse/LPS-62517
   * 
* * {@code "org/springframework/mail/javamail/mime.types"} * @see org.springframework.core.io.ClassPathResource#ClassPathResource(String) * @see javax.activation.MimetypesFileTypeMap#MimetypesFileTypeMap(InputStream) * @see javax.imageio.ImageIO#createImageInputStream(Object) * @see javax.imageio.ImageIO#getImageReaders(Object) * @see javax.imageio.ImageReader#getFormatName() */ public static MediaType getMediaType(Resource resource) { try (InputStream inputStream = resource.getInputStream()) { String detect = getDetect(inputStream, resource.getFilename()); return MediaType.parseMediaType(detect); } catch (IOException | InvalidMediaTypeException e) { if (logger.isTraceEnabled()) { logger.trace("Get MediaType fail... from: " + resource, e); } else if (logger.isWarnEnabled()) { logger.warn("Get MediaType fail... from: " + resource + " (" + e.getMessage() + ")"); } return MediaType.APPLICATION_OCTET_STREAM; } } /** * @see java.nio.file.Files#probeContentType(java.nio.file.Path) * @see javax.activation.MimetypesFileTypeMap#getContentType(File) * @see java.net.URLConnection#guessContentTypeFromName(String) * @see java.net.URLConnection#guessContentTypeFromStream(InputStream) */ public static MediaType getMediaType(String filename) { try { return MediaType.parseMediaType(FILE_TYPE_MAP.getContentType(filename)); } catch (InvalidMediaTypeException e) { if (logger.isTraceEnabled()) { logger.trace("Get MediaType fail... from: " + filename, e); } else if (logger.isWarnEnabled()) { logger.warn("Get MediaType fail... from: " + filename + " (" + e.getMessage() + ")"); } return MediaType.APPLICATION_OCTET_STREAM; } } public static String getChecksum(File file) { try { Assert.notNull(file, "'file' must not be null"); Assert.isTrue(file.exists() && file.isFile(), "'file' must be exists and file"); return DigestUtils.md5DigestAsHex(FileCopyUtils.copyToByteArray(file)); } catch (IOException | IllegalArgumentException e) { if (logger.isTraceEnabled()) { logger.trace("Get Checksum fail...", e); } else if (logger.isWarnEnabled()) { logger.warn("Get Checksum fail... (" + e.getMessage() + ")"); } return null; } } public static Collection getFiles(File file, FileFilter filter) { Assert.notNull(file, "'file' must not be null"); Assert.notNull(filter, "'filter' must not be null"); Collection collection = new LinkedHashSet(); File[] files = file.listFiles(filter); if (files == null || files.length == 0) { return Collections.emptySet(); } for (File listFile : files) { if (listFile.isDirectory()) { collection.addAll(getFiles(listFile, filter)); } else { collection.add(listFile); } } return collection; } public static boolean isValid(File parent, File file) { try { parent = parent.getCanonicalFile(); file = file.getCanonicalFile(); while (!(file == null)) { if (parent.equals(file)) { return true; } file = file.getParentFile(); } } catch (IOException e) { if (logger.isTraceEnabled()) { logger.trace("Not valid... parent: " + parent + ", file: " + file, e); } else if (logger.isWarnEnabled()) { logger.warn("Not valid... parent: " + parent + ", file: " + file + " (" + e.getMessage() + ")"); } } return false; } public static String getRelativize(File path, File file) { Assert.isTrue(isValid(path, file), "file valid is false"); try { return '/' + path.getCanonicalFile().toURI().relativize(file.getCanonicalFile().toURI()).getPath(); } catch (IOException e) { throw new IllegalStateException(e); } } // public static File getUploadFile(MultipartFile multipartFile, File path, String // filename, String... pathSegments) { // path = ApplicationUtil.getFile(path, pathSegments); // path = ApplicationUtil.getFile(path, filename); // return getUploadFile(multipartFile, path, true); // } public static File getUploadFile(MultipartFile multipartFile, File file) { return getUploadFile(multipartFile, file, true); } /** * @see org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.StandardMultipartFile * @see org.springframework.web.multipart.commons.CommonsMultipartFile#transferTo(File) * @see org.springframework.util.StreamUtils#copy(InputStream, OutputStream) */ public static File getUploadFile(MultipartFile multipartFile, File file, boolean rename) { Assert.isTrue(multipartFile != null && !multipartFile.isEmpty(), "MultipartFile must not be null..." + multipartFile); Assert.isTrue(file != null && !file.isDirectory() && file.getParentFile() != null && (file.getParentFile().mkdirs() || file.getParentFile().isDirectory()), "Create Directory fail..." + file); if (rename) { file = createRenameFile(file); } else { Assert.isTrue(!file.exists()); } try (InputStream inputStream = multipartFile.getInputStream(); OutputStream outputStream = new FileOutputStream(file)) { StreamUtils.copy(inputStream, outputStream); // FileCopyUtils.copy(inputStream, outputStream); } catch (IOException e) { throw new IllegalStateException(e); } if (logger.isTraceEnabled()) { logger.trace("file upload" + file); } return file; } // public static File createTempFile(Resource resource) { // File directory = ConstantUtil.getUserHome(ConstantUtil.DIRECTORY_TEMP); // Assert.isTrue(directory != null && (directory.mkdirs() || directory.isDirectory()), // "Create Directory fail... " + directory); // // String filename = resource.getFilename(); // String extension = StringUtils.getFilenameExtension(filename); // // if (StringUtils.hasText(extension)) { // filename = filename.substring(0, filename.length() - extension.length() - 1); // extension = '.' + extension; // } // // StringBuilder stringBuilder = new StringBuilder(filename); // do { // stringBuilder.append('_'); // } // while (stringBuilder.length() < 3); // // try { // File file = File.createTempFile(new String(stringBuilder), extension, directory); // try (InputStream inputStream = resource.getInputStream(); OutputStream outputStream = // new FileOutputStream(file);) { // FileCopyUtils.copy(inputStream, outputStream); // return file; // } // } // catch (IOException e) { // throw new IllegalStateException(e); // } // } public static void mkdirs(File file) { Assert.isTrue(file != null && (file.mkdirs() || file.isDirectory()), "Create Directory fail... " + file); } public static void delete(File file) { Assert.notNull(file, "File is null..." + file); Assert.isTrue(file.delete() || !file.exists(), "File delete fail..." + file); } private static File createRenameFile(File file) { Assert.notNull(file); Assert.notNull(file.getParentFile()); String filename = file.getName(); String extension = StringUtils.getFilenameExtension(filename); if (StringUtils.hasText(extension)) { filename = filename.substring(0, filename.length() - extension.length() - 1); } int count = 1; while (file.exists()) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(filename); stringBuilder.append('('); stringBuilder.append(count); stringBuilder.append(')'); if (StringUtils.hasText(extension)) { stringBuilder.append('.'); stringBuilder.append(extension); } file = Paths.get(file.getParent(), new String(stringBuilder)).toFile(); count++; } return file; } // public static OutputStream getDownloadOutputStream(HttpServletRequest request, // HttpServletResponse response, String downloadFileName) { // OutputStream result = null; // response.setContentType("application/octet-stream; charset=UTF-8"); // try { // String userAgent = request.getHeader("User-Agent"); // if (StringUtils.isEmpty(userAgent)) // return null; // if (userAgent.indexOf("MSIE 5.5") > -1) { // response.setHeader("Content-Disposition", "filename=" + // URLEncoder.encode(downloadFileName, "UTF-8") + ";"); // } else if (userAgent.indexOf("MSIE") > -1) { // response.setHeader("Content-Disposition", "attachment; filename=" + // java.net.URLEncoder.encode(downloadFileName, "UTF-8").replace("+", " ") // + ";"); // } else { // response.setHeader("Content-Disposition", "attachment; filename=\"" + new // String(downloadFileName.getBytes("UTF-8"), "ISO-8859-1") + "\";"); // } // response.setHeader("Content-Transfer-Encoding", "binary"); // result = response.getOutputStream(); // } catch (IOException ex) { // throw new RuntimeException(ex); // } // return result; // } // // public static void download(File file, String fileName, HttpServletRequest request, // HttpServletResponse response) { // FileInputStream fis = null; // try { // fis = new FileInputStream(file); // download(fis, fileName, request, response); // } catch (IOException e) { // throw new RuntimeException(String.format("file(%s) download error.., message:%s", // file.getAbsolutePath(), e.getMessage()), e); // } finally { // if (fis != null) // try { // fis.close(); // } catch (IOException ex) { // } // } // } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy