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.InputStream;
22 import java.net.MalformedURLException;
23 import java.net.URL;
24
25 import javax.faces.context.FacesContext;
26
27 import net.sf.jasperreports.jsf.context.ExternalContextHelper;
28 import net.sf.jasperreports.jsf.context.JRFacesContext;
29
30
31
32
33 public final class ContextResource implements Resource {
34
35 private final String name;
36
37
38
39
40
41
42 protected ContextResource(final String name) {
43 if (name == null || name.length() == 0) {
44 throw new IllegalArgumentException("'name' can't be empty or null");
45 }
46 this.name = name;
47 }
48
49 public String getName() {
50 return name;
51 }
52
53 public String getSimpleName() {
54 int slash = name.lastIndexOf('/');
55 if (slash > 0) {
56 return name.substring(slash);
57 } else {
58 return name;
59 }
60 }
61
62
63
64
65
66
67
68
69 public URL getLocation() throws MalformedURLException {
70 return getFacesContext().getExternalContext().getResource(getName());
71 }
72
73
74
75
76
77
78
79
80 public InputStream getInputStream() {
81 return getFacesContext()
82 .getExternalContext().getResourceAsStream(getName());
83 }
84
85 public String getPath() {
86 ExternalContextHelper helper = getJRFacesContext()
87 .getExternalContextHelper(getFacesContext());
88 return helper.getResourceRealPath(
89 getFacesContext().getExternalContext(), getName());
90 }
91
92 public String toString() {
93 return name;
94 }
95
96 protected FacesContext getFacesContext() {
97 FacesContext context = FacesContext.getCurrentInstance();
98 if (context == null) {
99 throw new IllegalStateException("Context reosurces are valid just " +
100 "inside a Faces' request.");
101 }
102 return context;
103 }
104
105 protected JRFacesContext getJRFacesContext() {
106 return JRFacesContext.getInstance(getFacesContext());
107 }
108
109 }