KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > ixenon > free > install > InstallUtilities


1 /* $Id$
2  *
3  * Copyright (c) 1999 Xenonsoft Limited. All Rights Reserved.
4  *
5  * This software is protected by copyright. You are hereby notified from
6  * now by reading this message. This software is also the confidential
7  * and proprietary information of Xenonsoft Limited. ("Confidential
8  * Information").
9  *
10  * This software is distributed under the Xenonsoft Public end user
11  * License ("XPeL"), where the machine-readable source code is provided
12  * under the "Open Source" model.
13  * For more information, please read the file "LICENSE-XPL.txt"
14  */

15
16 // InstallUtilities.java
17

18 // Description:
19
// Installer utilities
20
//
21
// Author:
22
// Peter Pilgrim
23
// Mon Jan 11 23:50:46 GMT 1999
24
//
25
// RCS HEADER
26
//
27
// $Author$
28
// $Date$
29
// $Source$
30
// $Revision$ $State$ $Locker$
31
//
32
// History
33
// ================================================================================
34
// $Log$
35

36 package ixenon.free.install;
37
38 import java.io.*;
39 import java.util.*;
40
41 import java.awt.*;
42 import java.awt.event.*;
43 import javax.swing.JComponent JavaDoc;
44 import javax.swing.JProgressBar JavaDoc;
45 import javax.swing.SwingConstants JavaDoc;
46 import javax.swing.SwingUtilities JavaDoc;
47
48 import ixenon.free.swing.*; // for UpdateProgressBar, ResetProgressBar
49

50
51 /**
52  * This class with a lot of static methods. You will find most
53  * the routines that <EM>normalize</EM> file or directory pathnames
54  * here. This is also known as canonilization. The routines I think
55  * are not perfect, there are a bit dumm. For example I left out
56  * critically transform a path like "C:\jdk1.2\" to UNIX "/jdk1.2".
57  * <P>
58  * <P>
59  * There is also some usual AWT routines to center a component on
60  * the screen.
61  * <P>
62  */

