|
27 | 27 | import jakarta.activation.MimetypesFileTypeMap;
|
28 | 28 |
|
29 | 29 | import java.io.File;
|
| 30 | +import java.io.IOException; |
30 | 31 | import java.io.InputStream;
|
31 | 32 | import java.net.MalformedURLException;
|
32 | 33 | import java.net.URISyntaxException;
|
33 | 34 | import java.net.URL;
|
| 35 | +import java.nio.file.Files; |
| 36 | +import java.nio.file.InvalidPathException; |
| 37 | +import java.nio.file.Paths; |
34 | 38 | import java.util.*;
|
35 | 39 | import java.util.stream.Collectors;
|
36 | 40 |
|
@@ -160,23 +164,33 @@ public int getEffectiveMinorVersion() {
|
160 | 164 |
|
161 | 165 | @Override
|
162 | 166 | @SuppressFBWarnings("PATH_TRAVERSAL_IN") // suppressing because we are using the getValidFilePath
|
163 |
| - public String getMimeType(String s) { |
164 |
| - if (s == null || !s.contains(".")) { |
| 167 | + public String getMimeType(String file) { |
| 168 | + if (file == null || !file.contains(".")) { |
165 | 169 | return null;
|
166 | 170 | }
|
| 171 | + String mimeType = null; |
| 172 | + try { |
| 173 | + mimeType = Files.probeContentType(Paths.get(file)); |
| 174 | + } catch (IOException | InvalidPathException e) { |
| 175 | + log("unable to probe for content type, will use fallback", e); |
| 176 | + } |
| 177 | + |
| 178 | + // MimetypesFileTypeMap is kept for backwards compatibility, remove in 2.0 |
167 | 179 | if (mimeTypes == null) {
|
168 | 180 | mimeTypes = new MimetypesFileTypeMap();
|
169 | 181 | }
|
170 |
| - if (s.endsWith(".css")) { |
171 |
| - return "text/css"; |
| 182 | + String backwardsCompatibleMimeType = mimeTypes.getContentType(file); |
| 183 | + // The getContentType method of the MimetypesFileTypeMap |
| 184 | + // returns MimetypesFileTypeMap.defaultType = application/octet-stream |
| 185 | + // instead of null when the type cannot be found. |
| 186 | + if (mimeType == null || (backwardsCompatibleMimeType != null && !backwardsCompatibleMimeType.equals(mimeType) |
| 187 | + && !MediaType.APPLICATION_OCTET_STREAM.equals(backwardsCompatibleMimeType))) { |
| 188 | + log("using type " + backwardsCompatibleMimeType + " from MimetypesFileTypeMap for " + file |
| 189 | + + " instead of " + mimeType + " for backwards compatibility"); |
| 190 | + mimeType = backwardsCompatibleMimeType; |
172 | 191 | }
|
173 |
| - if (s.endsWith(".js")) { |
174 |
| - return "application/javascript"; |
175 |
| - } |
176 |
| - // TODO: The getContentType method of the MimetypesFileTypeMap returns application/octet-stream |
177 |
| - // instead of null when the type cannot be found. We should replace with an implementation that |
178 |
| - // loads the System mime types ($JAVA_HOME/lib/mime.types |
179 |
| - return mimeTypes.getContentType(s); |
| 192 | + |
| 193 | + return mimeType; |
180 | 194 | }
|
181 | 195 |
|
182 | 196 |
|
|
0 commit comments