KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > javax > xml > bind > annotation > adapters > NormalizedStringAdapter


1 /*
2  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
3  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
4  */

5
6 package javax.xml.bind.annotation.adapters;
7
8
9
10 /**
11  * {@link XmlAdapter} to handle <tt>xs:normalizedString</tt>.
12  *
13  * <p>
14  * This adapter removes leading and trailing whitespaces, then replace
15  * any tab, CR, and LF by a whitespace character ' '.
16  *
17  * @author Kohsuke Kawaguchi
18  * @since JAXB 2.0
19  */

20 public final class NormalizedStringAdapter extends XmlAdapter<String JavaDoc,String JavaDoc> {
21     /**
22      * Replace any tab, CR, and LF by a whitespace character ' ',
23      * as specified in <a HREF="http://www.w3.org/TR/xmlschema-2/#rf-whiteSpace">the whitespace facet 'replace'</a>
24      */

25     public String JavaDoc unmarshal(String JavaDoc text) {
26         if(text==null) 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 JavaDoc(buf);
48     }
49
50     /**
51      * No-op.
52      *
53      * Just return the same string given as the parameter.
54      */

55         public String JavaDoc marshal(String JavaDoc s) {
56             return s;
57         }
58
59
60     /**
61      * Returns true if the specified char is a white space character
62      * but not 0x20.
63      */

64     protected static boolean isWhiteSpaceExceptSpace(char ch) {
65         // most of the characters are non-control characters.
66
// so check that first to quickly return false for most of the cases.
67
if( ch>=0x20 ) return false;
68
69         // other than we have to do four comparisons.
70
return ch == 0x9 || ch == 0xA || ch == 0xD;
71     }
72 }
73
Popular Tags