]> sjero.net Git - linphone/blob - p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/documentSerializable/DocumentSerializableUtilities.java
f32e88dd8dc4fd492903ed5e91b1172a68f07f8c
[linphone] / p2pproxy / dependencies-src / jxse-src-2.5 / api / src / net / jxta / util / documentSerializable / DocumentSerializableUtilities.java
1 /*
2  * Copyright (c) 2001-2007 Sun Microsystems, Inc.  All rights reserved.
3  *  
4  *  The Sun Project JXTA(TM) Software License
5  *  
6  *  Redistribution and use in source and binary forms, with or without 
7  *  modification, are permitted provided that the following conditions are met:
8  *  
9  *  1. Redistributions of source code must retain the above copyright notice,
10  *     this list of conditions and the following disclaimer.
11  *  
12  *  2. Redistributions in binary form must reproduce the above copyright notice, 
13  *     this list of conditions and the following disclaimer in the documentation 
14  *     and/or other materials provided with the distribution.
15  *  
16  *  3. The end-user documentation included with the redistribution, if any, must 
17  *     include the following acknowledgment: "This product includes software 
18  *     developed by Sun Microsystems, Inc. for JXTA(TM) technology." 
19  *     Alternately, this acknowledgment may appear in the software itself, if 
20  *     and wherever such third-party acknowledgments normally appear.
21  *  
22  *  4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must 
23  *     not be used to endorse or promote products derived from this software 
24  *     without prior written permission. For written permission, please contact 
25  *     Project JXTA at http://www.jxta.org.
26  *  
27  *  5. Products derived from this software may not be called "JXTA", nor may 
28  *     "JXTA" appear in their name, without prior written permission of Sun.
29  *  
30  *  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
31  *  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 
32  *  FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN 
33  *  MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
34  *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
35  *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
36  *  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
37  *  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
38  *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
39  *  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  *  
41  *  JXTA is a registered trademark of Sun Microsystems, Inc. in the United 
42  *  States and other countries.
43  *  
44  *  Please see the license information page at :
45  *  <http://www.jxta.org/project/www/license.html> for instructions on use of 
46  *  the license in source files.
47  *  
48  *  ====================================================================
49  *  
50  *  This software consists of voluntary contributions made by many individuals 
51  *  on behalf of Project JXTA. For more information on Project JXTA, please see 
52  *  http://www.jxta.org.
53  *  
54  *  This license is based on the BSD license adopted by the Apache Foundation. 
55  */
56
57 package net.jxta.util.documentSerializable;
58
59
60 import net.jxta.document.*;
61 import net.jxta.exception.*;
62 import net.jxta.util.*;
63
64 import java.util.*;
65 import java.io.*;
66
67
68 /**
69  **/
70 public class DocumentSerializableUtilities {
71     // Fix-Me: I didn't implement byte, short or float
72     // Fix-Me: I didn't implement arrays, ie addInt(Element element, String tagName, int values[]), etc
73
74     /**
75      * Creates a Structured XML Document containing the serialized object
76      *
77      * @return  The created Document
78      * @throws DocumentSerializationException if Unable to parse the serialized object.
79      */ 
80     public static XMLDocument createStructuredXmlDocument(String docType, DocumentSerializable documentSerializable) throws DocumentSerializationException {
81         XMLDocument xmlDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, docType);
82
83         documentSerializable.serializeTo(xmlDoc);
84         return xmlDoc;
85     }
86
87     /**
88      * Deeply copy an element into another element
89      *
90      * @param toElement The target Element
91      * @param fromElement The source Element
92      */ 
93     public static void copyChildren(Element toElement, Element fromElement) {
94         // for now ... a quicky use of another utility
95
96         StructuredDocument intoDoc = toElement.getRoot();
97
98         StructuredDocumentUtils.copyChildren(intoDoc, toElement, fromElement);
99     }
100
101     /**
102      *  Add an Element with the specified tagname and value (converted to a String)
103      *
104      * @param element Parent Element that the new child element will be added to
105      * @param tagName TagName to be used for the created Child Element
106      * @param documentSerializable This value will be serialized into the created child element
107      \   * @throws DocumentSerializationException if Unable to serialized object.
108      **/
109     public static void addDocumentSerializable(Element element, String tagName, DocumentSerializable documentSerializable)  throws DocumentSerializationException {
110         StructuredDocument structuredDocument = element.getRoot();
111         Element childElement = structuredDocument.createElement(tagName);
112
113         element.appendChild(childElement);
114         documentSerializable.serializeTo(childElement);
115     }
116
117     /**
118      *  Create an object from its Document Serialized components
119      *
120      * @param element The relative root element of a Document Serialized Object
121      * @param clazz The Class of the resurrected object (must implement DocumentSerializable and have a public no-arg constructor)
122      * @return An object of type 'clazz'
123      * @throws DocumentSerializationException if Unable to parse the serialized object.
124      **/
125     public static DocumentSerializable getDocumentSerializable(Element element, Class clazz) throws DocumentSerializationException {
126         try {
127             return getDocumentSerializable(element, (DocumentSerializable) clazz.newInstance());
128         } catch (DocumentSerializationException e) {
129             throw e;
130         } catch (Exception e) {
131             throw new DocumentSerializationException("Class must have a public no-arg constructor", e);
132         }
133     }
134         
135     /**
136      *  Initialize an object from its Document Serialized components
137      *
138      * @param element The relative root element of a Document Serialized Object
139      * @param documentSerializable The object that will be populated from the Element
140      * @return The same parameter passed to it 'documentSerializable'
141      * @throws DocumentSerializationException if Unable to parse the serialized object.
142      **/
143     public static DocumentSerializable getDocumentSerializable(Element element, DocumentSerializable documentSerializable) throws DocumentSerializationException {
144         documentSerializable.initializeFrom(element);
145         return documentSerializable;
146     }
147
148     /**
149      *  Create an object from its Document Serialized components
150      *
151      * @param element The Parent element which has a child Element with the serialized value
152      * @param tagName The tagname of the element that contains the relative root element of a Document Serialized Object
153      * @param clazz The Class of the resurrected object (must implement DocumentSerializable and have a public no-arg constructor)
154      * @return An object of type 'clazz'
155      * @throws DocumentSerializationException if Unable to parse the serialized object.
156      **/
157     public static DocumentSerializable getDocumentSerializable(Element element, String tagName, Class clazz) throws DocumentSerializationException {
158         Element childElement = getChildElement(element, tagName);
159                 
160         if (childElement != null) {
161             return getDocumentSerializable(childElement, clazz);
162         } else {
163             return null;
164         }
165     }   
166
167     /**
168      *  Create a copy of any Document Serializable object.
169      *  
170      *  This is done by serializing and then deserializing the object (ie not very efficient)
171      *
172      * @param documentSerializable The Object to be copied
173      * @return An copy of the presented object
174      * @throws DocumentSerializationException if Unable to serialize or parse object.
175      **/
176     public static DocumentSerializable copyDocumentSerializable(DocumentSerializable documentSerializable) throws DocumentSerializationException {
177         StructuredDocument structuredDocument = createStructuredXmlDocument("temp", documentSerializable);
178
179         return getDocumentSerializable(structuredDocument, documentSerializable.getClass());
180     }
181
182     /**
183      *  Create a child element of the specified tagName
184      *  
185      *  This is done by serializing and then deserializing the object (ie not very efficient)
186      *
187      * @param element The Parent Element
188      * @param tagName The Tag Name for the new Element
189      * @return The created Element
190      **/
191     public static Element createChildElement(Element element, String tagName) {
192         StructuredDocument structuredDocument = element.getRoot();
193         Element childElement = structuredDocument.createElement(tagName);
194
195         element.appendChild(childElement);
196         return childElement;
197     }
198
199     /**
200      *  Get a child element of the specified tagName
201      *  
202      *  This is done by serializing and then deserializing the object (ie not very efficient)
203      *
204      * @param element The Parent Element
205      * @param tagName The Tag Name for the new Element
206      * @return The found Element
207      **/
208     public static Element getChildElement(Element element, String tagName) {
209         Enumeration e = element.getChildren(tagName);
210                 
211         if (e.hasMoreElements()) {
212             return (Element) e.nextElement();
213         } else {
214             return null;
215         }
216     }
217
218     /**
219      *  Add an Element with the specified tagname and value (converted to a String)
220      *
221      * @param element Parent Element that the new element will be added to
222      * @param tagName TagName to be used for the created Child Element
223      * @param value The value that will be stored in the Element as a String
224      **/         
225     public static void addInt(Element element, String tagName, int value) {
226         StructuredDocument structuredDocument = element.getRoot();
227         Element childElement = structuredDocument.createElement(tagName, Integer.toString(value));
228
229         element.appendChild(childElement);
230     }
231
232     /**
233      *  Get  the value of an element converted from a String
234      *
235      * @param element Element that contains the value
236      * @return the value converted from a String
237      **/
238     public static int getInt(Element element) {
239         return Integer.parseInt((String) element.getValue());
240     }
241         
242     /**
243      *  Get the value of a Child Element 
244      *
245      * @param element The Parant Element
246      * @param tagName The Tag Name of the Child Element that will contain the value
247      * @param defaultValue The return value if there is no Child Element with that Tag Name
248      * @return the value converted from a String
249      **/
250     public static int getInt(Element element, String tagName, int defaultValue) {
251         Element childElement = getChildElement(element, tagName);
252                 
253         if (childElement != null) {
254             return getInt(childElement);
255         } else {
256             return defaultValue;
257         }
258     }   
259                 
260     /**
261      *  Add an Element with the specified tagname and value (converted to a String)
262      *
263      * @param element Parent Element that the new element will be added to
264      * @param tagName TagName to be used for the created Child Element
265      * @param value The value that will be stored in the Element as a String
266      **/
267     public static void addLong(Element element, String tagName, long value) {
268         StructuredDocument structuredDocument = element.getRoot();
269         Element childElement = structuredDocument.createElement(tagName, Long.toString(value));
270
271         element.appendChild(childElement);
272     }
273
274     /**
275      *  Get  the value of an element converted from a String
276      *
277      * @param element Element that contains the value
278      * @return the value converted from a String
279      **/
280     public static long getLong(Element element) {
281         return Long.parseLong((String) element.getValue());
282     }
283
284     /**
285      *  Get the value of a Child Element 
286      *
287      * @param element The Parant Element
288      * @param tagName The Tag Name of the Child Element that will contain the value
289      * @param defaultValue The return value if there is no Child Element with that Tag Name
290      * @return the value converted from a String
291      **/
292     public static long getLong(Element element, String tagName, long defaultValue) {
293         Element childElement = getChildElement(element, tagName);
294                 
295         if (childElement != null) {
296             return getLong(childElement);
297         } else {
298             return defaultValue;
299         }
300     }   
301                 
302     /**
303      *  Add an Element with the specified tagname and value (converted to a String)
304      *
305      * @param element Parent Element that the new element will be added to
306      * @param tagName TagName to be used for the created Child Element
307      * @param value The value that will be stored in the Element as a String
308      **/
309     public static void addDouble(Element element, String tagName, double value) {
310         StructuredDocument structuredDocument = element.getRoot();
311         Element childElement = structuredDocument.createElement(tagName, Double.toString(value));
312
313         element.appendChild(childElement);
314     }
315
316     /**
317      *  Get  the value of an element converted from a String
318      *
319      * @param element Element that contains the value
320      * @return the value converted from a String
321      **/
322     public static double getDouble(Element element) {
323         return Double.parseDouble((String) element.getValue());
324     }
325
326     /**
327      *  Get the value of a Child Element 
328      *
329      * @param element The Parant Element
330      * @param tagName The Tag Name of the Child Element that will contain the value
331      * @param defaultValue The return value if there is no Child Element with that Tag Name
332      * @return the value converted from a String
333      **/
334     public static double getDouble(Element element, String tagName, double defaultValue) {
335         Element childElement = getChildElement(element, tagName);
336                 
337         if (childElement != null) {
338             return getDouble(childElement);
339         } else {
340             return defaultValue;
341         }
342     }   
343                 
344     /**
345      *  Add an Element with the specified tagname and value (converted to a String)
346      *
347      * @param element Parent Element that the new element will be added to
348      * @param tagName TagName to be used for the created Child Element
349      * @param value The value that will be stored in the Element as a String
350      **/
351     public static void addBoolean(Element element, String tagName, boolean value) {
352         StructuredDocument structuredDocument = element.getRoot();
353         Element childElement = structuredDocument.createElement(tagName, value ? "true" : "false");
354
355         element.appendChild(childElement);
356     }
357
358     /**
359      *  Get  the value of an element converted from a String ("true" or "false")
360      *
361      * @param element Element that contains the value
362      * @return the value converted from a String
363      **/
364     public static boolean getBoolean(Element element) {
365         return "true".equals((String) element.getValue());
366     }
367
368     /**
369      *  Get the value of a Child Element 
370      *
371      * @param element The Parant Element
372      * @param tagName The Tag Name of the Child Element that will contain the value
373      * @param defaultValue The return value if there is no Child Element with that Tag Name
374      * @return the value converted from a String
375      **/
376     public static boolean getBoolean(Element element, String tagName, boolean defaultValue) {
377         Element childElement = getChildElement(element, tagName);
378                 
379         if (childElement != null) {
380             return getBoolean(childElement);
381         } else {
382             return defaultValue;
383         }
384     }   
385
386     /**
387      *  Add an Element with the specified tagname and value
388      *
389      * @param element Parent Element that the new element will be added to
390      * @param tagName TagName to be used for the created Child Element
391      * @param value The value that will be stored in the Element
392      **/
393     public static void addString(Element element, String tagName, String value) {
394         StructuredDocument structuredDocument = element.getRoot();
395         Element childElement = structuredDocument.createElement(tagName, value);
396
397         element.appendChild(childElement);
398     }
399
400     /**
401      *  Get  the value of an element as a String
402      *
403      * @param element Element that contains the value
404      * @return the value converted from a String
405      **/
406     public static String getString(Element element) {
407         return (String) element.getValue();
408     }
409
410     /**
411      *  Get the value of a Child Element 
412      *
413      * @param element The Parant Element
414      * @param tagName The Tag Name of the Child Element that will contain the value
415      * @param defaultValue The return value if there is no Child Element with that Tag Name
416      * @return The value found in the Element
417      **/
418     public static String getString(Element element, String tagName, String defaultValue) {
419         Element childElement = getChildElement(element, tagName);
420                 
421         if (childElement != null) {
422             return getString(childElement);
423         } else {
424             return defaultValue;
425         }
426     }
427
428     /**
429      *  Convert a DocumentSerializable object to its XML representation as a String
430      *  
431      *  The Root TagName will be 'documentSerializable' by default
432      *  
433      * @param documentSerializable The Object to be converted to an XML Document
434      * @return The String representation of an XML Document
435      * @throws DocumentSerializationException if Unable to serialize object.
436      **/
437     public static String toXmlString(DocumentSerializable documentSerializable) throws DocumentSerializationException {
438         return toXmlString(documentSerializable, "documentSerializable");
439     }
440
441     /**
442      *  Convert a DocumentSerializable object to its XML representation as a String
443      *  
444      *  The Root TagName will be 'documentSerializable' by default
445      *  
446      * @param documentSerializable The Object to be converted to an XML Document
447      * @param rootTagName The Root tagName for the XML Document
448      * @return The String representation of an XML Document
449      * @throws DocumentSerializationException if Unable to serialize object.
450      **/
451     public static String toXmlString(DocumentSerializable documentSerializable, String rootTagName) throws DocumentSerializationException {
452         try {
453             StringWriter bout = new StringWriter();
454             XMLDocument document = DocumentSerializableUtilities.createStructuredXmlDocument(rootTagName, documentSerializable);
455
456             document.sendToWriter(bout);
457             bout.close();
458                         
459             return bout.toString();
460         } catch (IOException e) {
461             throw new DocumentSerializationException("Error converting to String", e);
462         }
463     }
464         
465     /**
466      *  Write a DocumentSerializable object as an XML Document to a Stream
467      *  
468      *  The Root TagName will be 'documentSerializable' by default
469      *  
470      * @param out The Stream to write the document to
471      * @param documentSerializable The Object to be converted to an XML Document
472      * @throws DocumentSerializationException if Unable to serialize object.
473      * @throws IOException if I/O error while writing
474      **/
475     public static void writeAsXmlString(OutputStream out, DocumentSerializable documentSerializable) throws IOException, DocumentSerializationException {
476         writeAsXmlString(out, documentSerializable, "documentSerializable");
477     }
478         
479     /**
480      *  Write a DocumentSerializable object as an XML Document to a Stream
481      *  
482      *  The Root TagName will be 'documentSerializable' by default
483      *  
484      * @param out The Stream to write the document to
485      * @param rootTagName The Root tagName for the XML Document
486      * @param documentSerializable The Object to be converted to an XML Document
487      * @throws DocumentSerializationException if Unable to serialize object.
488      * @throws IOException if I/O error while writing
489      **/
490     public static void writeAsXmlString(OutputStream out, DocumentSerializable documentSerializable, String rootTagName) throws IOException, DocumentSerializationException {
491         StructuredDocument document = DocumentSerializableUtilities.createStructuredXmlDocument(rootTagName, documentSerializable);
492
493         document.sendToStream(out);
494     }
495
496     /**
497      *  Write a DocumentSerializable object as an XML Document to StdErr
498      *  
499      *  The Root TagName will be 'documentSerializable' by default
500      *  
501      * @param documentSerializable The DocumentSerializable to be printed.
502      **/
503     public static void printAsXmlString(DocumentSerializable documentSerializable) {
504         try {
505             if (documentSerializable == null) {
506                 System.err.println("<null DocumentSerializable>");
507             } else {
508                 writeAsXmlString(System.err, documentSerializable);
509             }
510         } catch (Exception e) {
511             System.err.println("<Error converting DocumentSerializable to XML doc: " + e);
512         }
513     }
514         
515     /**
516      *  Create a DocumentSerializable Object from an XML Document
517      *  
518      * @param buf The XML document contained in a String
519      * @param clazz The Class of the resurrected object (must implement DocumentSerializable and have a public no-arg constructor)
520      * @return An object of type 'clazz'
521      * @throws DocumentSerializationException if Unable to parse object.
522      **/
523     public static DocumentSerializable getDocumentSerializableFromXml(String buf, Class clazz) throws DocumentSerializationException {
524         try {
525             XMLDocument xmlDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8
526                     ,
527                     new StringReader(buf));
528
529             return getDocumentSerializable(xmlDoc.getRoot(), clazz);                    
530         } catch (IOException readErr) {
531             throw new DocumentSerializationException("Unable to read the document", readErr);
532         } catch (JxtaException e) {
533             throw new DocumentSerializationException("Unable to get the document", e);
534         }
535     }
536
537     /**
538      *  Create a DocumentSerializable Object from an XML Document
539      *  
540      * @param buf The XML document contained in a byte buffer
541      * @param clazz The Class of the resurrected object (must implement DocumentSerializable and have a public no-arg constructor)
542      * @return An object of type 'clazz'
543      * @throws DocumentSerializationException if Unable to parse object.
544      **/
545     public static DocumentSerializable getDocumentSerializableFromXml(byte buf[], Class clazz) throws DocumentSerializationException {
546         return getDocumentSerializableFromXml(new ByteArrayInputStream(buf), clazz);
547     }
548
549     /**
550      *  Create a DocumentSerializable Object from an XML Document
551      *  
552      * @param in The Stream containing an XML Document to be read
553      * @param clazz The Class of the resurrected object (must implement DocumentSerializable and have a public no-arg constructor)
554      * @return An object of type 'clazz'
555      * @throws DocumentSerializationException if Unable to parse object.
556      **/
557     public static DocumentSerializable getDocumentSerializableFromXml(InputStream in, Class clazz) throws DocumentSerializationException {
558         try {
559             XMLDocument xmlDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, in);
560
561             return getDocumentSerializable(xmlDoc.getRoot(), clazz);                    
562         } catch (IOException readErr) {
563             throw new DocumentSerializationException("Unable to read the document", readErr);
564         } catch (JxtaException e) {
565             throw new DocumentSerializationException("Unable to get the document", e);
566         }
567     }
568
569 }
570