1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.myfaces.view.facelets.util;
20
21 import java.io.FileNotFoundException;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.net.MalformedURLException;
25 import java.net.URL;
26 import java.net.URLConnection;
27 import java.net.URLStreamHandler;
28 import java.util.logging.Level;
29 import java.util.logging.Logger;
30
31 import javax.faces.context.ExternalContext;
32 import javax.faces.context.FacesContext;
33 import javax.servlet.ServletContext;
34
35
36
37
38
39 public final class Resource
40 {
41
42
43 protected final static Logger log = Logger.getLogger(Resource.class.getName());
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61 public static URL getResourceUrl(FacesContext ctx, String path) throws MalformedURLException
62 {
63 final ExternalContext externalContext = ctx.getExternalContext();
64 URL url = externalContext.getResource(path);
65 if (log.isLoggable(Level.FINE))
66 {
67 log.fine("Resource-Url from external context: " + url);
68 }
69 if (url == null)
70 {
71
72
73
74
75
76
77
78 if (resourceExist(externalContext, path))
79 {
80 url = getUrlForResourceAsStream(externalContext, path);
81 }
82 }
83 return url;
84 }
85
86
87
88
89 private static boolean resourceExist(ExternalContext externalContext, String path)
90 {
91 if ("/".equals(path))
92 {
93
94 return true;
95 }
96 Object ctx = externalContext.getContext();
97 if (ctx instanceof ServletContext)
98 {
99 ServletContext servletContext = (ServletContext) ctx;
100 InputStream stream = servletContext.getResourceAsStream(path);
101 if (stream != null)
102 {
103 try
104 {
105 stream.close();
106 }
107 catch (IOException e)
108 {
109
110
111 }
112 return true;
113 }
114 }
115 return false;
116 }
117
118
119
120 private static URL getUrlForResourceAsStream(final ExternalContext externalContext, String path)
121 throws MalformedURLException
122 {
123 URLStreamHandler handler = new URLStreamHandler()
124 {
125 protected URLConnection openConnection(URL u) throws IOException
126 {
127 final String file = u.getFile();
128 return new URLConnection(u)
129 {
130 public void connect() throws IOException
131 {
132 }
133
134 public InputStream getInputStream() throws IOException
135 {
136 if (log.isLoggable(Level.FINE))
137 {
138 log.fine("Opening internal url to " + file);
139 }
140 Object ctx = externalContext.getContext();
141
142
143
144
145 if (ctx instanceof ServletContext)
146 {
147 ServletContext servletContext = (ServletContext) ctx;
148 InputStream stream = servletContext.getResourceAsStream(file);
149 if (stream == null)
150 {
151 throw new FileNotFoundException("Cannot open resource " + file);
152 }
153 return stream;
154 }
155 else
156 {
157 throw new IOException("Cannot open resource for an context of "
158 + (ctx != null ? ctx.getClass() : null));
159 }
160 }
161 };
162 }
163 };
164 return new URL("internal", null, 0, path, handler);
165 }
166 }