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