From c3f5719f553ba180b86daa9c86bf1200bc3bbe6c Mon Sep 17 00:00:00 2001 From: sbeimin Date: Wed, 27 Dec 2017 12:51:37 +0100 Subject: [PATCH] Implemented FileTypeDetector to return contentType from Metadata --- .../upplication/s3fs/S3FileTypeDetector.java | 21 +++++++++++++++++++ .../com/upplication/s3fs/util/S3Utils.java | 14 +++++++++++++ .../java.nio.file.spi.FileTypeDetector | 1 + 3 files changed, 36 insertions(+) create mode 100644 src/main/java/com/upplication/s3fs/S3FileTypeDetector.java create mode 100644 src/main/resources/META-INF/services/java.nio.file.spi.FileTypeDetector diff --git a/src/main/java/com/upplication/s3fs/S3FileTypeDetector.java b/src/main/java/com/upplication/s3fs/S3FileTypeDetector.java new file mode 100644 index 0000000..cbe4ae2 --- /dev/null +++ b/src/main/java/com/upplication/s3fs/S3FileTypeDetector.java @@ -0,0 +1,21 @@ +package com.upplication.s3fs; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.spi.FileTypeDetector; + +import com.amazonaws.services.s3.model.ObjectMetadata; +import com.upplication.s3fs.util.S3Utils; + +public class S3FileTypeDetector extends FileTypeDetector { + @Override + public String probeContentType(Path path) throws IOException { + if (path instanceof S3Path) { + S3Path s3Path = (S3Path) path; + ObjectMetadata metadata = S3Utils.getObjectMetadata(s3Path); + if (metadata != null) + return metadata.getContentType(); + } + return null; + } +} diff --git a/src/main/java/com/upplication/s3fs/util/S3Utils.java b/src/main/java/com/upplication/s3fs/util/S3Utils.java index aff084f..d757b05 100644 --- a/src/main/java/com/upplication/s3fs/util/S3Utils.java +++ b/src/main/java/com/upplication/s3fs/util/S3Utils.java @@ -21,6 +21,20 @@ */ public class S3Utils { + public static ObjectMetadata getObjectMetadata(S3Path s3Path) { + String key = s3Path.getKey(); + String bucketName = s3Path.getFileStore().name(); + AmazonS3 client = s3Path.getFileSystem().getClient(); + // try to find the element with the current key (maybe with end slash or maybe not.) + try { + return client.getObjectMetadata(bucketName, key); + } catch (AmazonS3Exception e) { + if (e.getStatusCode() != 404) + throw e; + } + return null; + } + /** * Get the {@link S3ObjectSummary} that represent this Path or her first child if this path not exists * diff --git a/src/main/resources/META-INF/services/java.nio.file.spi.FileTypeDetector b/src/main/resources/META-INF/services/java.nio.file.spi.FileTypeDetector new file mode 100644 index 0000000..f729399 --- /dev/null +++ b/src/main/resources/META-INF/services/java.nio.file.spi.FileTypeDetector @@ -0,0 +1 @@ +com.upplication.s3fs.S3FileTypeDetector