| ServletVelocityResourceListener.java |
1 /**
2 * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
3 *
4 * The contents of this file are subject to the terms of the Liferay Enterprise
5 * Subscription License ("License"). You may not use this file except in
6 * compliance with the License. You can obtain a copy of the License by
7 * contacting Liferay, Inc. See the License for the specific language governing
8 * permissions and limitations under the License, including but not limited to
9 * distribution rights of the Software.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
13 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
14 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
15 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
16 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
17 * SOFTWARE.
18 */
19
20 package com.liferay.portal.velocity;
21
22 import com.liferay.portal.kernel.log.Log;
23 import com.liferay.portal.kernel.log.LogFactoryUtil;
24 import com.liferay.portal.kernel.util.Validator;
25 import com.liferay.portal.util.PortalUtil;
26
27 import java.io.ByteArrayInputStream;
28 import java.io.InputStream;
29
30 import javax.servlet.ServletContext;
31
32 import org.apache.velocity.exception.ResourceNotFoundException;
33
34 /**
35 * <a href="ServletVelocityResourceListener.java.html"><b><i>View Source</i></b>
36 * </a>
37 *
38 * @author Alexander Chow
39 *
40 */
41 public class ServletVelocityResourceListener extends VelocityResourceListener {
42
43 public InputStream getResourceStream(String source)
44 throws ResourceNotFoundException {
45
46 InputStream is = null;
47
48 int pos = source.indexOf(SERVLET_SEPARATOR);
49
50 if (pos != -1) {
51 String servletContextName = source.substring(0, pos);
52
53 if (Validator.isNull(servletContextName)) {
54 servletContextName = PortalUtil.getPathContext();
55 }
56
57 ServletContext servletContext = VelocityContextPool.get(
58 servletContextName);
59
60 if (servletContext != null) {
61 String name =
62 source.substring(pos + SERVLET_SEPARATOR.length());
63
64 if (_log.isDebugEnabled()) {
65 _log.debug(
66 name + " is associated with the servlet context " +
67 servletContextName + " " + servletContext);
68 }
69
70 is = servletContext.getResourceAsStream(name);
71
72 if ((is == null) && (name.endsWith("/init_custom.vm"))) {
73 if (_log.isWarnEnabled()) {
74 _log.warn(
75 "The template " + name + " should be created");
76 }
77
78 is = new ByteArrayInputStream(new byte[0]);
79 }
80 }
81 else {
82 _log.error(
83 source + " is not valid because " + servletContextName +
84 " does not map to a servlet context");
85 }
86 }
87
88 return is;
89 }
90
91 private static Log _log =
92 LogFactoryUtil.getLog(ServletVelocityResourceListener.class);
93
94 }