View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.myfaces.shared.renderkit.html.util;
20  
21  import java.io.UnsupportedEncodingException;
22  import java.util.Arrays;
23  import java.util.HashSet;
24  import java.util.Set;
25  import java.util.logging.Logger;
26  
27  import javax.faces.context.ExternalContext;
28  import javax.servlet.http.HttpSession;
29  
30  import org.apache.myfaces.shared.config.MyfacesConfig;
31  
32  /**
33   * @author Manfred Geiler (latest modification by $Author: lu4242 $)
34   * @author Anton Koinov
35   * @version $Revision: 1230312 $ $Date: 2012-01-11 18:03:50 -0500 (Wed, 11 Jan 2012) $
36   */
37  public final class JavascriptUtils
38  {
39      //private static final Log log = LogFactory.getLog(JavascriptUtils.class);
40      private static final Logger log = Logger.getLogger(JavascriptUtils.class.getName());
41  
42      public static final String JAVASCRIPT_DETECTED = JavascriptUtils.class.getName() + ".JAVASCRIPT_DETECTED";
43  
44      private static final String AUTO_SCROLL_PARAM = "autoScroll";
45      private static final String AUTO_SCROLL_FUNCTION = "getScrolling()";
46  
47      private static final String OLD_VIEW_ID = JavascriptUtils.class + ".OLD_VIEW_ID";
48  
49  
50      private JavascriptUtils()
51      {
52          // utility class, do not instantiate
53      }
54  
55      private static final Set RESERVED_WORDS =
56          new HashSet(Arrays.asList(new String[]{
57              "abstract",
58              "boolean",
59              "break",
60              "byte",
61              "case",
62              "catch",
63              "char",
64              "class",
65              "const",
66              "continue",
67              "default",
68              "delete",
69              "do",
70              "double",
71              "else",
72              "export",
73              "extends",
74              "false",
75              "final",
76              "finally",
77              "float",
78              "for",
79              "function",
80              "goto",
81              "if",
82              "implements",
83              "in",
84              "instanceof",
85              "int",
86              "long",
87              "native",
88              "new",
89              "null",
90              "package",
91              "private",
92              "protected",
93              "public",
94              "return",
95              "short",
96              "static",
97              "super",
98              "switch",
99              "synchronized",
100             "this",
101             "throw",
102             "throws",
103             "transient",
104             "true",
105             "try",
106             "typeof",
107             "var",
108             "void",
109             "while",
110             "with"
111         }));
112 
113     /**Don't use this function - except when compatibility with the RI is a must,
114      * as in the name for the clear form parameters script.
115      */
116     public static String getValidJavascriptNameAsInRI(String origIdentifier)
117     {
118         return origIdentifier.replaceAll("-", "\\$_");
119     }
120 
121     public static String getValidJavascriptName(String s, boolean checkForReservedWord)
122     {
123         if (checkForReservedWord && RESERVED_WORDS.contains(s))
124         {
125             return s + "_";
126         }
127 
128         StringBuilder buf = null;
129         for (int i = 0, len = s.length(); i < len; i++)
130         {
131             char c = s.charAt(i);
132 
133             if (Character.isLetterOrDigit(c))
134             {
135                 // allowed char
136                 if (buf != null)
137                 {
138                     buf.append(c);
139                 }
140             }
141             else
142             {
143                 if (buf == null)
144                 {
145                     buf = new StringBuilder(s.length() + 10);
146                     buf.append(s.substring(0, i));
147                 }
148 
149                 buf.append('_');
150                 if (c < 16)
151                 {
152                     // pad single hex digit values with '0' on the left
153                     buf.append('0');
154                 }
155 
156                 if (c < 128)
157                 {
158                     // first 128 chars match their byte representation in UTF-8
159                     buf.append(Integer.toHexString(c).toUpperCase());
160                 }
161                 else
162                 {
163                     byte[] bytes;
164                     try
165                     {
166                         bytes = Character.toString(c).getBytes("UTF-8");
167                     }
168                     catch (UnsupportedEncodingException e)
169                     {
170                         throw new RuntimeException(e);
171                     }
172 
173                     for (int j = 0; j < bytes.length; j++)
174                     {
175                         int intVal = bytes[j];
176                         if (intVal < 0)
177                         {
178                             // intVal will be >= 128
179                             intVal = 256 + intVal;
180                         }
181                         else if (intVal < 16)
182                         {
183                             // pad single hex digit values with '0' on the left
184                             buf.append('0');
185                         }
186                         buf.append(Integer.toHexString(intVal).toUpperCase());
187                     }
188                 }
189             }
190 
191         }
192 
193         return buf == null ? s : buf.toString();
194     }
195 
196 
197     public static String encodeString(String string)
198     {
199         if (string == null)
200         {
201             return "";
202         }
203         StringBuilder sb = null;    //create later on demand
204         String app;
205         char c;
206         for (int i = 0; i < string.length (); ++i)
207         {
208             app = null;
209             c = string.charAt(i);
210             switch (c)
211             {
212                 case '\\' : app = "\\\\";  break;
213                 case '"' : app = "\\\"";  break;
214                 case '\'' : app = "\\'";  break;
215                 case '\n' : app = "\\n";  break;
216                 case '\r' : app = "\\r";  break;
217                 default:
218             }
219             if (app != null)
220             {
221                 if (sb == null)
222                 {
223                     sb = new StringBuilder(string.substring(0, i));
224                 }
225                 sb.append(app);
226             }
227             else
228             {
229                 if (sb != null)
230                 {
231                     sb.append(c);
232                 }
233             }
234         }
235 
236         if (sb == null)
237         {
238             return string;
239         }
240         else
241         {
242             return sb.toString();
243         }
244     }
245 
246     public static boolean isJavascriptAllowed(ExternalContext externalContext)
247     {
248         MyfacesConfig myfacesConfig = MyfacesConfig.getCurrentInstance(externalContext);
249         if (myfacesConfig.isAllowJavascript())
250         {
251             if (myfacesConfig.isDetectJavascript())
252             {
253                 return isJavascriptDetected(externalContext);
254             }
255             else
256             {
257                 return true;
258             }
259         }
260         else
261         {
262             return false;
263         }
264     }
265     
266     public static boolean isRenderClearJavascriptOnButton(ExternalContext externalContext)
267     {
268         MyfacesConfig myfacesConfig = MyfacesConfig.getCurrentInstance(externalContext);
269         if (myfacesConfig.isRenderClearJavascriptOnButton())
270         {
271             return true;
272         }
273         else
274         {
275             return false;
276         }
277     }
278     
279     public static boolean isSaveFormSubmitLinkIE(ExternalContext externalContext)
280     {
281         MyfacesConfig myfacesConfig = MyfacesConfig.getCurrentInstance(externalContext);
282         if (myfacesConfig.isSaveFormSubmitLinkIE())
283         {
284             return true;
285         }
286         else
287         {
288             return false;
289         }
290     }    
291 
292     public static void setJavascriptDetected(HttpSession session, boolean value)
293     {
294         session.setAttribute(JAVASCRIPT_DETECTED, Boolean.valueOf(value));
295     }
296     
297     public static boolean isJavascriptDetected(ExternalContext externalContext)
298     {
299         //TODO/FIXME (manolito): This info should be better stored in the viewroot component and not in the session
300         Boolean sessionValue = (Boolean)externalContext.getSessionMap().get(JAVASCRIPT_DETECTED);
301         return sessionValue != null && sessionValue.booleanValue();
302     }
303 
304 
305     public static void setOldViewId(ExternalContext externalContext, String viewId)
306     {
307         externalContext.getRequestMap().put(OLD_VIEW_ID, viewId);
308     }
309 
310     public static String getOldViewId(ExternalContext externalContext)
311     {
312         return (String)externalContext.getRequestMap().get(OLD_VIEW_ID);
313     }
314 }