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: * Built-in {@link XmlAdapter} to handle <tt>xs:token</tt> and its derived types.
10: *
11: * <p>
12: * This adapter removes leading and trailing whitespaces, then truncate any
13: * sequnce of tab, CR, LF, and SP by a single whitespace character ' '.
14: *
15: * @author Kohsuke Kawaguchi
16: * @since JAXB 2.0
17: */
18: public class CollapsedStringAdapter extends XmlAdapter<String, String> {
19: /**
20: * Removes leading and trailing whitespaces of the string
21: * given as the parameter, then truncate any
22: * sequnce of tab, CR, LF, and SP by a single whitespace character ' '.
23: */
24: public String unmarshal(String text) {
25: if (text == null)
26: return null; // be defensive
27:
28: int len = text.length();
29:
30: // most of the texts are already in the collapsed form.
31: // so look for the first whitespace in the hope that we will
32: // never see it.
33: int s = 0;
34: while (s < len) {
35: if (isWhiteSpace(text.charAt(s)))
36: break;
37: s++;
38: }
39: if (s == len)
40: // the input happens to be already collapsed.
41: return text;
42:
43: // we now know that the input contains spaces.
44: // let's sit down and do the collapsing normally.
45:
46: StringBuffer result = new StringBuffer(len /*allocate enough size to avoid re-allocation*/);
47:
48: if (s != 0) {
49: for (int i = 0; i < s; i++)
50: result.append(text.charAt(i));
51: result.append(' ');
52: }
53:
54: boolean inStripMode = true;
55: for (int i = s + 1; i < len; i++) {
56: char ch = text.charAt(i);
57: boolean b = isWhiteSpace(ch);
58: if (inStripMode && b)
59: continue; // skip this character
60:
61: inStripMode = b;
62: if (inStripMode)
63: result.append(' ');
64: else
65: result.append(ch);
66: }
67:
68: // remove trailing whitespaces
69: len = result.length();
70: if (len > 0 && result.charAt(len - 1) == ' ')
71: result.setLength(len - 1);
72: // whitespaces are already collapsed,
73: // so all we have to do is to remove the last one character
74: // if it's a whitespace.
75:
76: return result.toString();
77: }
78:
79: /**
80: * No-op.
81: *
82: * Just return the same string given as the parameter.
83: */
84: public String marshal(String s) {
85: return s;
86: }
87:
88: /** returns true if the specified char is a white space character. */
89: protected static boolean isWhiteSpace(char ch) {
90: // most of the characters are non-control characters.
91: // so check that first to quickly return false for most of the cases.
92: if (ch > 0x20)
93: return false;
94:
95: // other than we have to do four comparisons.
96: return ch == 0x9 || ch == 0xA || ch == 0xD || ch == 0x20;
97: }
98: }
|