001: /*
002: * escape.java
003: *
004: * Copyright (c) 2003-2006 Sun Microsystems, Inc. All Rights Reserved.
005: *
006: * See the file "LICENSE.txt" for information on usage and redistribution
007: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
008: */
009: package org.pnuts.servlet;
010:
011: import pnuts.lang.*;
012:
013: public class escape extends PnutsFunction {
014:
015: public escape() {
016: super ("escape");
017: }
018:
019: public boolean defined(int narg) {
020: return narg == 1;
021: }
022:
023: protected Object exec(Object[] args, Context context) {
024: if (args.length != 1) {
025: undefined(args, context);
026: }
027: Object arg = args[0];
028: if (arg == null) {
029: return "";
030: }
031: String input = String.valueOf(arg);
032: char[] a = null;
033: int len = input.length();
034: StringBuffer sbuf = null;
035: int pos = 0;
036: for (int i = 0; i < len; i++) {
037: if (a == null) {
038: char c = input.charAt(i);
039: switch (c) {
040: case '<':
041: a = input.toCharArray();
042: sbuf = new StringBuffer(len * 10 / 9);
043: sbuf.append(a, 0, i);
044: sbuf.append("<");
045: pos = i + 1;
046: break;
047: case '>':
048: a = input.toCharArray();
049: sbuf = new StringBuffer(len * 10 / 9);
050: sbuf.append(a, 0, i);
051: sbuf.append(">");
052: pos = i + 1;
053: break;
054: case '&':
055: a = input.toCharArray();
056: sbuf = new StringBuffer(len * 10 / 9);
057: sbuf.append(a, 0, i);
058: sbuf.append("&");
059: pos = i + 1;
060: break;
061: case '"':
062: a = input.toCharArray();
063: sbuf = new StringBuffer(len * 10 / 9);
064: sbuf.append(a, 0, i);
065: sbuf.append(""");
066: pos = i + 1;
067: break;
068: case '\'':
069: a = input.toCharArray();
070: sbuf = new StringBuffer(len * 10 / 9);
071: sbuf.append(a, 0, i);
072: sbuf.append("'");
073: pos = i + 1;
074: break;
075: }
076: } else {
077: switch (a[i]) {
078: case '<':
079: sbuf.append(a, pos, i - pos);
080: sbuf.append("<");
081: pos = i + 1;
082: break;
083: case '>':
084: sbuf.append(a, pos, i - pos);
085: sbuf.append(">");
086: pos = i + 1;
087: break;
088: case '&':
089: sbuf.append(a, pos, i - pos);
090: sbuf.append("&");
091: pos = i + 1;
092: break;
093: case '"':
094: sbuf.append(a, pos, i - pos);
095: sbuf.append(""");
096: pos = i + 1;
097: break;
098: case '\'':
099: sbuf.append(a, pos, i - pos);
100: sbuf.append("'");
101: pos = i + 1;
102: break;
103: }
104: }
105: }
106: if (a == null) {
107: return input;
108: } else {
109: if (pos > 0 && pos < len) {
110: sbuf.append(a, pos, len - pos);
111: }
112: return sbuf.toString();
113: }
114: }
115: }
|