KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > soap > encoding > soapenc > DateSerializer


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  *
5  * Copyright (c) 2000 The Apache Software Foundation. All rights
6  * reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  * notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  * notice, this list of conditions and the following disclaimer in
17  * the documentation and/or other materials provided with the
18  * distribution.
19  *
20  * 3. The end-user documentation included with the redistribution,
21  * if any, must include the following acknowledgment:
22  * "This product includes software developed by the
23  * Apache Software Foundation (http://www.apache.org/)."
24  * Alternately, this acknowledgment may appear in the software itself,
25  * if and wherever such third-party acknowledgments normally appear.
26  *
27  * 4. The names "SOAP" and "Apache Software Foundation" must
28  * not be used to endorse or promote products derived from this
29  * software without prior written permission. For written
30  * permission, please contact apache@apache.org.
31  *
32  * 5. Products derived from this software may not be called "Apache",
33  * nor may "Apache" appear in their name, without prior written
34  * permission of the Apache Software Foundation.
35  *
36  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This software consists of voluntary contributions made by many
51  * individuals on behalf of the Apache Software Foundation and was
52  * originally based on software copyright (c) 2000, International
53  * Business Machines, Inc., http://www.apache.org. For more
54  * information on the Apache Software Foundation, please see
55  * <http://www.apache.org/>.
56  */

57
58 package org.apache.soap.encoding.soapenc;
59
60 import org.apache.soap.util.xml.*;
61 import org.apache.soap.util.*;
62 import org.apache.soap.rpc.SOAPContext;
63 import java.io.*;
64 import org.w3c.dom.*;
65 import java.io.*;
66 import java.util.*;
67 import java.text.*;
68
69 /**
70 *
71 * This class de/serializes instances of java.util.Date from/to
72 * the XML-Schema type 'timeInstant'. For details see the
73 * <A HREF="http://www.w3.org/TR/xmlschema-2/#timeInstant">XML-Schema specification</A>
74 *
75 * @author Phil Mork
76 * @author Glen Daniels (gdaniels@allaire.com)
77 * @author Matthew J. Duftler (duftler@us.ibm.com)
78 * @author Sam Ruby (rubys@us.ibm.com)
79 * @see Serializer
80 * @see Deserializer
81 */

82 public class DateSerializer implements Serializer, Deserializer
83 {
84   SimpleDateFormat sdf;
85
86   public DateSerializer()
87   {
88     sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
89                             // 0123456789 0 123456789
90
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
91   }
92
93   public void marshall(String JavaDoc inScopeEncStyle, Class JavaDoc javaType, Object JavaDoc src,
94                        Object JavaDoc context, Writer sink, NSStack nsStack,
95                        XMLJavaMappingRegistry xjmr, SOAPContext ctx)
96                         throws IllegalArgumentException JavaDoc, IOException
97   {
98     if(!javaType.equals(java.util.Date JavaDoc.class))
99     {
100       throw new IllegalArgumentException JavaDoc("Can only serialize java.util.Date instances");
101     }
102     nsStack.pushScope();
103     if(src!=null)
104     {
105       SoapEncUtils.generateStructureHeader(inScopeEncStyle,
106                                            javaType,
107                                            context,
108                                            sink,
109                                            nsStack,xjmr);
110
111       String JavaDoc fdate=null;
112
113       synchronized(sdf)
114       {
115         fdate=sdf.format((Date)src);
116       }
117
118       sink.write(fdate);
119       sink.write("</" + context + '>');
120     }
121     else
122     {
123       SoapEncUtils.generateNullStructure(inScopeEncStyle,
124                                            javaType,
125                                            context,
126                                            sink,
127                                            nsStack,xjmr);
128     }
129     nsStack.popScope();
130   }
131
132   public Bean unmarshall(String JavaDoc inScopeEncStyle, QName elementType, Node src,
133                          XMLJavaMappingRegistry xjmr, SOAPContext ctx)
134                           throws IllegalArgumentException JavaDoc
135   {
136     Date date=null;
137     Element root = (Element)src;
138     String JavaDoc value = DOMUtils.getChildCharacterData(root);
139     if(value!=null && !((value=value.trim()).equals("")))
140     {
141       try
142       {
143         synchronized(sdf)
144         {
145           date=sdf.parse(value);
146         }
147       }
148       catch (ParseException pe)
149       {
150         try
151         {
152           // validate fixed portion of format
153
if (value.length() < 19)
154             throw new ParseException("",0);
155
156           if (value.charAt(4) != '-' || value.charAt(7) != '-' ||
157               value.charAt(10) != 'T')
158             throw new ParseException("",0);
159
160           if (value.charAt(13) != ':' || value.charAt(16) != ':')
161             throw new ParseException("",0);
162
163           // convert what we have validated so far
164
try
165           {
166             synchronized(sdf)
167             {
168               date=sdf.parse(value.substring(0,19)+".000Z");
169             }
170           }
171           catch (Exception JavaDoc e)
172           {
173             throw new ParseException("",0);
174           }
175
176           int pos = 19;
177
178           // parse optional milliseconds
179
if (pos < value.length() && value.charAt(pos)=='.') {
180             int milliseconds = 0;
181             int start = ++pos;
182             while (pos<value.length() && Character.isDigit(value.charAt(pos)))
183               pos++;
184
185             String JavaDoc decimal=value.substring(start,pos);
186             if (decimal.length()==3) {
187               milliseconds=Integer.parseInt(decimal);
188             } else if (decimal.length() < 3) {
189               milliseconds=Integer.parseInt((decimal+"000").substring(0,3));
190             } else {
191               milliseconds=Integer.parseInt(decimal.substring(0,3));
192               if (decimal.charAt(3)>='5') ++milliseconds;
193             }
194
195             // add milliseconds to the current result
196
date.setTime(date.getTime()+milliseconds);
197           }
198
199           // parse optional timezone
200
if (pos+5 < value.length() &&
201                (value.charAt(pos)=='+' || (value.charAt(pos)=='-')))
202           {
203             if (!Character.isDigit(value.charAt(pos+1)) ||
204                 !Character.isDigit(value.charAt(pos+2)) ||
205                 value.charAt(pos+3) != ':' ||
206                 !Character.isDigit(value.charAt(pos+4)) ||
207                 !Character.isDigit(value.charAt(pos+5)))
208                throw new ParseException("",0);
209
210             int hours = (value.charAt(pos+1)-'0')*10+value.charAt(pos+2)-'0';
211             int mins = (value.charAt(pos+4)-'0')*10+value.charAt(pos+5)-'0';
212             int milliseconds = (hours*60+mins)*60*1000;
213
214             // subtract milliseconds from the current date to obtain GMT
215
if (value.charAt(pos)=='+') milliseconds=-milliseconds;
216             date.setTime(date.getTime()+milliseconds);
217             pos+=6;
218           }
219
220           if (pos < value.length() && value.charAt(pos)=='Z') pos++;
221
222           if (pos < value.length())
223             throw new ParseException("",0);
224         }
225         catch (ParseException pe2)
226         {
227           synchronized(sdf)
228           {
229             throw new IllegalArgumentException JavaDoc("String represents no valid " +
230                                              "Date for this Deserializer; " +
231                                              "try " + sdf.toPattern() + ".");
232           }
233         }
234       }
235     }
236     return new Bean(java.util.Date JavaDoc.class,date);
237   }
238 }
239
Popular Tags