KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > util > Util


1 package jodd.util;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.ByteArrayOutputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.ObjectInputStream;
8 import java.io.ObjectOutputStream;
9 import java.io.OutputStream;
10 import java.io.PrintWriter;
11 import java.io.Serializable;
12 import java.io.StringWriter;
13 import java.net.MalformedURLException;
14 import java.net.URL;
15 import java.net.URLClassLoader;
16
17 /**
18  * General and System utilities.
19  */

20 public final class Util {
21
22     /**
23      * Compare two objects just like "equals" would. Unlike Object.equals,
24      * this method allows any of the 2 objects to be null.
25      *
26      * @param obj1
27      * @param obj2
28      *
29      * @return true if equal, otherwise false
30      */

31     public static boolean equals(Object obj1, Object obj2) {
32         if (obj1 == null && obj2 == null) {
33             return true;
34         } else if (obj1 != null) {
35             return obj1.equals(obj2);
36         } else {
37             return obj2.equals(obj1);
38         }
39     }
40
41
42     /**
43      * Create object copy using serialization mechanism.
44      *
45      * @param obj
46      *
47      * @return cloned object
48      * @exception Exception
49      */

50     public static Object cloneViaSerialization(Serializable obj) throws Exception {
51         ByteArrayOutputStream bytes = new ByteArrayOutputStream();
52         ObjectOutputStream out = new ObjectOutputStream(bytes);
53         out.writeObject(obj);
54         out.close();
55         ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()));
56         Object objCopy = in.readObject();
57         in.close();
58         return objCopy;
59     }
60
61
62     /**
63      * Loads external or internal class. Class may exists in current virtual
64      * mashine, or it may be defined externally, as part of a jar.
65      *
66      * @param jarPath path to the jar file, or null
67      * @param type class type
68      *
69      * @return founded class, otherwise null
70      * @exception ClassNotFoundException
71      */

72     public static Class loadClass(String jarPath, String type) throws ClassNotFoundException {
73         Class clazz = null;
74         try {
75             if (jarPath == null) {
76                 clazz = Class.forName(type);
77             } else {
78                 jarPath = "jar:file:/" + jarPath + "!/";
79                 URL[] url = {new URL(jarPath)};
80                 URLClassLoader ucl = new URLClassLoader(url);
81                 clazz = ucl.loadClass(type);
82             }
83         } catch (MalformedURLException muex) {
84             throw new ClassNotFoundException("bad jar path: " + jarPath, muex);
85         }
86         return clazz;
87     }
88
89
90     /**
91      * Reads from input and writes read data to the output, until the stream end.
92      *
93      * @param in
94      * @param out
95      * @param bufSizeHint
96      *
97      * @throws IOException
98      */

99     public static void copyPipe(InputStream in, OutputStream out, int bufSizeHint) throws IOException {
100         int read = -1;
101         byte[] buf = new byte[bufSizeHint];
102         while ((read = in.read(buf, 0, bufSizeHint)) >= 0) {
103             out.write(buf, 0, read);
104         }
105         out.flush();
106     }
107
108
109     /**
110      * Returns current stack trace not without this method in the trace. Since an
111      * exception is thrown internally, this is a slow method.
112      *
113      * @return array of stack trace elements
114      */

115     public static StackTraceElement[] getStackTrace() {
116         try {
117             throw new Exception();
118         } catch (Exception ex) {
119             StackTraceElement[] ste = ex.getStackTrace();
120             if (ste.length > 1) {
121                 StackTraceElement[] result = new StackTraceElement[ste.length - 1];
122                 System.arraycopy(ste, 1, result, 0, ste.length - 1);
123                 return result;
124             } else {
125                 return ste;
126             }
127         }
128     }
129     
130     
131     /**
132      * Returns exception stack trace as a String.
133      *
134      * @param ex exception
135      *
136      * @return string of the exception
137      */

138     public static String exceptionToString(Exception ex) {
139         StringWriter sw = new StringWriter();
140         PrintWriter pw = new PrintWriter(sw);
141         ex.printStackTrace(pw);
142         return sw.getBuffer().toString();
143     }
144
145     // ---------------------------------------------------------------- synchronization
146

147     /**
148      * Waits for a object for synchronization purposes.
149      *
150      * @param obj object to wait for
151      */

152     public static void wait(Object obj) {
153         synchronized (obj) {
154             try {
155                 obj.wait();
156             } catch (InterruptedException inex) {
157             }
158         }
159     }
160
161     /**
162      * Waits for a object or a timeout for synchronization purposes.
163      *
164      * @param obj object to wait for
165      * @param timeout the maximum time to wait in milliseconds
166      */

167     public static void wait(Object obj, long timeout) {
168         synchronized (obj) {
169             try {
170                 obj.wait(timeout);
171             } catch (InterruptedException inex) {
172             }
173         }
174     }
175
176     /**
177      * Notifies an object for synchronization purposes.
178      *
179      * @param obj object to notify
180      */

181     public static void notify(Object obj){
182         synchronized (obj) {
183             obj.notify();
184         }
185     }
186
187     /**
188      * Notifies an object for synchronization purposes.
189      *
190      * @param obj object to notify
191      */

192     public static void notifyAll(Object obj){
193         synchronized (obj) {
194             obj.notifyAll();
195         }
196     }
197
198
199     // ---------------------------------------------------------------- serialization
200

201
202     /**
203      * Serializes an Object to bytes array.
204      *
205      * @param obj Object to serialize
206      *
207      * @return byte array of the serialized object
208      * @exception IOException
209      */

210     public static byte[] objectToByteArray(Object obj) throws IOException {
211         byte[] octets = null;
212         ByteArrayOutputStream ostream = new ByteArrayOutputStream();
213         ObjectOutputStream p = new ObjectOutputStream(ostream);
214         p.writeObject (obj);
215         p.flush();
216         octets = ostream.toByteArray();
217         ostream.close();
218         p.close();
219         return octets;
220     }
221
222     /**
223      * Deserializes an object from byte array
224      *
225      * @param octets byte array of serialized object
226      *
227      * @return deserialized object
228      * @exception IOException
229      * @exception ClassNotFoundException
230      */

231     public static Object byteArrayToObject(byte[] octets) throws IOException, ClassNotFoundException {
232         Object retObj = null;
233         ByteArrayInputStream istream = new ByteArrayInputStream(octets);
234         ObjectInputStream i = new ObjectInputStream(istream);
235         retObj = i.readObject();
236         i.close();
237         istream.close();
238         return retObj;
239     }
240
241     // ---------------------------------------------------------------- memory
242

243     /**
244      * Returns amount of total memory.
245      *
246      * @return total memory in bytes
247      */

248     public long getTotalMemory() {
249         return Runtime.getRuntime().totalMemory();
250     }
251
252     /**
253      * Returns amount of free memory.
254      *
255      * @return free memory in bytes
256      */

257     public long getFreeMemory() {
258         return Runtime.getRuntime().freeMemory();
259     }
260
261     /**
262      * Returns amount of used memory.
263      *
264      * @return used memory in bytes
265      */

266     public long getUsedMemory() {
267         return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
268     }
269
270 }
271
Popular Tags