001
014
015 package com.liferay.portal.template;
016
017 import com.liferay.portal.kernel.template.TemplateException;
018 import com.liferay.portal.kernel.template.TemplateResource;
019 import com.liferay.portal.kernel.template.URLTemplateResource;
020 import com.liferay.portal.kernel.util.CharPool;
021 import com.liferay.portal.kernel.util.StringPool;
022 import com.liferay.portal.kernel.util.StringUtil;
023
024 import java.io.IOException;
025
026 import java.net.URL;
027
028 import java.util.ArrayList;
029 import java.util.List;
030
031
034 public abstract class URLResourceParser implements TemplateResourceParser {
035
036 @Override
037 public TemplateResource getTemplateResource(String templateId)
038 throws TemplateException {
039
040 templateId = normalizePath(templateId);
041
042 try {
043 URL url = getURL(templateId);
044
045 if (url == null) {
046 return null;
047 }
048
049 return new URLTemplateResource(templateId, url);
050 }
051 catch (IOException ioe) {
052 throw new TemplateException(ioe);
053 }
054 }
055
056 public abstract URL getURL(String templateId) throws IOException;
057
058 protected static String normalizePath(String path) {
059 List<String> elements = new ArrayList<String>();
060
061 boolean absolutePath = false;
062
063 int previousIndex = -1;
064
065 for (int index;
066 (index = path.indexOf(CharPool.SLASH, previousIndex + 1)) != -1;
067 previousIndex = index) {
068
069 if ((previousIndex + 1) == index) {
070
071
072
073 if (previousIndex == -1) {
074 absolutePath = true;
075
076 continue;
077 }
078
079
080
081 throw new IllegalArgumentException(
082 "Unable to parse path " + path);
083 }
084
085 String pathElement = path.substring(previousIndex + 1, index);
086
087
088
089 if (pathElement.equals(StringPool.PERIOD)) {
090 continue;
091 }
092
093
094
095 if (pathElement.equals(StringPool.DOUBLE_PERIOD)) {
096 if (elements.isEmpty()) {
097 throw new IllegalArgumentException(
098 "Unable to parse path " + path);
099 }
100
101 elements.remove(elements.size() - 1);
102
103 continue;
104 }
105
106
107
108 elements.add(pathElement);
109 }
110
111 if (previousIndex == -1) {
112 elements.add(path);
113 }
114 else if ((previousIndex + 1) < path.length()) {
115 elements.add(path.substring(previousIndex + 1));
116 }
117
118 String normalizedPath = StringUtil.merge(elements, StringPool.SLASH);
119
120 if (absolutePath) {
121 normalizedPath = StringPool.SLASH.concat(normalizedPath);
122 }
123
124 return normalizedPath;
125 }
126
127 }