001
014
015 package com.liferay.util.bridges.php;
016
017 import com.caucho.vfs.FilesystemPath;
018 import com.caucho.vfs.Path;
019 import com.caucho.vfs.StreamImpl;
020 import com.caucho.vfs.VfsStream;
021
022 import com.liferay.portal.kernel.servlet.ServletContextUtil;
023 import com.liferay.portal.kernel.util.StringPool;
024 import com.liferay.portal.kernel.util.Validator;
025
026 import java.io.FileNotFoundException;
027 import java.io.IOException;
028
029 import java.net.MalformedURLException;
030 import java.net.URI;
031 import java.net.URL;
032
033 import java.util.Map;
034
035 import javax.servlet.ServletContext;
036
037
040 public class ServletContextPath extends FilesystemPath {
041
042 public ServletContextPath(ServletContext servletContext) {
043 super(null, StringPool.SLASH, StringPool.SLASH);
044
045 _servletContext = servletContext;
046
047 _root = this;
048
049 try {
050 _rootURI = ServletContextUtil.getRootURI(_servletContext);
051 }
052 catch (MalformedURLException murle) {
053 throw new IllegalStateException();
054 }
055
056 _useRootURI = true;
057 }
058
059 @Override
060 public boolean canRead() {
061 return true;
062 }
063
064 @Override
065 public Path fsWalk(
066 String userPath, Map<String, Object> newAttributes, String path) {
067
068 String authority = _rootURI.getAuthority();
069
070 if (Validator.isNotNull(authority)) {
071 int index = path.indexOf(authority);
072
073 if (index != -1) {
074 path = path.substring(index + authority.length());
075 }
076 }
077
078 return new ServletContextPath(_root, userPath, path, _servletContext);
079 }
080
081 @Override
082 public String getScheme() {
083 if (_useRootURI) {
084 return _rootURI.getScheme();
085 }
086
087 return "file";
088 }
089
090 @Override
091 public StreamImpl openReadImpl() throws IOException {
092 String path = getPath();
093
094 URL url = _servletContext.getResource(path);
095
096 if (url == null) {
097 throw new FileNotFoundException(getFullPath());
098 }
099
100 return new VfsStream(url.openStream(), null);
101 }
102
103 protected ServletContextPath(
104 FilesystemPath root, String userPath, String path,
105 ServletContext servletContext) {
106
107 super(root, userPath, path);
108
109 _servletContext = servletContext;
110
111 try {
112 _rootURI = ServletContextUtil.getRootURI(_servletContext);
113 }
114 catch (MalformedURLException murle) {
115 throw new IllegalStateException();
116 }
117
118 _useRootURI = userPath.startsWith(_rootURI.toString());
119 }
120
121 private URI _rootURI;
122 private ServletContext _servletContext;
123 private boolean _useRootURI;
124
125 }