|
23 | 23 | import javax.activation.MimetypesFileTypeMap;
|
24 | 24 | import javax.servlet.*;
|
25 | 25 | import javax.servlet.descriptor.JspConfigDescriptor;
|
| 26 | +import javax.ws.rs.core.MediaType; |
26 | 27 |
|
27 | 28 | import java.io.File;
|
| 29 | +import java.io.IOException; |
28 | 30 | import java.io.InputStream;
|
29 | 31 | import java.net.MalformedURLException;
|
30 | 32 | import java.net.URISyntaxException;
|
31 | 33 | import java.net.URL;
|
| 34 | +import java.nio.file.Files; |
| 35 | +import java.nio.file.InvalidPathException; |
| 36 | +import java.nio.file.Paths; |
32 | 37 | import java.util.*;
|
33 | 38 | import java.util.stream.Collectors;
|
34 | 39 |
|
@@ -129,23 +134,33 @@ public int getEffectiveMinorVersion() {
|
129 | 134 |
|
130 | 135 | @Override
|
131 | 136 | @SuppressFBWarnings("PATH_TRAVERSAL_IN") // suppressing because we are using the getValidFilePath
|
132 |
| - public String getMimeType(String s) { |
133 |
| - if (s == null || !s.contains(".")) { |
| 137 | + public String getMimeType(String file) { |
| 138 | + if (file == null || !file.contains(".")) { |
134 | 139 | return null;
|
135 | 140 | }
|
| 141 | + String mimeType = null; |
| 142 | + try { |
| 143 | + mimeType = Files.probeContentType(Paths.get(file)); |
| 144 | + } catch (IOException | InvalidPathException e) { |
| 145 | + log("unable to probe for content type, will use fallback", e); |
| 146 | + } |
| 147 | + |
| 148 | + // MimetypesFileTypeMap is kept for backwards compatibility, remove in 2.0 |
136 | 149 | if (mimeTypes == null) {
|
137 | 150 | mimeTypes = new MimetypesFileTypeMap();
|
138 | 151 | }
|
139 |
| - if (s.endsWith(".css")) { |
140 |
| - return "text/css"; |
| 152 | + String backwardsCompatibleMimeType = mimeTypes.getContentType(file); |
| 153 | + // The getContentType method of the MimetypesFileTypeMap |
| 154 | + // returns MimetypesFileTypeMap.defaultType = application/octet-stream |
| 155 | + // instead of null when the type cannot be found. |
| 156 | + if (mimeType == null || (backwardsCompatibleMimeType != null && !backwardsCompatibleMimeType.equals(mimeType) |
| 157 | + && !MediaType.APPLICATION_OCTET_STREAM.equals(backwardsCompatibleMimeType))) { |
| 158 | + log("using type " + backwardsCompatibleMimeType + " from MimetypesFileTypeMap for " + file |
| 159 | + + " instead of " + mimeType + " for backwards compatibility"); |
| 160 | + mimeType = backwardsCompatibleMimeType; |
141 | 161 | }
|
142 |
| - if (s.endsWith(".js")) { |
143 |
| - return "application/javascript"; |
144 |
| - } |
145 |
| - // TODO: The getContentType method of the MimetypesFileTypeMap returns application/octet-stream |
146 |
| - // instead of null when the type cannot be found. We should replace with an implementation that |
147 |
| - // loads the System mime types ($JAVA_HOME/lib/mime.types |
148 |
| - return mimeTypes.getContentType(s); |
| 162 | + |
| 163 | + return mimeType; |
149 | 164 | }
|
150 | 165 |
|
151 | 166 |
|
|
0 commit comments