org.springframework.util.MediaTypeUtils Maven / Gradle / Ivy
package org.springframework.util;
import java.io.IOException;
import java.io.InputStream;
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.springframework.core.io.Resource;
import org.springframework.http.InvalidMediaTypeException;
import org.springframework.http.MediaType;
public class MediaTypeUtils {
private static final Log logger = LogFactory.getLog(MediaTypeUtils.class);
private static final TikaConfig TIKA_CONFIG = TikaConfig.getDefaultConfig();
private static final Tika TIKA = new Tika(TIKA_CONFIG);
/**
*
* 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 parseMediaType(Resource resource) {
return parseMediaType(resource, MediaType.APPLICATION_OCTET_STREAM);
}
public static MediaType parseMediaType(Resource resource, MediaType fallback) {
try (InputStream inputStream = resource.getInputStream()) {
String detect = detect(inputStream, resource.getFilename());
return MediaType.parseMediaType(detect);
}
catch (IOException | InvalidMediaTypeException e) {
if (fallback == null) {
throw new IllegalStateException(e);
}
if (logger.isWarnEnabled()) {
logger.warn("parse MediaType fail... from: " + resource + " (" + e + ")");
}
return fallback;
}
}
private static String detect(InputStream inputStream, String filename) throws IOException {
return StringUtils.hasText(filename) ? TIKA.detect(inputStream, filename) : TIKA.detect(inputStream);
}
}