View Javadoc

1   /*
2    * Copyright 2001-2005 The Apache Software Foundation.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package net.sf.nxqd.common;
17  
18  import net.sf.nxqd.NxqdException;
19  
20  import org.w3c.dom.Document;
21  import org.w3c.dom.Node;
22  
23  import org.apache.xml.serialize.OutputFormat;
24  import org.apache.xml.serialize.XMLSerializer;
25  
26  import org.xml.sax.SAXException;
27  import org.xml.sax.InputSource;
28  
29  import javax.xml.parsers.DocumentBuilderFactory;
30  import javax.xml.parsers.ParserConfigurationException;
31  import javax.xml.parsers.DocumentBuilder;
32  import javax.xml.transform.stream.StreamResult;
33  import javax.xml.transform.dom.DOMSource;
34  import javax.xml.transform.Transformer;
35  import javax.xml.transform.TransformerFactory;
36  
37  import java.io.IOException;
38  import java.io.StringReader;
39  import java.io.StringWriter;
40  
41  import java.util.ArrayList;
42  import java.util.Map;
43  import java.util.Set;
44  import java.util.Iterator;
45  import java.util.List;
46  import java.util.Random;
47  import java.util.Date;
48  
49  /**
50   * The class <code>Utils</code> is n abstract class to centralise common
51   * uility methods for use by all the classes.
52   *
53   * @author <a href="mailto:webhiker@sourceforge.net">webhiker</a>
54   * @version 1.0
55   */
56  public abstract class NxqdUtils {
57      private static DocumentBuilder documentBuilder;
58      private static Transformer serializer;
59      private static Random random = new Random();
60  
61      /**
62       * The <code>docToString</code> method converts a <code>Document</code>
63       * object into a <code>java.lang.String</code>.
64       *
65       * @param document a <code>org.w3c.dom.Document</code> value
66       * @return a <code>String</code> value
67       * @exception NxqdException if an error occurs
68       */
69      public static final String docToString(Node node) throws NxqdException {
70  	if (node instanceof Document) {
71  	    return docToString((Document)node);
72  	}
73  	try {
74  	    // Use transformer for serialization.
75  	    if (serializer==null) {
76  		serializer = TransformerFactory.newInstance().newTransformer();
77  	    }
78  	    StringWriter sw = new StringWriter();
79  	    // using the null transformation to write the tree fragment to standard output 
80  	    serializer.transform(new DOMSource(node), new StreamResult(sw));
81  	    
82  	    return sw.toString();
83      	}
84  	catch (Exception t) {
85  	    throw new NxqdException(t);
86  	}
87      }
88  
89      /**
90       * The <code>docToString</code> method converts a <code>Document</code>
91       * object into a <code>java.lang.String</code>.
92       *
93       * @param document a <code>org.w3c.dom.Document</code> value
94       * @return a <code>String</code> value
95       * @exception NxqdException if an error occurs
96       */
97      public static final String docToString(Document document) throws NxqdException {
98  	try {
99  	    // this code now pretty prints the xml
100 	    OutputFormat format = new OutputFormat(document);
101 	    format.setLineWidth(80);
102 	    format.setIndenting(true);
103 	    format.setIndent(3);
104 	    StringWriter sw = new StringWriter();
105 	    XMLSerializer serializer = new XMLSerializer(sw, format);
106 	    serializer.serialize(document);
107 	    return sw.toString();
108 
109 	}
110 	catch (Exception t) {
111 	    throw new NxqdException(t);
112 	}
113     }
114     
115     /**
116      * The <code>docFromString</code> method converts a <code>java.lang.String</code>
117      * object into a <code>org.w3c.dom.Document</code>.
118      *
119      * @param documentAsString a <code>String</code> value
120      * @return a <code>Document</code> value
121      * @exception NxqdException if an error occurs
122      */
123     public static final Document docFromString(String documentAsString) throws NxqdException {
124 	try {
125 	    if (documentBuilder==null) {
126 		// Create a builder factory
127 		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
128 		factory.setValidating(false);
129 		documentBuilder = factory.newDocumentBuilder();
130 	    }
131 	    
132 	    // Create the builder and parse the file
133 	    return documentBuilder.parse(new InputSource(new StringReader(documentAsString)));
134 	} catch (SAXException e) {
135 	    throw new NxqdException(e);
136 	} catch (ParserConfigurationException e) {
137 	    throw new NxqdException(e);
138 	} catch (IOException e) {
139 	    throw new NxqdException(e);
140 	}
141     }
142 
143     /**
144      * The <code>gsoapResultObjectToList</code> method converts
145      * the strange gsoap behaviour into something more
146      * consistent, as gsoap returns sometimes null, a string or
147      * a List, dpending on the number of results.
148      *
149      * @param result an <code>Object</code> value
150      * @return a <code>List</code> value
151      */
152     public static List gsoapResultObjectToList(Object result) {
153 	if (result == null) {
154 	    return new ArrayList();
155 	}
156 	else {
157 	    // for some reason, if only one item is found
158 	    // it s returned as a String
159 	    if (result instanceof String) {
160 		List resultList = new ArrayList();
161 		resultList.add(result.toString());
162 		return resultList;
163 	    }
164 	    else {
165 		return (List)result;
166 	    }
167 	}
168     }
169 
170     public static String generateUniqueId() {
171 	Date date = new Date();
172         String id;
173 	id  = Integer.toString(Math.abs(random.nextInt(10)));
174 	id += Math.abs(random.nextInt(10));
175 	id += Math.abs(random.nextInt(10));
176 	id += Long.toString(date.getTime()-1124437000000L);
177 	id += Math.abs(random.nextInt(10));
178 	id += Math.abs(random.nextInt(10));
179 	return id;
180     }
181 
182     public static List getKeysAsList(final Map map) {
183 	if (map==null) {
184 	    return null;
185 	}
186 	if (map.size()==0) {
187 	    return null;
188 	}
189  	String key;
190  	List list = new ArrayList(map.size());
191 	for (Iterator e = map.keySet().iterator(); e.hasNext() ;) {
192  	    key = e.next().toString();
193 	    list.add(key);
194  	}
195 	return list;
196     }
197     
198     public static List getValuesAsList(final Map map) {
199 	if (map==null) {
200 	    return null;
201 	}
202 	if (map.size()==0) {
203 	    return null;
204 	}
205  	String key;
206  	List list = new ArrayList(map.size());
207 	for (Iterator e = map.keySet().iterator(); e.hasNext() ;) {
208  	    key = e.next().toString();
209 	    list.add(map.get(key));
210  	}
211  	return list;
212     }
213 }
214