001
014
015 package com.liferay.portal.servlet.filters.aggregate;
016
017 import com.liferay.portal.kernel.log.Log;
018 import com.liferay.portal.kernel.log.LogFactoryUtil;
019 import com.liferay.portal.kernel.servlet.ServletContextUtil;
020 import com.liferay.portal.kernel.util.StringBundler;
021 import com.liferay.portal.kernel.util.StringPool;
022 import com.liferay.portal.kernel.util.StringUtil;
023 import com.liferay.portal.kernel.util.Validator;
024
025 import java.io.IOException;
026
027 import java.net.URL;
028 import java.net.URLConnection;
029
030 import java.util.Stack;
031
032 import javax.servlet.ServletContext;
033
034
037 public class ServletAggregateContext implements AggregateContext {
038
039 public ServletAggregateContext(
040 ServletContext servletContext, String resourcePath)
041 throws IOException {
042
043 _servletContext = servletContext;
044
045 String rootPath = ServletContextUtil.getRootPath(_servletContext);
046
047 int pos = resourcePath.lastIndexOf(StringPool.SLASH);
048
049 if (pos > 0) {
050 resourcePath = resourcePath.substring(0, resourcePath.length() - 1);
051 }
052
053 pos = resourcePath.lastIndexOf(StringPool.SLASH);
054
055 resourcePath = resourcePath.substring(0, pos);
056
057 pos = resourcePath.lastIndexOf(rootPath);
058
059 if (pos == 0) {
060 resourcePath = resourcePath.substring(rootPath.length());
061 }
062
063 _stack.push(resourcePath);
064 }
065
066 public String getContent(String path) {
067 try {
068 String stackPath = _generatePathFromStack();
069
070 URL resourceURL = _servletContext.getResource(
071 stackPath.concat(path));
072
073 if (resourceURL == null) {
074 return null;
075 }
076
077 URLConnection urlConnection = resourceURL.openConnection();
078
079 return StringUtil.read(urlConnection.getInputStream());
080 }
081 catch (IOException ioe) {
082 _log.error(ioe, ioe);
083 }
084
085 return null;
086 }
087
088 public String getFullPath(String path) {
089 String stackPath = _generatePathFromStack();
090
091 return stackPath.concat(path);
092 }
093
094 public void popPath(String path) {
095 if (Validator.isNotNull(path)) {
096 _stack.pop();
097 }
098 }
099
100 public void pushPath(String path) {
101 if (Validator.isNotNull(path)) {
102 _stack.push(path);
103 }
104 }
105
106 private String _generatePathFromStack() {
107 StringBundler sb = new StringBundler();
108
109 for (String path : _stack) {
110 sb.append(path);
111
112 if (!path.endsWith(StringPool.SLASH)) {
113 sb.append(StringPool.SLASH);
114 }
115 }
116
117 return StringUtil.replace(
118 sb.toString(), StringPool.DOUBLE_SLASH, StringPool.SLASH);
119 }
120
121 private static Log _log = LogFactoryUtil.getLog(
122 ServletAggregateContext.class);
123
124 private ServletContext _servletContext;
125 private Stack<String> _stack = new Stack<String>();
126
127 }