001
014
015 package com.liferay.portal.velocity;
016
017 import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayInputStream;
018 import com.liferay.portal.kernel.log.Log;
019 import com.liferay.portal.kernel.log.LogFactoryUtil;
020 import com.liferay.portal.kernel.servlet.ServletContextPool;
021 import com.liferay.portal.kernel.util.Validator;
022 import com.liferay.portal.util.PortalUtil;
023
024 import java.io.InputStream;
025
026 import javax.servlet.ServletContext;
027
028 import org.apache.velocity.exception.ResourceNotFoundException;
029
030
034 public class ServletVelocityResourceListener extends VelocityResourceListener {
035
036 @Override
037 public InputStream getResourceStream(String source)
038 throws ResourceNotFoundException {
039
040 try {
041 return doGetResourceStream(source);
042 }
043 catch (Exception e) {
044 throw new ResourceNotFoundException(source);
045 }
046 }
047
048 protected InputStream doGetResourceStream(String source) throws Exception {
049 int pos = source.indexOf(SERVLET_SEPARATOR);
050
051 if (pos == -1) {
052 return null;
053 }
054
055 String servletContextName = source.substring(0, pos);
056
057 if (Validator.isNull(servletContextName)) {
058 servletContextName = PortalUtil.getPathContext();
059 }
060
061 ServletContext servletContext = ServletContextPool.get(
062 servletContextName);
063
064 if (servletContext == null) {
065 _log.error(
066 source + " is not valid because " + servletContextName +
067 " does not map to a servlet context");
068
069 return null;
070 }
071
072 String name = source.substring(pos + SERVLET_SEPARATOR.length());
073
074 if (_log.isDebugEnabled()) {
075 _log.debug(
076 name + " is associated with the servlet context " +
077 servletContextName + " " + servletContext);
078 }
079
080 InputStream inputStream = servletContext.getResourceAsStream(name);
081
082 if ((inputStream == null) && name.endsWith("/init_custom.vm")) {
083 if (_log.isWarnEnabled()) {
084 _log.warn("The template " + name + " should be created");
085 }
086
087 return new UnsyncByteArrayInputStream(new byte[0]);
088 }
089 else {
090 return inputStream;
091 }
092 }
093
094 private static Log _log = LogFactoryUtil.getLog(
095 ServletVelocityResourceListener.class);
096
097 }