-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathClasspathResourceHandler.java
More file actions
50 lines (43 loc) · 1.44 KB
/
Copy pathClasspathResourceHandler.java
File metadata and controls
50 lines (43 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.retailsvc.http.internal;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
/**
* Eagerly-loaded bytes for a classpath resource. Content-Type is inferred from the file extension.
* Throws {@link IllegalArgumentException} if the resource is missing.
*/
public final class ClasspathResourceHandler {
private final byte[] bytes;
private final String contentType;
public ClasspathResourceHandler(String classpathResource) {
try (InputStream in = ClasspathResourceHandler.class.getResourceAsStream(classpathResource)) {
if (in == null) {
throw new IllegalArgumentException("classpath resource not found: " + classpathResource);
}
this.bytes = in.readAllBytes();
} catch (IOException io) {
throw new IllegalArgumentException(
"failed reading classpath resource: " + classpathResource, io);
}
this.contentType = contentTypeFor(classpathResource);
}
public byte[] bytes() {
return bytes;
}
public String contentType() {
return contentType;
}
private static String contentTypeFor(String path) {
String lower = path.toLowerCase(Locale.ROOT);
if (lower.endsWith(".json")) {
return "application/json";
}
if (lower.endsWith(".yaml") || lower.endsWith(".yml")) {
return "application/yaml";
}
if (lower.endsWith(".txt")) {
return "text/plain; charset=utf-8";
}
return "application/octet-stream";
}
}