01: // Copyright 2007 The Apache Software Foundation
02: //
03: // Licensed under the Apache License, Version 2.0 (the "License");
04: // you may not use this file except in compliance with the License.
05: // You may obtain a copy of the License at
06: //
07: // http://www.apache.org/licenses/LICENSE-2.0
08: //
09: // Unless required by applicable law or agreed to in writing, software
10: // distributed under the License is distributed on an "AS IS" BASIS,
11: // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12: // See the License for the specific language governing permissions and
13: // limitations under the License.
14:
15: package org.apache.tapestry;
16:
17: /**
18: * Utilities often needed when building Tapestry applications.
19: */
20: public class TapestryUtils {
21: private static final char APOS = '\'';
22:
23: private static final char QUOTE = '"';
24:
25: private static final char SLASH = '\\';
26:
27: /**
28: * Quotes the provided value as a JavaScript string literal. The input value is surrounded by
29: * single quotes and any interior backslash, single or double quotes are escaped (a preceding
30: * backslash is added).
31: *
32: * @param text
33: * @return quoted text
34: */
35: public static String quote(String text) {
36: StringBuilder result = new StringBuilder(text.length() * 2);
37:
38: result.append(APOS);
39:
40: for (char ch : text.toCharArray()) {
41: switch (ch) {
42: case APOS:
43: case QUOTE:
44: case SLASH:
45:
46: result.append(SLASH);
47:
48: default:
49: result.append(ch);
50: break;
51: }
52: }
53:
54: result.append(APOS);
55:
56: return result.toString();
57: }
58: }
|