001
014
015 package com.liferay.portal.kernel.util;
016
017 import com.liferay.portal.kernel.concurrent.ConcurrentReferenceValueHashMap;
018 import com.liferay.portal.kernel.memory.FinalizeManager;
019
020 import java.util.Map;
021 import java.util.regex.Matcher;
022 import java.util.regex.Pattern;
023
024
028 public class StringParserFragment {
029
030 public static StringParserFragment create(String chunk) {
031 StringParserFragment stringParserFragment = _stringParserFragments.get(
032 chunk);
033
034 if (stringParserFragment == null) {
035 stringParserFragment = new StringParserFragment(chunk);
036
037 _stringParserFragments.put(chunk, stringParserFragment);
038 }
039
040 return stringParserFragment;
041 }
042
043 public String getName() {
044 return _name;
045 }
046
047 public String getPattern() {
048 return _pattern.toString();
049 }
050
051 public String getToken() {
052 return _token;
053 }
054
055 public boolean isRaw() {
056 return _raw;
057 }
058
059 public boolean matches(String parameter) {
060 Matcher matcher = _pattern.matcher(parameter);
061
062 return matcher.matches();
063 }
064
065 protected StringParserFragment(String fragment) {
066 if ((fragment == null) || (fragment.length() < 3)) {
067 throw new IllegalArgumentException(
068 "Fragment is invalid: " + fragment);
069 }
070
071 int index = fragment.indexOf(CharPool.COLON);
072
073 String name = null;
074
075 if (index < 0) {
076 name = fragment.substring(1, fragment.length() - 1);
077
078 _pattern = _defaultPattern;
079 }
080 else {
081 name = fragment.substring(1, index);
082 String pattern = fragment.substring(
083 index + 1, fragment.length() - 1);
084
085 if (Validator.isNull(pattern)) {
086 throw new IllegalArgumentException(
087 "Pattern is null: " + fragment);
088 }
089
090 _pattern = Pattern.compile(pattern);
091 }
092
093 if (name.isEmpty()) {
094 throw new IllegalArgumentException("Name is null: " + fragment);
095 }
096
097 if (name.charAt(0) == CharPool.PERCENT) {
098 name = name.substring(1);
099
100 if (name.isEmpty()) {
101 throw new IllegalArgumentException(
102 "Name is invalid: " + fragment);
103 }
104
105 _raw = true;
106 }
107 else {
108 _raw = false;
109 }
110
111 _name = name;
112
113 _token = StringPool.OPEN_CURLY_BRACE.concat(_name).concat(
114 StringPool.CLOSE_CURLY_BRACE);
115 }
116
117 private static final Pattern _defaultPattern = Pattern.compile("[^/\\.]+");
118 private static final Map<String, StringParserFragment>
119 _stringParserFragments = new ConcurrentReferenceValueHashMap<>(
120 FinalizeManager.SOFT_REFERENCE_FACTORY);
121
122 private final String _name;
123 private final Pattern _pattern;
124 private final boolean _raw;
125 private final String _token;
126
127 }