KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sslexplorer > agent > client > util > Utils


1 package com.sslexplorer.agent.client.util;
2
3 import java.io.BufferedReader JavaDoc;
4 import java.io.ByteArrayOutputStream JavaDoc;
5 import java.io.File JavaDoc;
6 import java.io.FileInputStream JavaDoc;
7 import java.io.FileOutputStream JavaDoc;
8 import java.io.IOException JavaDoc;
9 import java.io.InputStream JavaDoc;
10 import java.io.InputStreamReader JavaDoc;
11 import java.io.OutputStream JavaDoc;
12 import java.net.URL JavaDoc;
13 import java.util.Locale JavaDoc;
14 import java.util.MissingResourceException JavaDoc;
15 import java.util.PropertyResourceBundle JavaDoc;
16 import java.util.ResourceBundle JavaDoc;
17
18 /**
19  * Utilities that may be used throughout the VPN client suite.
20  *
21  * @author Lee David Painter <a HREF="mailto: lee@3sp.com">&lt;lee@3sp.com&gt;</a>
22  * @author Brett Smith <a HREF="mailto: brett@3sp.com">&lt;brett@3sp.com&gt;</a>
23  */

24 public class Utils {
25
26     /**
27      * Default buffer size for stream utility methods
28      */

29     public static int BUFFER_SIZE = 8192;
30
31
32     /**
33      * Trim spaces from both ends of string
34      *
35      * @param string string to trim
36      * @return trimmed string
37      */

38     public static String JavaDoc trimBoth(String JavaDoc string) {
39         string = string.trim();
40         for (int i = 0; i < string.length(); i++) {
41             if (string.charAt(i) != ' ') {
42                 return string.substring(i);
43             }
44         }
45         return string;
46     }
47
48     /**
49      * Return a trimmed string (both ends) regardless of whether the
50      * source string is <code>null</code> (in which case an
51      * empty string will be retuned).
52      *
53      * @param string
54      * @return trimmed or blank string
55      */

56     public static String JavaDoc trimmedBothOrBlank(String JavaDoc string) {
57         return trimBoth(string == null ? "" : string.trim());
58     }
59     
60     /**
61      * Get the users home directory and if were operating in the MSJVM then try
62      * to get the users profile, since MSJVM does not return the correct
63      * location for the user.home system property.
64      *
65      * @return String
66      */

67     public static String JavaDoc getHomeDirectory() {
68
69         String JavaDoc userHome = System.getProperty("user.home"); //$NON-NLS-1$
70

71         if (System.getProperty("java.vendor") != null && System.getProperty("java.vendor").startsWith("Microsoft")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
72

73             try {
74                 Process JavaDoc process = Runtime.getRuntime().exec(new String JavaDoc[] { "cmd.exe", "/C", "echo", "%USERPROFILE%" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
75
BufferedReader JavaDoc reader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(process.getInputStream()));
76
77                 String JavaDoc profileDir = reader.readLine();
78
79                 File JavaDoc f = new File JavaDoc(profileDir);
80                 if (f.exists()) {
81                     userHome = profileDir;
82                 }
83             } catch (Throwable JavaDoc t) {
84                 // Ignore, we cant do anything about it!!
85
}
86
87         }
88         return userHome;
89     }
90
91     /**
92      * Test if a string is <code>null</code> if it is an
93      * empty string when trimmed.
94      *
95      * @param string
96      * @return null or trimmed blank string
97      */

98     public static boolean isNullOrTrimmedBlank(String JavaDoc string) {
99         return string == null || string.trim().length() == 0;
100     }
101
102     /**
103      * Create a locale object given the code. This splits up the locale name
104      * into language, country and variant parts to keep 1.1 compatibility (which
105      * has no single string constructor in Locale)
106      *
107      * @param localeName locale name
108      * @return locale
109      */

110     public static Locale JavaDoc createLocale(String JavaDoc localeName) {
111         String JavaDoc lang = localeName;
112         String JavaDoc country = "";
113         String JavaDoc variant = "";
114         int idx = localeName.indexOf("_");
115         if (idx != -1) {
116             country = lang.substring(idx + 1);
117             lang = lang.substring(0, idx);
118         }
119         idx = country.indexOf('_');
120         if (idx != -1) {
121             variant = country.substring(idx + 1);
122             country = country.substring(0, idx);
123         }
124         return new Locale JavaDoc(lang, country, variant);
125     }
126
127     /**
128      * Get a resource bundle via the network class loader given the resource
129      * name and the locale. This is required for 1.1 compatibility.
130      *
131      * @param basename
132      * @param locale
133      * @param cl
134      * @param url url
135      * @return resource bundle
136      * @throws MissingResourceException if bundle cannot be found for any reason
137      */

138     public static ResourceBundle JavaDoc getBundle(String JavaDoc basename, Locale JavaDoc locale, ClassLoader JavaDoc cl, URL JavaDoc url) throws MissingResourceException JavaDoc {
139         
140         ResourceBundle JavaDoc resourceBundle = null;
141         
142         // ResourceBundle by default looks for loads of different ways of providing the
143
// resource bundle. We do not want it to go to the server unless a different locale is
144
// specified so must provide our own locating and loading
145

146         // Create the resource name
147
String JavaDoc resource = basename.replace('.', '/') + ".properties";
148         System.out.println("Looking for '" + resource + "' in locale " + locale + " (display name = " + locale.getDisplayName() + "'");
149         
150         // If the language is not specified and not "en" or "en_GB" then load from the network
151
if(locale != null && !"en".equalsIgnoreCase(locale.toString()) &&
152                 !"en_GB".equalsIgnoreCase(locale.toString())) {
153             try {
154                 URL JavaDoc resourceUrl = new URL JavaDoc(url.getProtocol(), url.getHost(), url.getPort(), url.getFile() + resource);
155                 System.out.println("Non GB resource, so trying server '" + resourceUrl.toExternalForm() + "'");
156                 InputStream JavaDoc in = resourceUrl.openStream();
157                 try {
158                     resourceBundle = new PropertyResourceBundle JavaDoc(in);
159                 }
160                 finally {
161                     closeStream(in);
162                 }
163             } catch (IOException JavaDoc ioe) {
164                 ioe.printStackTrace();
165             }
166         }
167         
168         // If no resource bundle has yet been loaded, look for it in the class loader
169
if(resourceBundle == null && cl != null) {
170             System.out.println("Must GB resource, so trying class load");
171             InputStream JavaDoc in = cl.getResourceAsStream(resource);
172             try {
173                 resourceBundle = new PropertyResourceBundle JavaDoc(in);
174             } catch (IOException JavaDoc ioe) {
175                 ioe.printStackTrace();
176             }
177             finally {
178                 closeStream(in);
179             }
180         }
181         
182         // Cannot find
183
if(resourceBundle == null) {
184             throw new MissingResourceException JavaDoc("No such bundle could be located for " + basename, basename, "");
185         }
186         
187         return resourceBundle;
188     }
189
190     /**
191      * Check if the current JRE meets the specified application extension JRE
192      * version.
193      *
194      * @param applicationJRE
195      * @return ok
196      */

197     public static boolean checkVersion(String JavaDoc applicationJRE) {
198         if (applicationJRE == null) {
199             return false;
200         }
201
202         int[] applicationVersion = Utils.getVersion(applicationJRE);
203         int[] installedJREVersion = Utils.getVersion(System.getProperty("java.version")); //$NON-NLS-1$
204

205         for (int i = 0; i < applicationVersion.length && i < installedJREVersion.length; i++) {
206             if (applicationVersion[i] > installedJREVersion[i])
207                 return false;
208         }
209
210         return true;
211     }
212
213     /**
214      * Get a dotted string version number an integer array.
215      *
216      * @param version
217      * @return integer array version number
218      */

219     public static int[] getVersion(String JavaDoc version) {
220         int idx = 0;
221         int pos = 0;
222         int[] result = new int[0];
223         do {
224
225             idx = version.indexOf('.', pos);
226             int v;
227             if (idx > -1) {
228                 v = Integer.parseInt(version.substring(pos, idx));
229                 pos = idx + 1;
230             } else {
231                 try {
232                     int sub = version.indexOf('_', pos);
233                     if (sub == -1) {
234                         sub = version.indexOf('-', pos);
235                     }
236                     if (sub > -1) {
237                         v = Integer.parseInt(version.substring(pos, sub));
238                     } else {
239                         v = Integer.parseInt(version.substring(pos));
240                     }
241                 } catch (NumberFormatException JavaDoc ex) {
242                     // Ignore the exception and return what version we have
243
break;
244                 }
245             }
246             int[] tmp = new int[result.length + 1];
247             System.arraycopy(result, 0, tmp, 0, result.length);
248             tmp[tmp.length - 1] = v;
249             result = tmp;
250
251         } while (idx > -1);
252
253         return result;
254     }
255
256     public static boolean isSupportedJRE(String JavaDoc jre) {
257         return isVersion(jre, System.getProperty("java.version"));
258     }
259
260     public static boolean isVersion(String JavaDoc required, String JavaDoc have) {
261
262         int[] ourVersion = Utils.getVersion(have); //$NON-NLS-1$
263

264         if (required.startsWith(">") || required.startsWith("+")) { //$NON-NLS-1$
265

266             // Our JRE must be greater than the value specified
267
int[] requiredVersion = Utils.getVersion(required.substring(1));
268             for (int i = 0; i < Math.max(ourVersion.length,requiredVersion.length); i++) {
269                 if ( ( i < ourVersion.length ?ourVersion[i] : 0 ) < ( i < requiredVersion.length ? requiredVersion[i] : 0 ) )
270                     return false;
271             }
272             return true;
273
274         } else if (required.startsWith("<") || required.startsWith("-")) { //$NON-NLS-1$
275
// Our JRE must be less than the value specified
276
int[] requiredVersion = Utils.getVersion(required.substring(1));
277             for (int i = 0; i < Math.min(ourVersion.length,requiredVersion.length); i++) {
278                 if ( ( i < ourVersion.length ?ourVersion[i] : 0 ) > ( i < requiredVersion.length ? requiredVersion[i] : 0 ) )
279                     return false;
280             }
281             return true;
282
283         } else {
284             // Direct comparison
285
int[] requiredVersion = Utils.getVersion(required);
286             for (int i = 0; i < Math.max(ourVersion.length,requiredVersion.length); i++) {
287                 if ( ( i < ourVersion.length ?ourVersion[i] : 0 ) != ( i < requiredVersion.length ? requiredVersion[i] : 0 ) )
288                     return false;
289             }
290             return true;
291
292         }
293
294     }
295
296     public static boolean isSupportedOSVersion(String JavaDoc osVersion) {
297         return isVersion(osVersion, System.getProperty("os.version"));
298     }
299
300     public static boolean isSupportedPlatform(String JavaDoc os) {
301         if (os != null) {
302             // If the os does not start with the current platform then ignore
303
// this
304
String JavaDoc platform = System.getProperty("os.name").toUpperCase(); //$NON-NLS-1$
305
if(os.startsWith("!")) { //$NON-NLS-1$
306
return !platform.startsWith(os.substring(1).toUpperCase());
307             } else
308                 return platform.startsWith(os.toUpperCase());
309         } else
310             return true;
311     }
312
313     public static boolean isSupportedArch(String JavaDoc arch) {
314         if (arch != null) {
315             String JavaDoc platformArch = System.getProperty("os.arch").toUpperCase(); //$NON-NLS-1$
316
if(arch.startsWith("!")) { //$NON-NLS-1$
317
if(isWindows64JREAvailable())
318                     return !arch.substring(1).toUpperCase().equals("AMD64");
319                 else
320                     return !platformArch.startsWith(arch.substring(1).toUpperCase());
321             } else {
322                 if(isWindows64JREAvailable())
323                     return arch.toUpperCase().equals("AMD64");
324                 else
325                     return platformArch.startsWith(arch.toUpperCase());
326             }
327         } else
328             return true;
329     }
330     
331     public static boolean isWindows64JREAvailable() {
332         
333         try {
334             String JavaDoc javaHome = new File JavaDoc(System.getProperty("java.home")).getCanonicalPath();
335             
336             try {
337                 if(System.getProperty("os.name").startsWith("Windows")) {
338                     int dataModel = Integer.parseInt(System.getProperty("sun.arch.data.model"));
339     
340                     if(dataModel!=64) {
341                         int idx = javaHome.indexOf(" (x86)");
342                         if(idx > -1) {
343                             // Looks like we have a 32bit Java version installed on 64 bit Windows
344
String JavaDoc programFiles = javaHome.substring(0, idx);
345                             File JavaDoc j = new File JavaDoc(programFiles, "Java");
346                             if(j.exists()) {
347                                 // We may have a 64 bit version of Java installed.
348
String JavaDoc[] jres = j.list();
349                                 for(int i=0;i<jres.length;i++) {
350     
351                                     File JavaDoc h = new File JavaDoc(j, jres[i]);
352                                     File JavaDoc exe = new File JavaDoc(h, "bin\\java.exe");
353                                     if(exe.exists()) {
354                                         // Found a 64bit version of java
355
return true;
356                                     }
357                                 }
358                             }
359                         }
360                     }
361                 }
362             } catch(NumberFormatException JavaDoc ex) {
363             }
364             
365             return false;
366         } catch(IOException JavaDoc ex) {
367             return false;
368         }
369     }
370     
371     public static String JavaDoc getJavaHome() {
372         
373         /**
374          * Try to determine if we have a 64bit version of Java available. This
375          * is required to ensure that any native 64 bit code functions correctly. Why?
376          * well there is no Java Plug-in available for Windows x64 so the 32 bit version
377          * has to be installed. This means that when the agent is launched java.home will
378          * always point to a 32 bit version of Java on a Windows x64 machine. This
379          * causes problems with drive mapping extension as we have x64 JNI code.
380          */

381         try {
382             String JavaDoc javaHome = new File JavaDoc(System.getProperty("java.home")).getCanonicalPath();
383             
384             try {
385                 if(System.getProperty("os.name").startsWith("Windows")) {
386                     int dataModel = Integer.parseInt(System.getProperty("sun.arch.data.model"));
387     
388                     if(dataModel!=64) {
389                         int idx = javaHome.indexOf(" (x86)");
390                         if(idx > -1) {
391                             // Looks like we have a 32bit Java version installed on 64 bit Windows
392
String JavaDoc programFiles = javaHome.substring(0, idx);
393                             File JavaDoc j = new File JavaDoc(programFiles, "Java");
394                             if(j.exists()) {
395                                 // We may have a 64 bit version of Java installed.
396
String JavaDoc[] jres = j.list();
397                                 for(int i=0;i<jres.length;i++) {
398     
399                                     File JavaDoc h = new File JavaDoc(j, jres[i]);
400                                     File JavaDoc exe = new File JavaDoc(h, "bin\\java.exe");
401                                     if(exe.exists()) {
402                                         // Found a 64bit version of java
403
javaHome = h.getAbsolutePath();
404                                         break;
405                                     }
406                                 }
407                             }
408                         }
409                     }
410                 }
411             } catch(NumberFormatException JavaDoc ex) {
412             }
413             
414             return javaHome;
415         } catch(IOException JavaDoc ex) {
416             return System.getProperty("java.home");
417         }
418     }
419
420     /**
421      * Attempt to make a file executable. Only current works on systems that
422      * have the <b>chmod</b> command available.
423      *
424      * @param file file
425      * @throws IOException on any error
426      */

427     public static void makeExecutable(File JavaDoc file) throws IOException JavaDoc {
428         Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[] { "chmod", "ug+rx", file.getAbsolutePath() });
429         try {
430             copy(p.getErrorStream(), new ByteArrayOutputStream JavaDoc());
431         } finally {
432             try {
433                 if (p.waitFor() != 0) {
434                     throw new IOException JavaDoc("Failed to set execute permission. Return code " + p.exitValue() + ".");
435                 }
436             } catch (InterruptedException JavaDoc e) {
437             }
438         }
439
440     }
441
442     /**
443      * Attempt to make a file read only. Uses Java method when possible,
444      * otherwise falls back to working only on systems that have the <b>chmod</b>
445      * command available.
446      *
447      * @param file file
448      * @throws IOException on any error
449      */

450     public static void makeReadOnly(File JavaDoc file) throws IOException JavaDoc {
451         try {
452             file.getClass().getMethod("setReadOnly", new Class JavaDoc[] {}).invoke(file, new Object JavaDoc[] {});
453         } catch (Exception JavaDoc e) {
454             Process JavaDoc p = Runtime.getRuntime().exec(new String JavaDoc[] { "chmod", "a-w", file.getAbsolutePath() });
455             try {
456                 copy(p.getErrorStream(), new ByteArrayOutputStream JavaDoc());
457             } finally {
458                 try {
459                     if (p.waitFor() != 0) {
460                         throw new IOException JavaDoc("Failed to set execute permission. Return code " + p.exitValue() + ".");
461                     }
462                 } catch (InterruptedException JavaDoc ie) {
463                 }
464             }
465
466         }
467
468     }
469
470     /**
471      * Copy from an input stream to an output stream. It is up to the caller to
472      * close the streams.
473      *
474      * @param in input stream
475      * @param out output stream
476      * @throws IOException on any error
477      */

478     public static void copy(InputStream JavaDoc in, OutputStream JavaDoc out) throws IOException JavaDoc {
479         copy(in, out, -1);
480     }
481
482     /**
483      * Copy the specified number of bytes from an input stream to an output
484      * stream. It is up to the caller to close the streams.
485      *
486      * @param in input stream
487      * @param out output stream
488      * @param count number of bytes to copy
489      * @throws IOException on any error
490      */

491     public static void copy(InputStream JavaDoc in, OutputStream JavaDoc out, long count) throws IOException JavaDoc {
492         copy(in, out, count, BUFFER_SIZE);
493     }
494
495     /**
496      * Copy the specified number of bytes from an input stream to an output
497      * stream. It is up to the caller to close the streams.
498      *
499      * @param in input stream
500      * @param out output stream
501      * @param count number of bytes to copy
502      * @param bufferSize buffer size
503      * @throws IOException on any error
504      */

505     public static void copy(InputStream JavaDoc in, OutputStream JavaDoc out, long count, int bufferSize) throws IOException JavaDoc {
506         byte buffer[] = new byte[bufferSize];
507         int i = bufferSize;
508         if (count >= 0) {
509             while (count > 0) {
510                 if (count < bufferSize)
511                     i = in.read(buffer, 0, (int) count);
512                 else
513                     i = in.read(buffer, 0, bufferSize);
514
515                 if (i == -1)
516                     break;
517
518                 count -= i;
519                 out.write(buffer, 0, i);
520             }
521         } else {
522             while (true) {
523                 i = in.read(buffer, 0, bufferSize);
524                 if (i < 0)
525                     break;
526                 out.write(buffer, 0, i);
527             }
528         }
529     }
530
531     /**
532      *
533      *
534      * @param in
535      *
536      * @return
537      */

538     public static boolean closeStream(InputStream JavaDoc in) {
539         try {
540             if (in != null) {
541                 in.close();
542             }
543
544             return true;
545         } catch (IOException JavaDoc ioe) {
546             return false;
547         }
548     }
549
550     public static void copyFile(File JavaDoc from, File JavaDoc to) throws IOException JavaDoc {
551
552         if (from.isDirectory()) {
553             if (!to.exists()) {
554                 to.mkdir();
555             }
556             String JavaDoc[] children = from.list();
557             for (int i = 0; i < children.length; i++) {
558                 File JavaDoc f = new File JavaDoc(from, children[i]);
559                 if (f.getName().equals(".") || f.getName().equals("..")) {
560                     continue;
561                 }
562                 if (f.isDirectory()) {
563                     File JavaDoc f2 = new File JavaDoc(to, f.getName());
564                     copyFile(f, f2);
565                 } else {
566                     copyFile(f, to);
567                 }
568             }
569         } else if (from.isFile() && (to.isDirectory() || to.isFile())) {
570             if (to.isDirectory()) {
571                 to = new File JavaDoc(to, from.getName());
572             }
573             FileInputStream JavaDoc in = new FileInputStream JavaDoc(from);
574             FileOutputStream JavaDoc out = new FileOutputStream JavaDoc(to);
575             byte[] buf = new byte[32678];
576             int read;
577             while ((read = in.read(buf)) > -1) {
578                 out.write(buf, 0, read);
579             }
580             closeStream(in);
581             closeStream(out);
582
583         }
584     }
585
586     /**
587      *
588      *
589      * @param out
590      *
591      * @return
592      */

593     public static boolean closeStream(OutputStream JavaDoc out) {
594         try {
595             if (out != null) {
596                 out.close();
597             }
598
599             return true;
600         } catch (IOException JavaDoc ioe) {
601             return false;
602         }
603     }
604
605 }
606
Popular Tags