001
014
015 package com.liferay.util;
016
017 import com.liferay.portal.kernel.util.CharPool;
018 import com.liferay.portal.kernel.util.StringBundler;
019 import com.liferay.portal.kernel.util.StringPool;
020 import com.liferay.portal.kernel.util.StringUtil;
021 import com.liferay.portal.kernel.util.UnicodeFormatter;
022
023 import java.net.URLDecoder;
024 import java.net.URLEncoder;
025
026 import java.util.regex.Matcher;
027 import java.util.regex.Pattern;
028
029
033 public class JS {
034
035 public static String decodeURIComponent(String s) {
036
037
038
039 Matcher matcher = _pattern.matcher(s);
040
041 s = matcher.replaceAll(StringPool.BLANK);
042
043
044
045 s = StringUtil.replace(s, "+", "%2B");
046 s = StringUtil.replace(s, "%20", "+");
047
048
049
050 try {
051 s = URLDecoder.decode(s, StringPool.UTF8);
052 }
053 catch (Exception e) {
054 }
055
056 return s;
057 }
058
059 public static String encodeURIComponent(String s) {
060
061
062
063 try {
064 s = URLEncoder.encode(s, StringPool.UTF8);
065 }
066 catch (Exception e) {
067 }
068
069
070
071 s = StringUtil.replace(s, "+", "%20");
072 s = StringUtil.replace(s, "%2B", "+");
073
074 return s;
075 }
076
077
080 @Deprecated
081 public static String escape(String s) {
082 return encodeURIComponent(s);
083 }
084
085 public static String getSafeName(String name) {
086 if (name == null) {
087 return null;
088 }
089
090 StringBuilder sb = null;
091
092 int index = 0;
093
094 for (int i = 0; i < name.length(); i++) {
095 char c = name.charAt(i);
096
097 switch (c) {
098 case CharPool.SPACE:
099
100 case CharPool.DASH:
101
102 case CharPool.PERIOD:
103 if (sb == null) {
104 sb = new StringBuilder(name.length() - 1);
105
106 sb.append(name, index, i);
107 }
108
109 break;
110
111 default:
112 if (sb != null) {
113 sb.append(c);
114 }
115 }
116 }
117
118 if (sb == null) {
119 return name;
120 }
121 else {
122 return sb.toString();
123 }
124 }
125
126 public static String toScript(String[] array) {
127 StringBundler sb = new StringBundler(array.length * 4 + 2);
128
129 sb.append(StringPool.OPEN_BRACKET);
130
131 for (int i = 0; i < array.length; i++) {
132 sb.append(StringPool.APOSTROPHE);
133 sb.append(UnicodeFormatter.toString(array[i]));
134 sb.append(StringPool.APOSTROPHE);
135
136 if ((i + 1) < array.length) {
137 sb.append(StringPool.COMMA);
138 }
139 }
140
141 sb.append(StringPool.CLOSE_BRACKET);
142
143 return sb.toString();
144 }
145
146
149 @Deprecated
150 public static String unescape(String s) {
151 return decodeURIComponent(s);
152 }
153
154 private static final Pattern _pattern = Pattern.compile("%u[0-9a-fA-F]{4}");
155
156 }