KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > lateralnz > common > util > ObjectUtils


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

55 package org.lateralnz.common.util;
56
57 import java.io.ByteArrayInputStream JavaDoc;
58 import java.io.ByteArrayOutputStream JavaDoc;
59 import java.io.IOException JavaDoc;
60 import java.io.ObjectInputStream JavaDoc;
61 import java.io.ObjectOutputStream JavaDoc;
62 import java.lang.reflect.Array JavaDoc;
63 import java.lang.reflect.Method JavaDoc;
64 import java.util.HashMap JavaDoc;
65 import java.util.Iterator JavaDoc;
66 import java.util.List JavaDoc;
67 import java.util.Map JavaDoc;
68
69
70 /**
71  * various utility functions for object handling
72  *
73  * <pre>
74  *
75  *
76  * </pre>
77  *
78  * @author J R Briggs
79  */

80 public class ObjectUtils implements Constants {
81   private static final String JavaDoc L_BRACKET = "[";
82   private static final String JavaDoc R_BRACKET = "]";
83   private static final String JavaDoc BRACKETS = L_BRACKET + R_BRACKET;
84
85   private static Map JavaDoc primitives = new HashMap JavaDoc();
86   static {
87     primitives.put("boolean", boolean.class);
88     primitives.put("byte", byte.class);
89     primitives.put("short", short.class);
90     primitives.put("char", char.class);
91     primitives.put("int", int.class);
92     primitives.put("long", long.class);
93     primitives.put("float", float.class);
94     primitives.put("double", double.class);
95   }
96   
97  /**
98   * resolve a string (specified as a primitive) to a object wrapper (i.e.
99   * turn a String into a Byte based upon a specified byte.class) given its primitive class
100   */

101   public static final Object JavaDoc coercePrimitive(String JavaDoc s, Class JavaDoc c) {
102     if (c == boolean.class) {
103       return new Boolean JavaDoc(s);
104     }
105     else if (c == byte.class) {
106       return new Byte JavaDoc(s);
107     }
108     else if (c == short.class) {
109       return new Short JavaDoc(s);
110     }
111     else if (c == char.class) {
112       return s;
113     }
114     else if (c == int.class) {
115       return new Integer JavaDoc(s);
116     }
117     else if (c == long.class) {
118       return new Long JavaDoc(s);
119     }
120     else if (c == float.class) {
121       return new Float JavaDoc(s);
122     }
123     else if (c == double.class) {
124       return new Double JavaDoc(s);
125     }
126     else {
127       return null;
128     }
129   }
130
131  /**
132   * return true if an object is found in an array
133   */

134   public static final boolean containsObject(Object JavaDoc[] src, Object JavaDoc match) {
135     for (int i = 0; i < src.length; i++) {
136       if (src[i].equals(match)) {
137         return true;
138       }
139     }
140
141     return false;
142   }
143
144  /**
145   * create a new array of a specified size copying the contents of a specified array
146   */

147   public static final Object JavaDoc copyArray(Object JavaDoc[] src, int newsize) {
148     if (src == null) {
149       return new Object JavaDoc[newsize];
150     }
151     else if (newsize < src.length) {
152       newsize = src.length;
153     }
154
155     Object JavaDoc dest = Array.newInstance(src[0].getClass(), newsize);
156     
157     String JavaDoc tmp[] = (String JavaDoc[])dest;
158     System.arraycopy(src, 0, dest, 0, src.length);
159
160     return dest;
161   }
162   
163  /**
164   * get a class based upon the specified classname (this method will correctly
165   * resolve primitives).
166   */

167   public static final Class JavaDoc getClass(String JavaDoc classname) throws Exception JavaDoc {
168     if (primitives.containsKey(classname)) {
169       return (Class JavaDoc)primitives.get(classname);
170     }
171     else {
172       return Class.forName(classname);
173     }
174   }
175
176  /**
177   * return a class as a Java string
178   */

179   public static final String JavaDoc getParameterType(Class JavaDoc c) {
180     if (c.isArray()) {
181       StringBuffer JavaDoc sb = new StringBuffer JavaDoc(c.getComponentType().getName());
182
183       for (int i = 0; i < StringUtils.countOccurrences(c.getName(), '[');
184           i++) {
185         sb.append(BRACKETS);
186       }
187
188       return sb.toString();
189     }
190     else {
191       return c.getName();
192     }
193   }
194   
195  /**
196   * get an md5 signature for a class based upon the methods (return type/name/parameters)
197   */

198   public static final String JavaDoc getMD5Signature(Class JavaDoc c) throws Exception JavaDoc {
199     Method JavaDoc[] meth = c.getDeclaredMethods();
200     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
201     for (int i = 0; i < meth.length; i++) {
202       sb.append(meth[i].getReturnType().getName()).append(SPACE);
203       sb.append(meth[i].getName()).append(LEFT_BRACKET);
204       Class JavaDoc[] params = meth[i].getParameterTypes();
205       for (int j = 0; j < params.length; j++) {
206         sb.append(params[j].getName());
207         if (j < params.length - 1) {
208           sb.append(COMMA);
209         }
210       }
211       sb.append(RIGHT_BRACKET).append(NEWLINE);
212     }
213
214     return StringUtils.toMD5Digest(sb.toString());
215   }
216
217  /**
218   * deserialize an array of bytes into the original object
219   */

220   public static final Object JavaDoc deserialize(byte[] b) throws IOException JavaDoc, ClassNotFoundException JavaDoc {
221     ByteArrayInputStream JavaDoc bais = null;
222     ObjectInputStream JavaDoc ois = null;
223
224     try {
225       bais = new ByteArrayInputStream JavaDoc(b);
226       ois = new ObjectInputStream JavaDoc(bais);
227       return ois.readObject();
228     }
229     finally {
230       IOUtils.close(ois);
231       IOUtils.close(bais);
232     }
233   }
234   
235  /**
236   * return true if the specified string classname is a primitive. This returns
237   * true if classname is "byte", "short", "char", "int", etc.
238   */

239   public static final boolean isPrimitive(String JavaDoc classname) {
240     return primitives.containsKey(classname);
241   }
242
243  /**
244   * load a list with the contents of an array
245   */

246   public static final void loadList(Object JavaDoc[] src, List JavaDoc dest) {
247     for (int i = 0; i < src.length; i++) {
248       dest.add(src[i]);
249     }
250   }
251
252  /**
253   * serialize an object into an array of bytes
254   */

255   public static final byte[] serialize(Object JavaDoc obj) throws IOException JavaDoc {
256     ByteArrayOutputStream JavaDoc baos = null;
257     ObjectOutputStream JavaDoc oos = null;
258     try {
259       baos = new ByteArrayOutputStream JavaDoc();
260       oos = new ObjectOutputStream JavaDoc(baos);
261       oos.writeObject(obj);
262       return baos.toByteArray();
263     }
264     finally {
265       IOUtils.close(oos);
266       IOUtils.close(baos);
267     }
268   }
269
270  /**
271   * generic function to iterate through a list of objects and return a concatenated
272   * 'toString' of them
273   */

274   public static final String JavaDoc toString(List JavaDoc objectList) {
275     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
276
277     if ((objectList != null) && (objectList.size() > 0)) {
278       Iterator JavaDoc iter = objectList.iterator();
279
280       while (iter.hasNext()) {
281         Object JavaDoc obj = iter.next();
282         sb.append(L_BRACKET).append(obj.toString()).append(R_BRACKET);
283
284         if (iter.hasNext()) {
285           sb.append(COMMA);
286         }
287       }
288     }
289
290     return sb.toString();
291   }
292 }
Popular Tags