1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package net.sf.jasperreports.jsf.resource;
20
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.net.URL;
24
25 public final class ClasspathResource implements Resource {
26
27 public static final String PREFIX = "classpath:";
28
29 private final String name;
30 private final ClassLoader classLoader;
31
32 protected ClasspathResource(final String name,
33 final ClassLoader classLoader) {
34 if (name == null || name.length() == 0) {
35 throw new IllegalArgumentException("'name' can't be empty or null");
36 }
37 if (classLoader == null) {
38 throw new IllegalArgumentException("'classLoader' can't ne null");
39 }
40
41 this.name = stripPrefix(name);
42 this.classLoader = classLoader;
43 }
44
45 public String getName() {
46 return name;
47 }
48
49 public String getSimpleName() {
50 int slash = name.lastIndexOf('/');
51 if (slash > 0) {
52 return name.substring(slash);
53 } else {
54 return name;
55 }
56 }
57
58 public InputStream getInputStream() throws IOException {
59 final URL location = classLoader.getResource(getName());
60 if (location == null) {
61 throwLocationNotFoundException();
62 }
63 return location.openStream();
64 }
65
66 public URL getLocation() throws IOException {
67 final URL location = classLoader.getResource(getName());
68 if (location == null) {
69 throwLocationNotFoundException();
70 }
71 return location;
72 }
73
74 public String getPath() {
75 final URL location = classLoader.getResource(getName());
76 if (location == null) {
77 throwLocationNotFoundException();
78 }
79 return location.getPath();
80 }
81
82 public String toString() {
83 StringBuilder str = new StringBuilder(PREFIX);
84 str.append(name);
85 return str.toString();
86 }
87
88 private void throwLocationNotFoundException() {
89 throw new ClasspathLocationNotFoundException(
90 "Resource location for classpath resource '" + getName()
91 + "' couldn't be identified.");
92 }
93
94 private static String stripPrefix(String resourceName) {
95 if (resourceName.startsWith(PREFIX)) {
96 return resourceName.substring(PREFIX.length());
97 }
98 return resourceName;
99 }
100
101 }