01: package net.sf.saxon.functions;
02:
03: import net.sf.saxon.codenorm.Normalizer;
04: import net.sf.saxon.expr.XPathContext;
05: import net.sf.saxon.om.Item;
06: import net.sf.saxon.trans.DynamicError;
07: import net.sf.saxon.trans.XPathException;
08: import net.sf.saxon.value.StringValue;
09:
10: /**
11: * Implement the XPath normalize-unicode() function
12: */
13:
14: public class NormalizeUnicode extends SystemFunction {
15:
16: /**
17: * Evaluate in a general context
18: */
19:
20: public Item evaluateItem(XPathContext c) throws XPathException {
21: StringValue sv = (StringValue) argument[0].evaluateItem(c);
22: if (sv == null) {
23: return StringValue.EMPTY_STRING;
24: }
25:
26: // fast path for ASCII strings: normalization is a no-op
27: boolean allASCII = true;
28: CharSequence chars = sv.getStringValueCS();
29: for (int i = chars.length() - 1; i >= 0; i--) {
30: if (chars.charAt(i) > 127) {
31: allASCII = false;
32: break;
33: }
34: }
35: if (allASCII) {
36: return sv;
37: }
38:
39: byte fb = Normalizer.C;
40: if (argument.length == 2) {
41: String form = argument[1].evaluateAsString(c);
42: if (form.equals("NFC")) {
43: fb = Normalizer.C;
44: } else if (form.equals("NFD")) {
45: fb = Normalizer.D;
46: } else if (form.equals("NFKC")) {
47: fb = Normalizer.KC;
48: } else if (form.equals("NFKD")) {
49: fb = Normalizer.KD;
50: } else if (form.equals("")) {
51: return sv;
52: } else {
53: String msg = "Normalization form " + form
54: + " is not supported";
55: DynamicError err = new DynamicError(msg);
56: err.setErrorCode("FOCH0003");
57: err.setXPathContext(c);
58: throw err;
59: }
60: }
61: Normalizer norm = new Normalizer(fb);
62: CharSequence result = norm.normalize(sv.getStringValueCS());
63: return StringValue.makeStringValue(result);
64: }
65:
66: }
67:
68: //
69: // The contents of this file are subject to the Mozilla Public License Version 1.0 (the "License");
70: // you may not use this file except in compliance with the License. You may obtain a copy of the
71: // License at http://www.mozilla.org/MPL/
72: //
73: // Software distributed under the License is distributed on an "AS IS" basis,
74: // WITHOUT WARRANTY OF ANY KIND, either express or implied.
75: // See the License for the specific language governing rights and limitations under the License.
76: //
77: // The Original Code is: all this file.
78: //
79: // The Initial Developer of the Original Code is Michael H. Kay.
80: //
81: // Portions created by (your name) are Copyright (C) (your legal entity). All Rights Reserved.
82: //
83: // Contributor(s): none.
84: //
|