01: /*
02: * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
03: * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
04: */
05:
06: package javax.xml.bind.annotation.adapters;
07:
08: /**
09: * {@link XmlAdapter} to handle <tt>xs:normalizedString</tt>.
10: *
11: * <p>
12: * This adapter removes leading and trailing whitespaces, then replace
13: * any tab, CR, and LF by a whitespace character ' '.
14: *
15: * @author Kohsuke Kawaguchi
16: * @since JAXB 2.0
17: */
18: public final class NormalizedStringAdapter extends
19: XmlAdapter<String, String> {
20: /**
21: * Replace any tab, CR, and LF by a whitespace character ' ',
22: * as specified in <a href="http://www.w3.org/TR/xmlschema-2/#rf-whiteSpace">the whitespace facet 'replace'</a>
23: */
24: public String unmarshal(String text) {
25: if (text == null)
26: return null; // be defensive
27:
28: int i = text.length() - 1;
29:
30: // look for the first whitespace char.
31: while (i >= 0 && !isWhiteSpaceExceptSpace(text.charAt(i)))
32: i--;
33:
34: if (i < 0)
35: // no such whitespace. replace(text)==text.
36: return text;
37:
38: // we now know that we need to modify the text.
39: // allocate a char array to do it.
40: char[] buf = text.toCharArray();
41:
42: buf[i--] = ' ';
43: for (; i >= 0; i--)
44: if (isWhiteSpaceExceptSpace(buf[i]))
45: buf[i] = ' ';
46:
47: return new String(buf);
48: }
49:
50: /**
51: * No-op.
52: *
53: * Just return the same string given as the parameter.
54: */
55: public String marshal(String s) {
56: return s;
57: }
58:
59: /**
60: * Returns true if the specified char is a white space character
61: * but not 0x20.
62: */
63: protected static boolean isWhiteSpaceExceptSpace(char ch) {
64: // most of the characters are non-control characters.
65: // so check that first to quickly return false for most of the cases.
66: if (ch >= 0x20)
67: return false;
68:
69: // other than we have to do four comparisons.
70: return ch == 0x9 || ch == 0xA || ch == 0xD;
71: }
72: }
|