KickJava   Java API By Example, From Geeks To Geeks.

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


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.File JavaDoc;
58 import java.io.FileFilter JavaDoc;
59 import java.io.FileInputStream JavaDoc;
60 import java.io.FilenameFilter JavaDoc;
61 import java.io.FileOutputStream JavaDoc;
62 import java.io.InputStreamReader JavaDoc;
63 import java.io.IOException JavaDoc;
64 import java.lang.reflect.InvocationTargetException JavaDoc;
65 import java.lang.reflect.Method JavaDoc;
66 import java.lang.reflect.Modifier JavaDoc;
67 import java.net.InetAddress JavaDoc;
68 import java.net.NetworkInterface JavaDoc;
69 import java.nio.channels.FileChannel JavaDoc;
70 import java.util.Arrays JavaDoc;
71 import java.util.Enumeration JavaDoc;
72 import java.util.List JavaDoc;
73
74 import org.apache.log4j.Logger;
75
76 /**
77  * various 'System' related functions
78  *
79  * @author J R Briggs
80  */

81 public class SystemUtils {
82   private static final Logger log = Logger.getLogger(SystemUtils.class.getName());
83   private static final String JavaDoc GET = "get";
84   private static final String JavaDoc SET = "set";
85   private static final Class JavaDoc MAIN_ARGS = (new String JavaDoc[]{ }).getClass();
86   
87   private static final byte[] LOCALHOST_LOOPBACK = new byte[]{ (byte)127, (byte)0, (byte)0, (byte)1 };
88   
89   private SystemUtils() {
90   }
91   
92   public static final void copyFile(String JavaDoc f1, String JavaDoc f2) throws IOException JavaDoc {
93     FileChannel JavaDoc source = new FileInputStream JavaDoc(f1).getChannel();
94     FileChannel JavaDoc dest = new FileOutputStream JavaDoc(f2).getChannel();
95     dest.transferFrom(source, 0, source.size());
96
97     source.close();
98     dest.close();
99   }
100   
101  /**
102   * execute a given command. This essentially wraps the command with a monitor so we can
103   * kill it after a certain period of time. At the moment this is useful for Jikes, since it
104   * seems to hang after certain errors, with no meaningful syserr output
105   * @param cmd the command array
106   * @param env the environment array
107   * @param f the file to use during the exec (@see java.lang.Runtime#getRuntime)
108   * @param waitPeriod the length of time to wait until we assume something has gone wrong and kill the process
109   */

110   public static final String JavaDoc[] exec(String JavaDoc[] cmd, String JavaDoc[] env, File JavaDoc f, long waitPeriod) throws IOException JavaDoc, InterruptedException JavaDoc {
111     Process JavaDoc p = Runtime.getRuntime().exec(cmd, env, f);
112
113     ProcessMonitor pm = new ProcessMonitor(p, waitPeriod);
114     p.waitFor();
115     
116     InputStreamReader JavaDoc is = null;
117     InputStreamReader JavaDoc es = null;
118     try {
119       is = new InputStreamReader JavaDoc(p.getInputStream());
120       es = new InputStreamReader JavaDoc(p.getErrorStream());
121       
122       if (pm.rtn[0] == null) {
123         pm.rtn[0] = StringUtils.readFrom(is).trim();
124       }
125       if (pm.rtn[1] == null) {
126         pm.rtn[1] = StringUtils.readFrom(es).trim();
127       }
128     }
129     finally {
130       IOUtils.close(is);
131       IOUtils.close(es);
132     }
133
134     return pm.rtn;
135   }
136   
137  /**
138   * taking an array of arguments (usually in the main() method) return the value at
139   * a particular index -- or if it is null/empty, return a default value
140   */

141   public static final String JavaDoc getArgument(String JavaDoc[] args, int idx, String JavaDoc defaultValue) {
142     if (args == null || idx >= args.length || StringUtils.isEmpty(args[idx])) {
143       return defaultValue;
144     }
145     else {
146       return args[idx];
147     }
148   }
149     
150  /**
151   * get a list of files matching a regex
152   */

153   public static final String JavaDoc[] getFileList(String JavaDoc directory, final String JavaDoc regex) {
154     File JavaDoc f = new File JavaDoc(directory);
155     if (!f.exists() || !f.isDirectory()) {
156       return new String JavaDoc[]{ };
157     }
158     else {
159       return f.list(new FilenameFilter JavaDoc() {
160         public boolean accept(File JavaDoc f, String JavaDoc name) {
161           if (StringUtils.matches(name, regex)) {
162             return true;
163           }
164           return false;
165         }
166       });
167     }
168   }
169   
170  /**
171   * loads the specified list with File objects (recursing through directories if required)
172   */

173   public static final void getFileList(List JavaDoc filelist, String JavaDoc directory, final String JavaDoc includesRegex, final String JavaDoc excludesRegex, boolean recursive) {
174     File JavaDoc f = new File JavaDoc(directory);
175     if (f.exists() && f.isDirectory()) {
176       File JavaDoc[] farray = f.listFiles(new FileFilter JavaDoc() {
177         public boolean accept(File JavaDoc f) {
178           if (f.isDirectory()) {
179             return true;
180           }
181           else {
182             String JavaDoc name;
183             try {
184               name = f.getCanonicalPath();
185               if (StringUtils.matches(name, includesRegex) && !StringUtils.matches(name, excludesRegex)) {
186                 return true;
187               }
188             }
189             catch (IOException JavaDoc ioe) {
190               ioe.printStackTrace();
191             }
192           }
193           return false;
194         }
195       });
196       for (int i = 0; i < farray.length; i++) {
197         if (farray[i].isDirectory() && recursive) {
198           getFileList(filelist, farray[i].getAbsolutePath(), includesRegex, excludesRegex, recursive);
199         }
200         else {
201           filelist.add(farray[i]);
202         }
203       }
204     }
205   }
206   
207  /**
208   * hopefully this will return the 'real' IP address even if the hosts file is configured
209   * incorrectly (as I discovered on my test machine... JRB). However, If it really can't
210   * figure out the address it will return the loopback address.
211   */

212   public static final byte[] getLocalhostIP() {
213     try {
214       InetAddress JavaDoc ia = InetAddress.getLocalHost();
215       if (!Arrays.equals(ia.getAddress(), LOCALHOST_LOOPBACK)) {
216         return ia.getAddress();
217       }
218       else {
219         Enumeration JavaDoc en = NetworkInterface.getNetworkInterfaces();
220         while (en.hasMoreElements()) {
221           NetworkInterface JavaDoc ni = (NetworkInterface JavaDoc)en.nextElement();
222           Enumeration JavaDoc en2 = ni.getInetAddresses();
223           while (en2.hasMoreElements()) {
224             ia = (InetAddress JavaDoc)en2.nextElement();
225             if (!ia.isLoopbackAddress()) {
226               return ia.getAddress();
227             }
228           }
229         }
230       }
231     }
232     catch (Exception JavaDoc e) {
233       e.printStackTrace();
234     }
235     return (byte[])LOCALHOST_LOOPBACK.clone();
236   }
237   
238  /**
239   * get the "set" method for a property given a class and paramTypes array
240   */

241   public static final Method JavaDoc getSetterMethod(Class JavaDoc c, String JavaDoc property, Class JavaDoc[] paramTypes) throws NoSuchMethodException JavaDoc {
242     if (StringUtils.isEmpty(property)) {
243       return null;
244     }
245
246     String JavaDoc tmp = SET + initCaps(property);
247
248     return c.getMethod(tmp, paramTypes);
249   }
250   
251   private static final String JavaDoc initCaps(String JavaDoc s) {
252     return s.substring(0,1).toUpperCase() + s.substring(1);
253   }
254   
255  /**
256   * invoke a method on an object
257   */

258   public static final Object JavaDoc invoke(Object JavaDoc obj, String JavaDoc method, Object JavaDoc[] args) throws IllegalAccessException JavaDoc, InvocationTargetException JavaDoc, NoSuchMethodException JavaDoc {
259     Class JavaDoc c = obj.getClass();
260     Class JavaDoc[] params = null;
261     if (args != null) {
262       params = new Class JavaDoc[args.length];
263       for (int i = 0; i < args.length; i++) {
264         params[i] = args[i].getClass();
265       }
266     }
267     Method JavaDoc m = c.getMethod(method, params);
268     return m.invoke(obj, args);
269   }
270   
271  /**
272   * invoke the main method of a class
273   */

274   public static final void invokeMain(Class JavaDoc c, String JavaDoc[] args) throws IllegalAccessException JavaDoc, InvocationTargetException JavaDoc, NoSuchMethodException JavaDoc {
275     Class JavaDoc argsClass;
276     if (args == null) {
277       argsClass = MAIN_ARGS;
278     }
279     else {
280       argsClass = args.getClass();
281     }
282     Method JavaDoc m = c.getMethod("main", new Class JavaDoc[] { argsClass });
283     m.setAccessible(true);
284     int mods = m.getModifiers();
285     if (m.getReturnType() != void.class || !Modifier.isStatic(mods) || !Modifier.isPublic(mods)) {
286       throw new NoSuchMethodException JavaDoc("main");
287     }
288     m.invoke(null, new Object JavaDoc[] { args });
289   }
290   
291  /**
292   * the process monitor used when exec'ing a command
293   */

294   static class ProcessMonitor extends Thread JavaDoc {
295     private String JavaDoc[] rtn = new String JavaDoc[2];
296     private boolean running = true;
297     private int count = 10;
298     private long waitPeriod;
299     private Process JavaDoc p;
300     
301     public ProcessMonitor(Process JavaDoc p, long waitPeriod) {
302       this.p = p;
303       this.waitPeriod = waitPeriod;
304       this.start();
305     }
306     
307     public void run() {
308       while (running) {
309         try {
310           this.sleep(waitPeriod);
311           p.exitValue();
312         }
313         catch (InterruptedException JavaDoc ie) { }
314         catch (IllegalThreadStateException JavaDoc itse) {
315           count--;
316           InputStreamReader JavaDoc iisr = null;
317           InputStreamReader JavaDoc eisr = null;
318           try {
319             int incount = p.getInputStream().available();
320             int errcount = p.getErrorStream().available();
321             if (incount > 0 || errcount > 0 || count <= 0) {
322               log.warn("stdin(" + incount + "), stderr(" + errcount + ")");
323               log.warn("destroying hung process " + p);
324               
325               iisr = new InputStreamReader JavaDoc(p.getInputStream());
326               eisr = new InputStreamReader JavaDoc(p.getErrorStream());
327               rtn[0] = StringUtils.readFrom(iisr, incount).trim();
328               rtn[1] = StringUtils.readFrom(eisr, errcount).trim();
329               p.destroy();
330               running = false;
331             }
332             else if (log.isInfoEnabled()) {
333               log.info("SystemUtils.exec: process has still not completed after 10 seconds");
334             }
335           }
336           catch (Exception JavaDoc e) {
337             log.error(e);
338             e.printStackTrace();
339           }
340           finally {
341             IOUtils.close(iisr);
342             IOUtils.close(eisr);
343           }
344         }
345       }
346     }
347   }
348   
349   public static final void sleep(long time) {
350     try {
351       Thread.currentThread().sleep(time);
352     }
353     catch (InterruptedException JavaDoc ie) { }
354   }
355 }
Popular Tags