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
030 public class JS {
031
032 public static String decodeURIComponent(String s) {
033
034
035
036 s = s.replaceAll("%u[0-9a-fA-F]{4}", StringPool.BLANK);
037
038
039
040 s = StringUtil.replace(s, "+", "%2B");
041 s = StringUtil.replace(s, "%20", "+");
042
043
044
045 try {
046 s = URLDecoder.decode(s, StringPool.UTF8);
047 }
048 catch (Exception e) {
049 }
050
051 return s;
052 }
053
054 public static String encodeURIComponent(String s) {
055
056
057
058 try {
059 s = URLEncoder.encode(s, StringPool.UTF8);
060 }
061 catch (Exception e) {
062 }
063
064
065
066 s = StringUtil.replace(s, "+", "%20");
067 s = StringUtil.replace(s, "%2B", "+");
068
069 return s;
070 }
071
072
075 public static String escape(String s) {
076 return encodeURIComponent(s);
077 }
078
079 public static String getSafeName(String name) {
080 if (name == null) {
081 return null;
082 }
083
084 StringBuilder sb = null;
085
086 int index = 0;
087
088 for (int i = 0; i < name.length(); i++) {
089 char c = name.charAt(i);
090
091 switch (c) {
092 case CharPool.SPACE:
093
094 case CharPool.DASH:
095
096 case CharPool.PERIOD:
097 if (sb == null) {
098 sb = new StringBuilder(name.length() - 1);
099
100 sb.append(name, index, i);
101 }
102
103 break;
104
105 default:
106 if (sb != null) {
107 sb.append(c);
108 }
109 }
110 }
111
112 if (sb == null) {
113 return name;
114 }
115 else {
116 return sb.toString();
117 }
118 }
119
120 public static String toScript(String[] array) {
121 StringBundler sb = new StringBundler(array.length * 4 + 2);
122
123 sb.append(StringPool.OPEN_BRACKET);
124
125 for (int i = 0; i < array.length; i++) {
126 sb.append(StringPool.APOSTROPHE);
127 sb.append(UnicodeFormatter.toString(array[i]));
128 sb.append(StringPool.APOSTROPHE);
129
130 if ((i + 1) < array.length) {
131 sb.append(StringPool.COMMA);
132 }
133 }
134
135 sb.append(StringPool.CLOSE_BRACKET);
136
137 return sb.toString();
138 }
139
140
143 public static String unescape(String s) {
144 return decodeURIComponent(s);
145 }
146
147 }