63 public class InstallUtilities implements InstallConstants {
64
65     /** The nominal buffer size for file copying */
66     public final static int NOMINAL_BUFFER_SIZE=8192;
67     public final static String JavaDoc PRESERVE_SUFFIX=".preserved";
68     
69     /**
70      * converts installation mode to a string value.
71      * If the mode cannot be matched then an empty string is returned.
72      */

73     public static String JavaDoc installModeToString( int installMode )
74     {
75     switch (installMode) {
76       case BASIC_INSTALLATION: return BASIC_INSTALLATION_STRING;
77       case CUSTOM_INSTALLATION: return CUSTOM_INSTALLATION_STRING;
78       case COMPACT_INSTALLATION: return COMPACT_INSTALLATION_STRING;
79     }
80     return "";
81     }
82           
83     /**
84      * A convenience method to copy a contents of a source file to a target file.
85      * By default <B>no preservation</B> of the target file takes place.
86      * <I>`.preserve'</I>.
87      *
88      * @param sourceFile the source file.
89      * @param targetFile the target file.
90      * @return a boolean flag on the success or failure of the operation.
91      */

92     public static boolean copyFile( File sourceFile, File targetFile )
93     {
94     return copyFile( sourceFile, targetFile, false );
95     }
96     
97     /**
98      * A convenience method to copy a contents of a source file to a target file.
99      * If the preserve parameter is true, then only if the target file
100      * <I>already</I>exists, then it is preserved by renaming it with a
101      * preservation suffix @see PRESERVE_SUFFIX.
102      * <P>
103      * Target files are <I>only</I> preserved if its file size and
104      * last modification time is different from the source file.
105      * <P>
106      * WARNING: This method does not copy directories.
107      *
108      * @param sourceFile the source file.
109      * @param targetFile the target file.
110      * @param preserve if true then preserve any target file.
111      * @return a boolean flag on the success or failure of the operation.
112      */

113     public static boolean copyFile( File sourceFile, File targetFile,
114                     boolean preserve )
115     {
116     boolean bfDone=true;
117     FileInputStream fin = null;
118     FileOutputStream fout = null;
119
120     if ( sourceFile.equals(targetFile))
121         // Source file and target file are identical.
122
return (false);
123     if ( sourceFile.isDirectory() )
124         return (false); // Cannot copy directories
125
if ( targetFile.isDirectory() )
126         return (false); // Cannot copy directories
127

128     // Check if the target file already exists
129
if ( targetFile.exists() ) {
130         if (preserve &&
131         sourceFile.length() != targetFile.length() &&
132         sourceFile.lastModified() != targetFile.lastModified() ) {
133         File preserveFile = new File( targetFile.getPath()+PRESERVE_SUFFIX );
134         // Delete the old preservation file if exists.
135
if (preserveFile.exists())
136             preserveFile.delete();
137         // Preserve the existing target file now.
138
targetFile.renameTo(preserveFile);
139         }
140         else
141         // no preservation required, delete it now.
142
targetFile.delete();
143     }
144     
145     try {
146         fin = new FileInputStream( sourceFile );
147         fout = new FileOutputStream( targetFile );
148         byte buffer[] = new byte[NOMINAL_BUFFER_SIZE];
149         int n;
150         while ( (n = fin.read( buffer )) > -1 )
151         fout.write( buffer, 0, n );
152     }
153     catch (IOException e) {
154         System.err.println("IO Exception:" + e.getMessage() );
155         bfDone = false;
156     }
157     finally {
158         if (fin != null)
159         try { fin.close(); } catch (Exception JavaDoc e) { ; }
160         if (fout != null)
161         try { fout.close(); } catch (Exception JavaDoc e) { ; }
162     }
163     
164     return (bfDone);
165     }
166
167     /**
168      * A convenience method to copy a contents of a source file to a target file
169      * with multiple thread safe updating of progress bar.
170      * By default <B>no preservation</B> of the target file takes place.
171      *
172      * @param pbar the progress bar.
173      * @param sourceFile the source file.
174      * @param targetFile the target file.
175      * @return a boolean flag on the success or failure of the operation.
176      */

177     public static boolean copyFile(
178     JProgressBar JavaDoc pbar, File sourceFile, File targetFile )
179     {
180     return copyFile( pbar, sourceFile, targetFile, false );
181     }
182
183     /**
184      * A convenience method to copy a contents of a source file to target file
185      * with multiple thread safe updating of progress bar.
186      * If the preserve parameter is true, then only if the target file
187      * <I>already</I>exists, then preserve it by renaming it with a
188      * preservation suffix @see PRESERVE_SUFFIX .
189      * <P>
190      * Target files are <I>only</I> preserved if its file size and
191      * last modification time is different from the source file.
192      * <P>
193      * WARNING: This method does not copy directories.
194      *
195      * @param pbar the progress bar.
196      * @param sourceFile the source file.
197      * @param targetFile the source file.
198      * @param preserve if true then preserve any target file.
199      * @return a boolean flag on the success or failure of the operation.
200      */

201     public static boolean copyFile(
202     JProgressBar JavaDoc pbar, File sourceFile, File targetFile, boolean preserve )
203     {
204     boolean bfDone=true;
205     FileInputStream fin = null;
206     FileOutputStream fout = null;
207
208     if ( sourceFile.equals(targetFile))
209         // Source file and target file are identical.
210
return (false);
211     if ( sourceFile.isDirectory() )
212         return (false); // Cannot copy directories
213
if ( targetFile.isDirectory() )
214         return (false); // Cannot copy directories
215

216     // Check if the target file already exists
217
if ( targetFile.exists() ) {
218         if (preserve &&
219         sourceFile.length() != targetFile.length() &&
220         sourceFile.lastModified() != targetFile.lastModified() ) {
221         File preserveFile = new File( targetFile.getPath()+PRESERVE_SUFFIX );
222         // Delete the old preservation file if exists.
223
if (preserveFile.exists())
224             preserveFile.delete();
225         // Preserve the existing target file now.
226
targetFile.renameTo(preserveFile);
227         }
228         else
229         // no preservation required, delete it now.
230
targetFile.delete();
231     }
232     
233     SwingUtilities.invokeLater( new ResetProgressBar( pbar, 0, 100, 0 ) );
234
235     try {
236         int percentage, total_bytes=0;
237         long fileLength = sourceFile.length();
238         
239         fin = new FileInputStream( sourceFile );
240         fout = new FileOutputStream( targetFile );
241         byte buffer[] = new byte[NOMINAL_BUFFER_SIZE];
242         int n;
243         while ( (n = fin.read( buffer )) > -1 ) {
244         fout.write( buffer, 0, n );
245         total_bytes += n;
246         percentage = (int)( 100.0 * ((double)total_bytes) / fileLength );
247         SwingUtilities.invokeLater( new UpdateProgressBar( pbar, percentage ) );
248         try { Thread.sleep(5); } catch (InterruptedException JavaDoc ie) { }
249         }
250
251         // Set the progress to the maximum 100%
252
SwingUtilities.invokeLater( new UpdateProgressBar( pbar, 100 ) );
253     }
254     catch (IOException e) {
255         System.err.println("IO Exception:" + e.getMessage() );
256         bfDone = false;
257     }
258     finally {
259         if (fin != null)
260         try { fin.close(); } catch (Exception JavaDoc e) { ; }
261         if (fout != null)
262         try { fout.close(); } catch (Exception JavaDoc e) { ; }
263
264     }
265     
266     return (bfDone);
267     }
268
269     /**
270      * Sets the permission for a filename using the operating system
271      * command line interpreter or other system dependant method.
272      * @param file the file to be set
273      * @param perm the permission enumeration
274      *
275      * @see InstallConstants#INST_EXE_PERMS
276      * @see InstallConstants#INST_RDWR_PERMS
277      * @see InstallConstants#INST_RDONLY_PERMS
278      */

279     public static boolean setFilePermissions( String JavaDoc filename, int perm )
280     {
281     return setFilePermissions( new File(filename), perm );
282     }
283     
284     /**
285      * Sets the permission for a filename using the operating system
286      * command line interpreter or other system dependant method.
287      * @param file the file to be set
288      * @param perm the permission enumeration
289      *
290      * @see InstallConstants#INST_EXE_PERMS
291      * @see InstallConstants#INST_RDWR_PERMS
292      * @see InstallConstants#INST_RDONLY_PERMS
293      */

294     public static boolean setFilePermissions( File file, int perm )
295     {
296     boolean done=true;
297     String JavaDoc command;
298     String JavaDoc osname = System.getProperty("os.name");
299     if ( osname.startsWith( "Windows 95" ) ||
300          osname.startsWith( "Windows 98" ) ||
301          osname.startsWith("Windows 2000") ||
302          osname.startsWith("Windows NT") ||
303          osname.startsWith("OS/2") ) {
304         // Don't know if ATTRIB also works for OS/2? *PP* Fri Mar 26 11:11:12 BST 1999
305
switch (perm) {
306           case INST_EXE_PERMS:
307           // Does not make sense for NT, anything with `.EXE' suffix is
308
// treated as being executable.
309
return true;
310           case INST_RDWR_PERMS:
311           command="ATTRIB -R \""+file.getAbsolutePath()+"\"";
312           break;
313           case INST_RDONLY_PERMS:
314           default:
315           command="ATTRIB +R \""+file.getAbsolutePath()+"\"";
316           break;
317         }
318     }
319     else {
320         switch (perm) {
321           case INST_EXE_PERMS:
322           command="/bin/chmod 755 "+file.getAbsolutePath();
323           break;
324           case INST_RDWR_PERMS:
325           command="/bin/chmod 644 "+file.getAbsolutePath();
326           break;
327           case INST_RDONLY_PERMS:
328           default:
329           command="/bin/chmod 444 "+file.getAbsolutePath();
330           break;
331         }
332     }
333          
334     try {
335         Process JavaDoc p = Runtime.getRuntime().exec(command);
336         p.waitFor();
337         // System.out.println("DEBUG: return code:"+ p.exitValue()+" command:"+command );
338
done = ( p.exitValue() == 0 ? true : false );
339         
340     } catch (IOException e) {
341         System.err.println("IO error: " + e);
342         done = false;
343     } catch (InterruptedException JavaDoc e1) {
344         System.err.println("Exception: " + e1.getMessage());
345         done = false;
346     }
347
348
349     return (done);
350     }
351
352     /** Converts a unix pathname string to a NT/DOS string by substituting the
353      * forward slashes (/) with backward slashes (\).
354      * @param unixpath the unix pathname
355      * @return the NT/DOS pathname
356      */

357     public static String JavaDoc convertUnixPathToNTPath( String JavaDoc unixpath )
358     {
359     StringBuffer JavaDoc ntpath = new StringBuffer JavaDoc();
360
361     for (int j=0; j<unixpath.length(); ++j) {
362         char ch = unixpath.charAt(j);
363         if (ch == '/' )
364         ch = '\\';
365         ntpath.append(ch);
366     }
367
368     return ntpath.toString();
369     }
370     
371
372     /** Converts a unix pathname string to a NT/DOS string by substituting the
373      * backward slashes (\) with forward slashes (/).
374      * @param ntpath the NT/DOS pathname
375      * @return the unix pathname
376      */

377     public static String JavaDoc convertNTPathToUnixPath( String JavaDoc ntpath )
378     {
379     StringBuffer JavaDoc unixpath = new StringBuffer JavaDoc();
380
381     for (int j=0; j<ntpath.length(); ++j) {
382         char ch = ntpath.charAt(j);
383         if (ch == '\\' )
384         ch = '/';
385         unixpath.append(ch);
386     }
387
388     return unixpath.toString();
389     }
390     
391
392     /** Normalize a given pathname by convert a unix pathname string
393      * to a NT/DOS string by substituting the forward slashes (/) with
394      * backward slashes (\), or by converting a unix pathname string
395      * to a NT/DOS string by substituting the backward slashes (\)
396      * with forward slashes (/).
397      *
398      * @see #convertUnixPathToNTPath
399      * @see #convertNTPathToUnixPath
400      *
401      * @param pathname the input pathname
402      * @return the normalized pathname
403      */

404     public static String JavaDoc normalizePathname( String JavaDoc pathname )
405     {
406     String JavaDoc fileSep = System.getProperty("file.separator");
407     if ( fileSep.equals("/") )
408         return convertNTPathToUnixPath( pathname );
409     else if ( fileSep.equals("\\") )
410         return convertUnixPathToNTPath( pathname );
411
412     return (pathname);
413     }
414     
415     /**
416      * A convenience method to create a <I>relative</I> normalize file
417      * @param path the path which is normalised
418      *
419      * @return <code>File</code> the normalized file.
420      */

421     public static File createNormalizedFile( String JavaDoc path )
422     {
423     return new File( normalizePathname( path ));
424     }
425
426     /**
427      * A convenience method to create a normalize file
428      * @param prefix the file prefix as a <code>String</code>.
429      * @param path the path which is normalized
430      *
431      * @return <code>File</code> the normalized file.
432      */

433     public static File createNormalizedFile( String JavaDoc prefix, String JavaDoc path )
434     {
435     File file = new File( normalizePathname( prefix ) );
436     return createNormalizedFile( file, path );
437     }
438
439     /**
440      * A convenience method to create a normalize file
441      * @param prefix the file prefix as a <code>File</code>.
442      * @param path the path which is normalized
443      *
444      * @return <code>File</code> the normalized file.
445      */

446     public static File createNormalizedFile( File prefix, String JavaDoc path )
447     {
448     String JavaDoc normPath = normalizePathname( path );
449     return new File( prefix, normPath );
450     }
451     
452     /** protect a NT/DOS pathname from the property file reader
453      * by backslashifying any backslashes (\) in the pathname
454      * @param path the input pathname
455      * @return the protected pathname
456      */

457     public static String JavaDoc getBackslashifiedPath( String JavaDoc path )
458     {
459     StringBuffer JavaDoc protpath = new StringBuffer JavaDoc();
460
461     for (int j=0; j<path.length(); ++j) {
462         char ch = path.charAt(j);
463         if (ch == '\\' )
464         protpath.append(ch);
465         protpath.append(ch);
466     }
467
468     return protpath.toString();
469     }
470     
471     /**
472      * Center component on screen using the components current size.
473      * @param screen the component to be centred on the screen
474      */

475     public static void centerComponentOnScreen( Component JavaDoc comp )
476     {
477     Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
478     Dimension size = new Dimension(comp.getSize());
479     
480     int x = (screen.width-size.width)/2;
481     int y = (screen.height-size.height)/2;
482     comp.setBounds(x, y, size.width, size.height);
483     }
484
485     /**
486      * Center component on screen as normal using the component's
487      * current size.
488      * However if the screen display is 19" high resolution
489      * (e.g 1600 x 1024) then use specified the high resolution dimensions
490      * to centered the component.
491      *
492      * @param screen the component to be centred on the screen
493      * @param hiresBest the dimension to use if the screen is 19"
494      * high resolution or greater.
495      */

496     public static void centerHiresComponentOnScreen(
497     Component JavaDoc comp, Dimension hiresBest )
498     {
499     Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
500     Dimension size = new Dimension(comp.getSize());
501     
502     if (screen.width > 1100 ) {
503         // For hires screens.
504
size.width = 1024;
505         size.height = 695;
506     }
507     int x = (screen.width-size.width)/2;
508     int y = (screen.height-size.height)/2;
509     comp.setBounds(x, y, size.width, size.height);
510     }
511
512 }
513
514 // fini
515
Popular Tags