KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > memoire > vainstall > Setup


1 /**
2  * $RCSfile: Setup.java,v $
3  * @creation 26/01/00
4  * @modification $Date: 2005/05/14 10:14:16 $
5  */

6 package com.memoire.vainstall;
7
8 import java.awt.Color JavaDoc;
9 import java.io.ByteArrayInputStream JavaDoc;
10 import java.io.ByteArrayOutputStream JavaDoc;
11 import java.io.File JavaDoc;
12 import java.io.FileInputStream JavaDoc;
13 import java.io.FileNotFoundException JavaDoc;
14 import java.io.FileOutputStream JavaDoc;
15 import java.io.FileReader JavaDoc;
16 import java.io.FileWriter JavaDoc;
17 import java.io.FilenameFilter JavaDoc;
18 import java.io.IOException JavaDoc;
19 import java.io.InputStream JavaDoc;
20 import java.io.LineNumberReader JavaDoc;
21 import java.io.ObjectInputStream JavaDoc;
22 import java.io.PrintWriter JavaDoc;
23 import java.lang.reflect.InvocationTargetException JavaDoc;
24 import java.lang.reflect.Method JavaDoc;
25 import java.util.ArrayList JavaDoc;
26 import java.util.Arrays JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.List JavaDoc;
29 import java.util.Properties JavaDoc;
30 import java.util.Set JavaDoc;
31 import java.util.StringTokenizer JavaDoc;
32 import java.util.Vector JavaDoc;
33 import java.util.jar.JarInputStream JavaDoc;
34 import java.util.jar.JarOutputStream JavaDoc;
35 import java.util.zip.CRC32 JavaDoc;
36 import java.util.zip.GZIPInputStream JavaDoc;
37 import java.util.zip.ZipEntry JavaDoc;
38 import java.util.zip.ZipInputStream JavaDoc;
39
40 import com.ice.jni.registry.RegStringValue;
41 import com.ice.jni.registry.Registry;
42 import com.ice.jni.registry.RegistryKey;
43
44 /**
45  * @version $Id: Setup.java,v 1.36 2005/05/14 10:14:16 deniger Exp $
46  * @author Axel von Arnim
47  */

48 /*
49  * Strategy for handling installation data for upgrades: the goal is to preserve
50  * old data until the install is completed successfully. If a directory of
51  * install data is found for the previous version, and that directory is not the
52  * same as the name of the directory for the new version. A new directory will
53  * be created for the install data from the upgrade. Upon successful completion,
54  * the old directory will be deleted, and upon failure, the new directory will
55  * be deleted. If the name of the old directory (version) is the same as the new
56  * directory, the current directory is renamed, and a new directory is created.
57  * The disposition of the directories will be the same as if they began with
58  * different names.
59  */

60 public class Setup extends AbstractInstall {
61     public static final String JavaDoc JAVA_HOME = System.getProperty("java.home");
62
63     public String JavaDoc JAVA_EXE;
64
65     private String JavaDoc JAVAW_EXE;
66
67     private String JavaDoc JAVA_EXE_QUOTE;
68
69     private File JavaDoc fileWithArchive_;
70
71     private String JavaDoc installClassName_;
72
73     private long installClassOffset_;
74
75     private long installClassSize_;
76
77     private long jarOffset_;
78
79     private LicenseKeySupport licenseKeySupport;
80
81     private boolean choosedLanguage;
82
83     private VAShortcutEntry[] launchparms;
84
85     // an array of String arrays, one
86
// for each launch script.
87
// Within each string array
88
// 0 - name of launch script (no suff)
89
// 1 - name of java binary
90
// 2 - arguments to java
91
// 3 - classpath
92
// 4 - class to be run
93
// 5 - arguments to class
94
private String JavaDoc customPrePostClassName_;
95
96     /**
97      * The original language
98      */

99     private String JavaDoc originalLanguage;
100
101     public Setup(String JavaDoc uiMode, String JavaDoc uiBluescreen, String JavaDoc uiBluescreenColor,
102             String JavaDoc appName, String JavaDoc appVersion, String JavaDoc destPath,
103             String JavaDoc linkSectionName, String JavaDoc linkSectionIcon,
104             String JavaDoc linkEntryName, String JavaDoc linkEntryIcon,
105             Boolean JavaDoc createUninstallShortcut, String JavaDoc licenseKeySupportName,
106             File JavaDoc fileWithArchive, String JavaDoc installClassName,
107             Long JavaDoc installClassOffset, Long JavaDoc installClassSize, Long JavaDoc jarOffset,
108             File JavaDoc classloaderTempDir) {
109         // this();
110
super();
111         classloaderTempDir_ = classloaderTempDir;
112         try {
113             licenseKeySupport = (LicenseKeySupport) getClass().getClassLoader()
114                     .loadClass(licenseKeySupportName).newInstance();
115         } catch (Exception JavaDoc ex) {
116             // what should be done here?
117
throw new IllegalArgumentException JavaDoc(
118                     "cannot load license key support: " + ex.toString());
119         }
120         uInfo_ = new UpgradeInfo();
121         VAGlobals.UI_MODE = System.getProperty("uimode", uiMode);
122         if ("no".equals(uiBluescreen))
123             VAGlobals.UI_BLUESCREEN = false;
124         else
125             VAGlobals.UI_BLUESCREEN = true;
126         String JavaDoc bsVar = System.getProperty("bluescreen");
127         if (bsVar != null) {
128             if ("no".equalsIgnoreCase(bsVar))
129                 VAGlobals.UI_BLUESCREEN = false;
130             else
131                 VAGlobals.UI_BLUESCREEN = true;
132         }
133         if ((uiBluescreenColor == null) || ("".equals(uiBluescreenColor))
134                 || ("null".equals(uiBluescreenColor)))
135             VAGlobals.UI_BLUESCREEN_COLOR = null;
136         else
137             VAGlobals.UI_BLUESCREEN_COLOR = new Color JavaDoc(Integer.parseInt(
138                     uiBluescreenColor, 16));
139         // image is forced to this location now
140
VAGlobals.IMAGE = "com/memoire/vainstall/resources/banner.gif";
141         VAGlobals.APP_NAME = appName;
142         VAGlobals.APP_VERSION = appVersion;
143         try {
144             VAGlobals.DEST_PATH = expandDirectory(destPath, false, uInfo_);
145         } catch (IOException JavaDoc e) {
146             VAGlobals.printDebug(e.toString());
147             //System.out.println("Cannot determine path, trying your home
148
// directory instead.., received exception " + e);
149
}
150         // HACK CVDL since the above exception is not handled and we don't know
151
// if the environment variable is set, the path will default to the home
152
// directory"
153
if (VAGlobals.DEST_PATH == null) {
154             try {
155                 VAGlobals.DEST_PATH = expandDirectory("[HOME]"
156                         + getWithoutMacro(destPath), false, uInfo_);
157             } catch (IOException JavaDoc e) {
158                 VAGlobals.printDebug(e.toString());
159             }
160             //no problem...
161
if (VAGlobals.DEST_PATH == null)
162                 VAGlobals.DEST_PATH = System.getProperty("user.dir"
163                         + getWithoutMacro(destPath));
164         }
165         VAGlobals.LINK_SECTION_NAME = linkSectionName;
166         VAGlobals.LINK_SECTION_ICON = linkSectionIcon;
167         VAGlobals.LINK_ENTRY_NAME = linkEntryName;
168         VAGlobals.LINK_ENTRY_ICON = linkEntryIcon;
169         VAGlobals.CREATE_UNINSTALL_SHORTCUT = createUninstallShortcut
170                 .booleanValue();
171         if (uInfo_.forceUpgrade)
172             VAGlobals.OPERATION = VAGlobals.UPDATE;
173         else
174             VAGlobals.OPERATION = VAGlobals.INSTALL;
175         fileWithArchive_ = fileWithArchive;
176         installClassName_ = installClassName;
177         installClassOffset_ = installClassOffset.longValue();
178         installClassSize_ = installClassSize.longValue();
179         jarOffset_ = jarOffset.longValue();
180         // get vainstall.properties
181
InputStream JavaDoc pin = getClass().getResourceAsStream(
182                 "resources/vainstall.properties");
183         Properties JavaDoc prop = new Properties JavaDoc();
184         try {
185             prop.load(pin);
186         } catch (IOException JavaDoc exc) {
187             // ignore at the moment
188
}
189         language = prop.getProperty("vainstall.destination.language");
190         if (language != null) {
191             if (language.toLowerCase().indexOf("choose") != -1) {
192                 choosedLanguage = true;
193                 state_ = LANGUAGE;
194             }
195             VAGlobals.setLanguage(language);
196         } // endif
197
originalLanguage = VAGlobals.getCurrentLanguage();
198         customPrePostClassName_ = prop
199                 .getProperty("vainstall.install.customprepost.className");
200         //set the look and feel
201
VAStepFactory.setLnf(VAGlobals.UI_MODE, prop, getClass(),
202                 classloaderTempDir);
203         //the user interface
204
ui_ = VAStepFactory.createUI(VAGlobals.UI_MODE, this);
205         VAGlobals.printDebug("UI created");
206         if (!fileWithArchive.exists()) {
207             ui_.showError(new Exception JavaDoc(VAGlobals.i18n("Setup_ArchiveNotFound")
208                     + fileWithArchive.getAbsolutePath()));
209             quit();
210         }
211         //the the jvm version
212
testVersion(prop);
213         if ("true".equals(prop.getProperty("vainstall.script.java.fullpath",
214                 null))) {
215             VAGlobals.USE_FULL_JAVA_PATH = true;
216             if (VAGlobals.DEBUG) {
217                 VAGlobals.printDebug("Full java path always used");
218             }
219         } else if (VAGlobals.DEBUG)
220             VAGlobals.printDebug("Full java path used only if needed");
221         if ("true".equals(prop.getProperty("vainstall.shortcut.in.installdir",
222                 null))) {
223             VAGlobals.SHORTCUTS_IN_INSTALLDIR = true;
224             if (VAGlobals.DEBUG) {
225                 VAGlobals
226                         .printDebug("Shortcuts will be created in install dir");
227             }
228         }
229         JAVA_EXE = getJavaExe(".exe");
230
231         JAVAW_EXE = getJavaExe("w.exe");
232
233         JAVA_EXE_QUOTE = JAVA_EXE.indexOf(" ") > -1 ? "\"" : "";
234         nextStep();
235         ui_.activateUI();
236     }
237
238     public void testVersion(final Properties JavaDoc prop) {
239         // we test the java version
240
boolean wrongVersion = false;
241         String JavaDoc minVersion = prop
242                 .getProperty("vainstall.java.version.min", null);
243         String JavaDoc maxVersion = prop
244                 .getProperty("vainstall.java.version.max", null);
245         String JavaDoc vendor = prop.getProperty("vainstall.java.vendor", null);
246         if (minVersion != null || maxVersion != null) {
247             String JavaDoc version = System.getProperty("java.version");
248             if (minVersion != null && minVersion.compareTo(version) > 0) {
249                 wrongVersion = true;
250             }
251             if (maxVersion != null && maxVersion.compareTo(version) < 0) {
252                 wrongVersion = true;
253             }
254         }
255         //if the version is correct and a spec vendor is required
256
if (!wrongVersion && vendor != null) {
257             String JavaDoc currentVendor = System.getProperty("java.vendor", null);
258             boolean found = false;
259             if (currentVendor != null) {
260                 currentVendor = currentVendor.toLowerCase();
261                 System.err.println("current vendor " + currentVendor);
262                 StringTokenizer JavaDoc tk = new StringTokenizer JavaDoc(vendor.toLowerCase(), ",");
263                 while (!found && tk.hasMoreTokens()) {
264                     if (currentVendor.indexOf(tk.nextToken().trim()) != -1)
265                         found = true;
266                 }
267             }
268             wrongVersion = !found;
269         }
270         if (wrongVersion) {
271             String JavaDoc minMax = "";
272             if (minVersion != null) {
273                 minMax = VAGlobals.i18n("Setup_MinJavaVersion") + ": "
274                         + minVersion + "\n";
275             }
276             if (maxVersion != null) {
277                 minMax = minMax + VAGlobals.i18n("Setup_MaxJavaVersion") + ": "
278                         + maxVersion + "\n";
279             }
280             if (vendor != null) {
281                 minMax = minMax + VAGlobals.i18n("Setup_JavaVendor") + ": "
282                         + vendor + "\n";
283             }
284             String JavaDoc error = VAGlobals.i18n("Setup_JavaVersionNotSuitable")
285                     + "\n\n"
286                     + minMax
287                     + "\n"
288                     + VAGlobals.i18n("Setup_JavaUsedVersion")
289                     + ": "
290                     + System.getProperty("java.version")+" ("+System.getProperty("java.vendor")+")"
291                     + "\n\n"
292                     + VAGlobals.i18n("Setup_JavaDownload")
293                     + ":\n"
294                     + prop.getProperty("vainstall.java.download.url",
295                             "http://www.java.com/download/manual.jsp");
296             if(VAGlobals.DEBUG){
297                 System.err.println("check version failed ...");
298             }
299             ui_.showError(new Exception JavaDoc(error));
300             quit();
301         }
302     }
303
304     public void nextStep() {
305         switch (state_) {
306         case LANGUAGE: {
307             VAGlobals.printDebug("LANGUAGE");
308             state_ = START;
309             setActionEnabled(NEXT | CANCEL);
310             step_ = ui_.createSetupLanguageStep();
311             break;
312         }
313         case START: {
314             VAGlobals.printDebug("WELCOME");
315             if (step_ instanceof VALanguageStep) {
316                 language = ((VALanguageStep) step_).getLanguage();
317                 VAGlobals.setLanguage(language);
318             }
319             state_ = WELCOME;
320             if (choosedLanguage == false) {
321                 setActionEnabled(NEXT | CANCEL);
322             } else {
323                 setActionEnabled(BACK | NEXT | CANCEL);
324             }
325             step_ = ui_.createWelcomeStep();
326             break;
327         }
328         case WELCOME: {
329             VAGlobals.printDebug("LICENSE");
330             state_ = LICENSE;
331             setActionEnabled(BACK | NEXT | CANCEL);
332             step_ = ui_.createLicenseStep();
333             ((VALicenseStep) step_).setText(getClass().getResourceAsStream(
334                     "license.txt"));
335             break;
336         }
337         case LICENSE: {
338             if (!((VALicenseStep) step_).isLicenseAccepted()) {
339                 ui_.showError(new Exception JavaDoc(VAGlobals
340                         .i18n("Setup_AcceptLicense")));
341             } else {
342                 VAGlobals.printDebug("README");
343                 state_ = README;
344                 setActionEnabled(BACK | NEXT | CANCEL);
345                 step_ = ui_.createReadmeStep();
346                 ((VAReadmeStep) step_).setText(getClass().getResourceAsStream(
347                         "readme.txt"));
348             }
349             break;
350         }
351         case README: {
352             if (licenseKeySupport.needsLicenseKey()) {
353                 VAGlobals.printDebug("LICENSE_KEY");
354                 state_ = LICENSE_KEY;
355                 setActionEnabled(0);
356                 step_ = ui_.createLicenseKeyStep();
357                 ((VALicenseKeyStep) step_)
358                         .setLicenseKeySupport(licenseKeySupport);
359                 setActionEnabled(BACK | NEXT | CANCEL);
360             } else {
361                 nextStepUpgrade();
362             }
363             break;
364         }
365         case LICENSE_KEY: {
366             if (((VALicenseKeyStep) step_).getGetFields(licenseKeySupport)) {
367                 nextStepUpgrade();
368             } else {
369                 ui_.showError(new Exception JavaDoc("invalid license key" /*
370                                                                    * i18n fix
371                                                                    * needed
372                                                                    */

373                 ));
374             }
375             break;
376         }
377         case UPGRADE: {
378             boolean uConfirm = true;
379             if (uInfo_.forceUpgrade
380                     || VAGlobals.APP_VERSION.equals(uInfo_.lastVersion()))
381                 uConfirm = true;
382             else {
383                 VAUpgradeStep ustep = (VAUpgradeStep) step_;
384                 uConfirm = ustep.isConfirmUpgrade();
385             }
386             uInfo_.upgrade = uInfo_.upgrade && uConfirm;
387             if (uInfo_.upgrade) {
388                 if (!uInfo_.lastPath().exists()) {
389                     exitOnError(new Exception JavaDoc(uInfo_.lastPath()
390                             + VAGlobals.i18n("Setup_DirectoryNotAccessible")
391                             + "\n" + VAGlobals.i18n("Setup_ReinstallFirst")));
392                 }
393                 if (uInfo_.module
394                         && !VAGlobals.APP_VERSION.equals(uInfo_.lastVersion())) {
395                     exitOnError(new Exception JavaDoc(VAGlobals
396                             .i18n("Setup_VersionWarning")
397                             + "\n"
398                             + VAGlobals.i18n("Setup_Current")
399                             + uInfo_.lastVersion()
400                             + ", "
401                             + VAGlobals.i18n("Setup_ThisOne")
402                             + VAGlobals.APP_VERSION
403                             + "\n"
404                             + VAGlobals.i18n("Setup_ReinstallFirst")));
405                 }
406                 if (uInfo_.lastVersion().compareTo(VAGlobals.APP_VERSION) > 0) {
407                     ui_.showError(new Exception JavaDoc(VAGlobals
408                             .i18n("Setup_VersionWarning")
409                             + "\n"
410                             + VAGlobals.i18n("Setup_Current")
411                             + uInfo_.lastVersion()
412                             + ", "
413                             + VAGlobals.i18n("Setup_ThisOne")
414                             + VAGlobals.APP_VERSION
415                             + "\n"
416                             + VAGlobals.i18n("Setup_CurrentVersionNewer")
417                             + "\n" + VAGlobals.i18n("Setup_MayCancelUpdate")));
418                 }
419                 VAGlobals.printDebug("Upgrade from version: "
420                         + uInfo_.lastVersion());
421                 VAGlobals.DEST_PATH = uInfo_.lastPath().getAbsolutePath();
422                 uInfo_.paths = null;
423                 VAGlobals.printDebug("INSTALL");
424                 state_ = INSTALL;
425                 setActionEnabled(BACK | NEXT | CANCEL);
426                 step_ = ui_.createInstallStep();
427             } else {
428                 if (uInfo_.forceUpgrade)
429                     exitOnError(new Exception JavaDoc(VAGlobals
430                             .i18n("Setup_UpdateOnly")
431                             + "\n"
432                             + VAGlobals.i18n("Setup_NoSuitableVersion")
433                             + "\n" + VAGlobals.APP_NAME));
434                 VAGlobals.printDebug("DIRECTORY");
435                 state_ = DIRECTORY;
436                 setActionEnabled(BACK | NEXT | CANCEL);
437                 step_ = ui_.createDirectoryStep();
438                 ((VADirectoryStep) step_).setDirectory(new File JavaDoc(
439                         VAGlobals.DEST_PATH));
440             }
441             break;
442         }
443         case DIRECTORY: {
444             VADirectoryStep dstep = (VADirectoryStep) step_;
445             File JavaDoc file = (dstep).getDirectory();
446             if (file == null)
447                 return;
448             File JavaDoc errorDir = checkDirectory(file);
449             if (errorDir != null) {
450                 dstep.roDirectory(errorDir);
451                 VAGlobals.printDebug(" " + errorDir.getAbsolutePath()
452                         + " read-only");
453                 return;
454             }
455             if (uInfo_.paths != null) {
456                 for (int i = 0; i < uInfo_.paths.length; i++) {
457                     if ((uInfo_.paths[i] != null)
458                             && (uInfo_.paths[i].getAbsolutePath().equals(file
459                                     .getAbsolutePath()))) {
460                         dstep.rejectDirectory();
461                         VAGlobals.printDebug(" " + file.getAbsolutePath()
462                                 + " rejected");
463                         return;
464                     }
465                 }
466             }
467             if (!dstep.acceptDirectory()) {
468                 VAGlobals.printDebug(" " + file.getAbsolutePath()
469                         + " refused by user");
470                 return;
471             }
472
473             VAGlobals.DEST_PATH = file.getAbsolutePath();
474             VAGlobals.printDebug(" " + file.getAbsolutePath() + " accepted");
475             VAGlobals.printDebug("INSTALL");
476             state_ = INSTALL;
477             setActionEnabled(BACK | NEXT | CANCEL);
478             step_ = ui_.createInstallStep();
479             break;
480         }
481         case INSTALL: {
482             if (VAGlobals.APP_VERSION == null)
483                 exitOnError(new Exception JavaDoc(VAGlobals
484                         .i18n("Setup_VersionWarning")
485                         + "\n"
486                         + VAGlobals.i18n("Setup_Current")
487                         + uInfo_.lastVersion()
488                         + ", "
489                         + VAGlobals.i18n("Setup_ThisOne")
490                         + "is null"
491                         + "\n"
492                         + VAGlobals.i18n("Setup_ReinstallFirst")));
493             setActionEnabled(0);
494             startInstall(sharedDir_, uInfo_);
495             // On saute les raccourcis en mode mise a jour
496
if (uInfo_.upgrade || uInfo_.forceUpgrade) {
497                 try {
498                     if (!uInfo_.module) {
499                         if (cleanShortcuts(new File JavaDoc(sharedDir_
500                                 .getAbsolutePath()
501                                 + File.separator
502                                 + "vai_"
503                                 + VAGlobals.APP_NAME
504                                 + "_" + VAGlobals.APP_VERSION + File.separator)))
505                             createShortcuts(sharedDir_);
506                     } else {
507                         createShortcuts(sharedDir_);
508                     }
509                 } catch (IOException JavaDoc e) {
510                     System.out.println("[Setup]: " + e.getMessage());
511                 }
512                 VAGlobals.printDebug("END");
513                 state_ = END;
514                 setActionEnabled(FINISH);
515                 step_ = ui_.createEndStep();
516                 ((VAEndStep) step_).setStats(stats_);
517             } else {
518                 VAGlobals.printDebug("SHORTCUTS");
519                 state_ = SHORTCUTS;
520                 setActionEnabled(NEXT);
521                 step_ = ui_.createShortcutStep();
522             }
523             break;
524         }
525         case SHORTCUTS: {
526             if (((VAShortcutStep) step_).isShortcutAccepted()) {
527                 createShortcuts(sharedDir_);
528             }
529             VAGlobals.printDebug("END");
530             state_ = END;
531             setActionEnabled(FINISH);
532             step_ = ui_.createEndStep();
533             ((VAEndStep) step_).setStats(stats_);
534             break;
535         }
536         case END: {
537             ui_.quitUI();
538             quit();
539         }
540         }
541     }
542
543     private void nextStepUpgrade() {
544         VAGlobals.printDebug("UPGRADE");
545         state_ = UPGRADE;
546         setActionEnabled(0);
547         step_ = ui_.createUpgradeStep();
548         VAGlobals.printDebug(IS_ROOT ? "Root install" : "User install");
549         sharedDir_ = findVAISharedDir();
550         VAGlobals.printDebug("vainstall directory: !!!" + sharedDir_);
551         checkUpgrade(sharedDir_, uInfo_);
552         if ((!(VAGlobals.APP_VERSION.equals(uInfo_.lastVersion())))
553                 && uInfo_.upgrade && (!uInfo_.forceUpgrade)) {
554             VAUpgradeStep ustep = (VAUpgradeStep) step_;
555             ustep.setChoiceEnabled(true);
556         }
557         setActionEnabled(BACK | NEXT | CANCEL);
558     }
559
560     public void previousStep() {
561         switch (state_) {
562         case WELCOME: {
563             VAGlobals.printDebug("LANGUAGE");
564             state_ = START;
565             setActionEnabled(NEXT | CANCEL);
566             VAGlobals.setLanguage(originalLanguage);
567             step_ = ui_.createSetupLanguageStep();
568             break;
569         }
570         case LICENSE: {
571             VAGlobals.printDebug("WELCOME");
572             state_ = WELCOME;
573             if (choosedLanguage == false) {
574                 setActionEnabled(NEXT | CANCEL);
575             } else {
576                 setActionEnabled(BACK | NEXT | CANCEL);
577             }
578             step_ = ui_.createWelcomeStep();
579             break;
580         }
581         case README: {
582             VAGlobals.printDebug("LICENSE");
583             state_ = LICENSE;
584             setActionEnabled(BACK | NEXT | CANCEL);
585             step_ = ui_.createLicenseStep();
586             ((VAReadmeStep) step_).setText(getClass().getResourceAsStream(
587                     "license.txt"));
588             break;
589         }
590         case LICENSE_KEY: {
591             VAGlobals.printDebug("README");
592             state_ = README;
593             setActionEnabled(BACK | NEXT | CANCEL);
594             step_ = ui_.createReadmeStep();
595             ((VAReadmeStep) step_).setText(getClass().getResourceAsStream(
596                     "readme.txt"));
597             break;
598         }
599         case UPGRADE: {
600             if (licenseKeySupport.needsLicenseKey()) {
601                 VAGlobals.printDebug("LICENSE_KEY");
602                 state_ = LICENSE_KEY;
603                 setActionEnabled(0);
604                 step_ = ui_.createLicenseKeyStep();
605                 ((VALicenseKeyStep) step_)
606                         .setLicenseKeySupport(licenseKeySupport);
607                 setActionEnabled(BACK | NEXT | CANCEL);
608             } else {
609                 VAGlobals.printDebug("README");
610                 state_ = README;
611                 setActionEnabled(BACK | NEXT | CANCEL);
612                 step_ = ui_.createReadmeStep();
613                 ((VAReadmeStep) step_).setText(getClass().getResourceAsStream(
614                         "readme.txt"));
615             }
616             break;
617         }
618         case DIRECTORY: {
619             VAGlobals.printDebug("UPGRADE");
620             state_ = UPGRADE;
621             setActionEnabled(0);
622             step_ = ui_.createUpgradeStep();
623             checkUpgrade(sharedDir_, uInfo_);
624             if ((!(VAGlobals.APP_VERSION.equals(uInfo_.lastVersion())))
625                     && uInfo_.upgrade && (!uInfo_.forceUpgrade)) {
626                 VAUpgradeStep ustep = (VAUpgradeStep) step_;
627                 ustep.setChoiceEnabled(true);
628             }
629             setActionEnabled(BACK | NEXT | CANCEL);
630             break;
631         }
632         case INSTALL: {
633             if (uInfo_.upgrade) {
634                 state_ = UPGRADE;
635                 setActionEnabled(0);
636                 step_ = ui_.createUpgradeStep();
637                 checkUpgrade(sharedDir_, uInfo_);
638                 setActionEnabled(BACK | NEXT | CANCEL);
639             } else {
640                 VAGlobals.printDebug("DIRECTORY");
641                 state_ = DIRECTORY;
642                 setActionEnabled(BACK | NEXT | CANCEL);
643                 step_ = ui_.createDirectoryStep();
644                 ((VADirectoryStep) step_).setDirectory(new File JavaDoc(
645                         VAGlobals.DEST_PATH));
646             }
647             break;
648         }
649         default: {
650             VAGlobals.printDebug("can't go back...");
651             break;
652         }
653         }
654     }
655
656     public void redoStep() {
657         switch (state_) {
658         case START: {
659             setActionEnabled(NEXT | CANCEL);
660             step_ = ui_.createSetupLanguageStep();
661             break;
662         }
663         case WELCOME: {
664             {
665                 setActionEnabled(BACK | NEXT | CANCEL);
666             }
667             step_ = ui_.createWelcomeStep();
668             break;
669         }
670         case LICENSE: {
671             setActionEnabled(BACK | NEXT | CANCEL);
672             step_ = ui_.createLicenseStep();
673             ((VALicenseStep) step_).setText(getClass().getResourceAsStream(
674                     "license.txt"));
675             break;
676         }
677         case README: {
678             setActionEnabled(BACK | NEXT | CANCEL);
679             step_ = ui_.createReadmeStep();
680             ((VAReadmeStep) step_).setText(getClass().getResourceAsStream(
681                     "readme.txt"));
682             break;
683         }
684         case LICENSE_KEY: {
685             VAGlobals.printDebug("LICENSE_KEY");
686             state_ = LICENSE_KEY;
687             setActionEnabled(0);
688             step_ = ui_.createLicenseKeyStep();
689             ((VALicenseKeyStep) step_).setLicenseKeySupport(licenseKeySupport);
690             setActionEnabled(BACK | NEXT | CANCEL);
691             break;
692         }
693         case UPGRADE: {
694             setActionEnabled(0);
695             step_ = ui_.createUpgradeStep();
696             checkUpgrade(sharedDir_, uInfo_);
697             if ((!(VAGlobals.APP_VERSION.equals(uInfo_.lastVersion())))
698                     && uInfo_.upgrade && (!uInfo_.forceUpgrade)) {
699                 VAUpgradeStep ustep = (VAUpgradeStep) step_;
700                 ustep.setChoiceEnabled(true);
701             }
702             setActionEnabled(BACK | NEXT | CANCEL);
703             break;
704         }
705         case DIRECTORY: {
706             setActionEnabled(BACK | NEXT | CANCEL);
707             step_ = ui_.createDirectoryStep();
708             ((VADirectoryStep) step_)
709                     .setDirectory(new File JavaDoc(VAGlobals.DEST_PATH));
710             break;
711         }
712         case INSTALL: {
713             setActionEnabled(BACK | NEXT | CANCEL);
714             step_ = ui_.createInstallStep();
715             break;
716         }
717         case SHORTCUTS: {
718             setActionEnabled(NEXT);
719             step_ = ui_.createShortcutStep();
720             break;
721         }
722         case END: {
723             setActionEnabled(FINISH);
724             step_ = ui_.createEndStep();
725             ((VAEndStep) step_).setStats(stats_);
726             break;
727         }
728         }
729     }
730
731     private File JavaDoc checkDirectory(File JavaDoc dir) {
732         File JavaDoc res = null;
733         // CVDL CHANGED if one wants to install into the existing directory
734
// /tmp,
735
// the installer doesn't have to check if / is writable therefore parten
736
// = dir and NOT parent = dir.getParentFile()
737
//OK...
738
//File parent=dir.getParentFile();
739
File JavaDoc parent = new VAFile(dir);
740         while (parent != null) {
741             if (parent.exists()) {
742                 if (!parent.canWrite() && !IS_WIN)
743                     res = parent;
744                 else
745                     res = null;
746                 break;
747             }
748             parent = parent.getParentFile();
749         }
750         return res;
751     }
752
753     private void createShortcuts(File JavaDoc sharedDir) {
754         int i, numEntries;
755         LogInfo logInfo;
756         Vector JavaDoc oldLog;
757         PrintWriter JavaDoc log;
758         Set JavaDoc shortcuts;
759         Iterator JavaDoc scIt;
760         String JavaDoc tempString;
761         try {
762             Vector JavaDoc oldlog = loadLogFile(new File JavaDoc(sharedDir.getAbsolutePath()
763                     + File.separator + "vai_" + VAGlobals.APP_NAME + "_"
764                     + VAGlobals.APP_VERSION + File.separator + "shortcuts.vai"));
765             log = new PrintWriter JavaDoc(new FileWriter JavaDoc(sharedDir.getAbsolutePath()
766                     + File.separator + "vai_" + VAGlobals.APP_NAME + "_"
767                     + VAGlobals.APP_VERSION + File.separator + "shortcuts.vai"));
768             logInfo = new LogInfo();
769             logInfo.log = log;
770             logInfo.oldlog = oldlog;
771             scIt = oldlog.iterator();
772             shortcuts = new java.util.LinkedHashSet JavaDoc();
773             while (scIt.hasNext()) {
774                 shortcuts.add(scIt.next());
775             }
776             if (VAGlobals.CREATE_UNINSTALL_SHORTCUT) {
777                 if (VAGlobals.DEBUG)
778                     VAGlobals.printDebug("create uninstall shortcut");
779                 List JavaDoc entry = new ArrayList JavaDoc();
780                 if (launchparms != null)
781                     entry.addAll(Arrays.asList(launchparms));
782                 String JavaDoc exe = VAGlobals.DEST_PATH
783                         + System.getProperty("file.separator") + "uninstall_"
784                         + VAGlobals.APP_NAME + "_" + VAGlobals.APP_VERSION;
785                 if (IS_WIN)
786                     exe += ".bat";
787                 else if (IS_UNIX)
788                     exe += ".sh";
789                 VAShortcutEntry e = new VAShortcutEntry("Uninstall "
790                         + VAGlobals.APP_NAME, exe);
791                 e.setUninstall(true);
792                 e.setCreateOnDesktop(false);
793                 entry.add(e);
794                 launchparms = new VAShortcutEntry[entry.size()];
795                 entry.toArray(launchparms);
796             }
797             if (launchparms != null) {
798                 if (IS_UNIX) {
799                     VALinkLinux.createAll(this.launchparms, shortcuts);
800
801                 } else if (IS_WIN) {
802                     VALinkWindows.create(launchparms, sharedDir,
803                             installClassName_, shortcuts);
804                 } else {
805                     ui_.showError(new Exception JavaDoc(VAGlobals
806                             .i18n("Setup_SorryFeatureNotImplemented")));
807                 }
808             }
809             scIt = shortcuts.iterator();
810             while (scIt.hasNext()) {
811                 tempString = (String JavaDoc) scIt.next();
812                 log.println(tempString);
813             }
814             logInfo.close();
815         } catch (IOException JavaDoc e) {
816             ui_.showError(e);
817         }
818     }
819
820     private void startInstall(File JavaDoc sharedDir, UpgradeInfo uInfo) {
821         VAInstallStep step = (VAInstallStep) step_;
822         LogInfo logInfo = new LogInfo();
823         ObjectInputStream JavaDoc infos = null;
824         try {
825             if (uInfo.upgrade)
826                 VAGlobals.printDebug("Upgrade mode");
827             else
828                 VAGlobals.printDebug("Install mode");
829             step.status(VAGlobals.i18n("Setup_ExtractingUninstaller"));
830             File JavaDoc oldlogfile = extractUninstallFiles(sharedDir, uInfo.upgrade,
831                     uInfo.lastVersion());
832             infos = new ObjectInputStream JavaDoc(getClass().getResourceAsStream(
833                     "archive_infos"));
834             // open log of installed file names
835
FileWriter JavaDoc filewrtr = new FileWriter JavaDoc(sharedDir.getAbsolutePath()
836                     + File.separator + "vai_" + VAGlobals.APP_NAME + "_"
837                     + VAGlobals.APP_VERSION + File.separator + "uninstall.vai");
838             logInfo.log = new PrintWriter JavaDoc(filewrtr);
839             logInfo.filewriter = filewrtr;
840             // create directory for installed package
841
File JavaDoc destPath = new File JavaDoc(computeLocalPath(""));
842             step.details("D " + destPath);
843             if ((!destPath.exists()) && (!destPath.mkdirs())) {
844                 throw new IOException JavaDoc(VAGlobals
845                         .i18n("Setup_NotCreateDirectory")
846                         + " " + destPath);
847             }
848             logInfo.log.println(destPath.getAbsolutePath());
849             // custom pre-processing
850
if (customPrePostClassName_.length() > 0)
851                 callPreCustom(logInfo.log, uInfo_, step);
852             step.status(VAGlobals.i18n("Setup_DecompressingFiles"));
853             int nbrFiles = infos.readInt();
854             unzip(licenseKeySupport.decodeStream(getClass()
855                     .getResourceAsStream("archive.zip")), nbrFiles, sharedDir,
856                     uInfo.upgrade, logInfo, oldlogfile);
857             step.status(VAGlobals.i18n("Setup_GeneratingLaunchScripts"));
858             launchparms = generateLaunchScripts(infos, logInfo);
859             ui_.uiSleep(2000);
860             step.status(VAGlobals.i18n("Setup_LaunchScriptsGenerated"));
861             ui_.uiSleep(1000);
862             step.status(VAGlobals.i18n("Setup_GeneratingUninstallScript"));
863             generateUninstallScripts(sharedDir, logInfo);
864             ui_.uiSleep(2000);
865             step.status(VAGlobals.i18n("Setup_UninstallScriptGenerated"));
866             ui_.uiSleep(1000);
867             if (IS_UNIX) {
868                 step.status(VAGlobals.i18n("Setup_RestoringExeAttributes"));
869                 restoreUnixExecutables(infos);
870                 ui_.uiSleep(2000);
871                 step.status(VAGlobals.i18n("Setup_ExeAttributesRestored"));
872                 ui_.uiSleep(1000);
873             }
874             if (IS_WIN) {
875                 step.status(VAGlobals.i18n("Setup_UpdatingWindowsRegistry"));
876                 updateWindowsRegistry(sharedDir, uInfo.upgrade, uInfo
877                         .lastVersion());
878                 ui_.uiSleep(2000);
879                 step.status(VAGlobals.i18n("Setup_WindowsRegistryUpdated"));
880                 ui_.uiSleep(1000);
881             }
882             if (customPrePostClassName_.length() > 0)
883                 callPostCustom(logInfo.log, uInfo_, step);
884             logInfo.close();
885             infos.close();
886             infos = null;
887             if (oldlogfile != null)
888                 copyShortcutLog(sharedDir, new File JavaDoc(oldlogfile.getParent(),
889                         "shortcuts.vai"));
890             removeBackups();
891             step.status(VAGlobals.i18n("Setup_InstallationComplete"));
892             ui_.uiSleep(1000);
893         } catch (Exception JavaDoc e) {
894             System.err.println(e.getMessage()); // DEBUG
895
e.printStackTrace(System.err);
896             VAGlobals.printDebug("exception caught - closing logInfo"); //DEBUG
897
if (logInfo != null) {
898                 logInfo.close();
899             } else {
900                 VAGlobals.printDebug("logInfo is null!"); //DEBUG
901
}
902             if (infos != null) {
903                 try {
904                     infos.close();
905                 } catch (IOException JavaDoc iox) {
906                     VAGlobals.printDebug("exception closing infos "
907                             + iox.getMessage());
908                     //DEBUG
909
}
910             }
911             exitOnError(e);
912         } //catch
913
}
914
915     protected void exitOnError(Throwable JavaDoc e) {
916         cleanInstall(sharedDir_, uInfo_);
917         super.exitOnError(e);
918     }
919
920     private final void callPostCustom(PrintWriter JavaDoc filelog, UpgradeInfo uInfo,
921             VAInstallStep step) throws Exception JavaDoc {
922         boolean rc;
923         VAGlobals.printDebug("begin custom post-install/upgrade");
924         step.status(VAGlobals.i18n("Custom_Mopping..."));
925
926         if (uInfo.upgrade)
927             rc = customUpgrade("postUpgrade", filelog, uInfo.lastVersion(),
928                     step);
929         else
930             rc = customInstall("postInstall", filelog, step);
931         if (!rc) {
932             VAGlobals
933                     .printDebug("custom postInstall/postUpgrade returned false");
934             throw new IOException JavaDoc(VAGlobals.i18n("Setup_PostFailed"));
935         }
936         VAGlobals.printDebug("end custom post-install/upgrade - OK");
937     }
938
939     private final void callPreCustom(PrintWriter JavaDoc filelog, UpgradeInfo uInfo,
940             VAInstallStep step) throws Exception JavaDoc {
941         VAGlobals.printDebug("begin custom pre-install/upgrade");
942         step.status(VAGlobals.i18n("Custom_Preparing..."));
943         boolean rc;
944         if (uInfo.upgrade)
945             rc = customUpgrade("preUpgrade", filelog, uInfo.lastVersion(), step);
946         else
947             rc = customInstall("preInstall", filelog, step);
948         if (!rc) {
949             VAGlobals.printDebug("custom preInstall/preUpgrade returned false");
950             throw new IOException JavaDoc(VAGlobals.i18n("Setup_PreFailed"));
951         }
952         VAGlobals.printDebug("end custom pre-install/upgrade - OK");
953     }
954
955     // static for use by VAUninstall
956
/** Call method that returns boolean. Unwrap InvocationTargetException. */
957     public static final boolean callReflect(Method JavaDoc method, Object JavaDoc[] args)
958             throws Exception JavaDoc {
959         try {
960             return ((Boolean JavaDoc) method.invoke(null, args)).booleanValue();
961         } catch (InvocationTargetException JavaDoc tie) {
962             throw ((Exception JavaDoc) tie.getTargetException());
963         }
964     }
965
966     private final boolean customInstall(String JavaDoc method_name,
967             PrintWriter JavaDoc filelog, VAInstallStep step) throws Exception JavaDoc {
968         Class JavaDoc custom = Class.forName(customPrePostClassName_);
969         Method JavaDoc method = custom.getMethod(method_name, new Class JavaDoc[] {
970                 PrintWriter JavaDoc.class, VAInstallStep.class });
971         Object JavaDoc[] args = new Object JavaDoc[] { filelog, step };
972         return callReflect(method, args);
973     }
974
975     private final boolean customUpgrade(String JavaDoc method_name,
976             PrintWriter JavaDoc filelog, String JavaDoc last_version, VAInstallStep step)
977             throws Exception JavaDoc {
978         Class JavaDoc custom = Class.forName(customPrePostClassName_);
979         Method JavaDoc method = custom.getMethod(method_name, new Class JavaDoc[] {
980                 String JavaDoc.class, PrintWriter JavaDoc.class, VAInstallStep.class });
981         Object JavaDoc[] args = new Object JavaDoc[] { last_version, filelog, step };
982         return callReflect(method, args);
983     }
984
985     private File JavaDoc findVAISharedDir() {
986         File JavaDoc destPath = null;
987         if (IS_ROOT) {
988             if (IS_WIN) {
989                 // chercher dans la Regedit l'emplacement de C:\Program
990
// Files\Common Files
991
// ou C:\windows\Application Data
992
// Key:
993
// HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\CommonFilesDir
994
try {
995                     RegistryKey sharedDirKey = Registry.HKEY_LOCAL_MACHINE
996                             .openSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion");
997                     destPath = new File JavaDoc(sharedDirKey
998                             .getStringValue("CommonFilesDir"));
999                     sharedDirKey.closeKey();
1000                } catch (Exception JavaDoc rex) {
1001                    destPath = null;
1002                }
1003            } else if (IS_UNIX) {
1004                // on cherche /usr/share
1005
destPath = new File JavaDoc("/usr/share");
1006                if (!destPath.exists()) {
1007                    // on cherche /opt/share
1008
destPath = new File JavaDoc("/opt/share");
1009                }
1010            }
1011            // if (!destPath.exists()) {
1012
// throw new IOException(VAGlobals
1013
// .i18n("Setup_CouldNotFindVAInstall"));
1014
// }
1015
if (destPath != null) {
1016                destPath = new File JavaDoc(destPath, "vainstall");
1017                if (!destPath.exists()) {
1018                    destPath.mkdirs();
1019                }
1020            }
1021        }
1022        //this is created by default below
1023
// else { // user mode
1024
// if (IS_WIN) {
1025
// destPath = new File(System.getProperty("user.home")
1026
// + File.separator + "vainstall");
1027
// } else if (IS_UNIX) {
1028
// destPath = new File(System.getProperty("user.home")
1029
// + File.separator + ".vainstall");
1030
// }
1031
// if (!destPath.exists()) {
1032
// destPath.mkdirs();
1033
// }
1034
// }
1035
//if the dest path doesn't exist (USER MODE) or if the dest path can't
1036
// be written
1037
//we create the default one 'user.home/.vainstall'
1038
if ((destPath == null) || (!destPath.exists())
1039                || !new VAFile(destPath).canWrite()) {
1040            //root mode: warn that we use the default path
1041
if (IS_ROOT) {
1042                VAGlobals.printDebug("Could not find common dir in registry:");
1043                VAGlobals.printDebug("user.home/.vainstall");
1044            }
1045            destPath = new File JavaDoc(System.getProperty("user.home")
1046                    + File.separator + ".vainstall");
1047            if (!destPath.exists())
1048                destPath.mkdirs();
1049        }
1050        return destPath;
1051    }
1052
1053    private File JavaDoc extractUninstallFiles(File JavaDoc _destPath, boolean upgrade,
1054            String JavaDoc lastVer) throws IOException JavaDoc {
1055        boolean oldClassCopied = false;
1056        File JavaDoc destPath = new File JavaDoc(_destPath, "vai_" + VAGlobals.APP_NAME + "_"
1057                + VAGlobals.APP_VERSION);
1058        File JavaDoc oldlog = null;
1059        if (upgrade) {
1060            File JavaDoc lastVerPath = new File JavaDoc(_destPath, "vai_" + VAGlobals.APP_NAME
1061                    + "_" + lastVer);
1062            // intended dest matches existing dest; rename existing dest
1063
if (destPath.equals(lastVerPath)) {
1064                File JavaDoc bkdir = new File JavaDoc(destPath.getAbsolutePath() + ".bak");
1065                if (!destPath.renameTo(bkdir)) {
1066                    // Lame message, but I don't understand resource system
1067
throw new IOException JavaDoc(VAGlobals
1068                            .i18n("Setup_NotCreateDirectory")
1069                            + " " + destPath);
1070                } //destPath.rename
1071
oldlog = new File JavaDoc(bkdir.getAbsolutePath()
1072                        + System.getProperty("file.separator")
1073                        + "uninstall.vai");
1074                lastVerPath = bkdir;
1075            } else { //destPath.equals
1076
oldlog = new File JavaDoc(lastVerPath.getAbsolutePath()
1077                        + System.getProperty("file.separator")
1078                        + "uninstall.vai");
1079            }
1080            // create destination dir
1081
if ((!destPath.exists()) && (!destPath.mkdirs())) {
1082                throw new IOException JavaDoc(VAGlobals
1083                        .i18n("Setup_NotCreateDirectory")
1084                        + " " + destPath);
1085            }
1086            if (uInfo_.module)
1087                oldClassCopied = copyOldSetupClass(lastVerPath, destPath);
1088        } else { // not upgrade
1089
if ((!destPath.exists()) && (!destPath.mkdirs())) {
1090                throw new IOException JavaDoc(VAGlobals
1091                        .i18n("Setup_NotCreateDirectory")
1092                        + " " + destPath);
1093            }
1094        } // not upgrade
1095
dirty_ = true;
1096        // nettoyage
1097
File JavaDoc[] ls = destPath.listFiles(); // shouldn't be needed; kept to be
1098
// safe
1099
for (int i = 0; i < ls.length; i++) {
1100            if (!oldClassCopied)
1101                ls[i].delete();
1102            else if (!ls[i].getPath().equals(
1103                    destPath.getAbsolutePath() + File.separator
1104                            + installClassName_ + ".class"))
1105                ls[i].delete();
1106        }
1107        FileOutputStream JavaDoc out = null;
1108        FileInputStream JavaDoc in = null;
1109        byte[] buf = new byte[0];
1110        int read = 0;
1111        // Install class
1112
if (!oldClassCopied && (installClassSize_ > 0 || jarOffset_ > 0)) { // !=
1113
// jar
1114
// target
1115
out = new FileOutputStream JavaDoc(destPath.getAbsolutePath()
1116                    + File.separator + installClassName_ + ".class");
1117            in = new FileInputStream JavaDoc(fileWithArchive_);
1118            if (installClassOffset_ > 0) {
1119                in.skip(installClassOffset_);
1120            }
1121            buf = new byte[0];
1122            if (installClassSize_ < 0)
1123                buf = new byte[(int) jarOffset_];
1124            else
1125                buf = new byte[(int) installClassSize_];
1126            read = in.read(buf, 0, buf.length);
1127            out.write(buf, 0, read);
1128            out.close();
1129            in.close();
1130        }
1131        // install.jar
1132
in = new FileInputStream JavaDoc(fileWithArchive_);
1133        if (jarOffset_ > 0) {
1134            in.skip(jarOffset_);
1135        }
1136        JarInputStream JavaDoc jar = new JarInputStream JavaDoc(in);
1137        JarOutputStream JavaDoc outJar = new JarOutputStream JavaDoc(new FileOutputStream JavaDoc(
1138                destPath.getAbsolutePath() + File.separator + "install.jar"));
1139        ZipEntry JavaDoc entry = jar.getNextEntry();
1140        while (entry != null) {
1141            String JavaDoc entryName = entry.getName();
1142            if (entryName
1143                    .equals("com/memoire/vainstall/resources/vainstall.properties")) {
1144                // we handle this file special
1145
} else if (entryName.equals(installClassName_ + ".class")
1146                    && !oldClassCopied) {
1147                // this is the install class which is inside the jar in jar
1148
// target
1149
// we have to extract it and put it in the uninstall dir
1150
out = new FileOutputStream JavaDoc(destPath.getAbsolutePath()
1151                        + File.separator + installClassName_ + ".class");
1152                buf = new byte[2048];
1153                read = jar.read(buf);
1154                while (read > 0) {
1155                    out.write(buf, 0, read);
1156                    read = jar.read(buf);
1157                }
1158                out.close();
1159            } else if (!entryName.endsWith(".zip")) {
1160                // *******************
1161
buf = new byte[2048];
1162                ByteArrayOutputStream JavaDoc bos = new ByteArrayOutputStream JavaDoc();
1163                while (true) {
1164                    read = jar.read(buf);
1165                    if (read == -1)
1166                        break;
1167                    bos.write(buf, 0, read);
1168                }
1169                ByteArrayInputStream JavaDoc bais = new ByteArrayInputStream JavaDoc(bos
1170                        .toByteArray());
1171                bos.close();
1172                // *******************
1173
ZipEntry JavaDoc outEntry = new ZipEntry JavaDoc(entryName);
1174                CRC32 JavaDoc crc = new CRC32 JavaDoc();
1175                outEntry.setCrc(crc.getValue());
1176                // outEntry.setSize(entry.getSize());
1177
outEntry.setSize(bos.toByteArray().length);
1178                outJar.putNextEntry(outEntry);
1179                buf = new byte[512];
1180                read = bais.read(buf, 0, buf.length);
1181                while (read > 0) {
1182                    crc.update(buf, 0, read);
1183                    outJar.write(buf, 0, read);
1184                    read = bais.read(buf, 0, buf.length);
1185                }
1186                bais.close();
1187                outEntry.setCrc(crc.getValue());
1188                outJar.closeEntry();
1189            }
1190            jar.closeEntry();
1191            entry = jar.getNextEntry();
1192        }
1193        // HFALK
1194
// get vainstall.properties
1195
InputStream JavaDoc pin = getClass().getResourceAsStream(
1196                "resources/vainstall.properties");
1197        Properties JavaDoc prop = new Properties JavaDoc();
1198        try {
1199            prop.load(pin);
1200        } catch (IOException JavaDoc exc) {
1201            // ignore at the moment
1202
}
1203        if (language == null)
1204            language = "default";
1205        prop.setProperty("vainstall.destination.language", language);
1206        ZipEntry JavaDoc outEntry = new ZipEntry JavaDoc(
1207                "com/memoire/vainstall/resources/vainstall.properties");
1208        CRC32 JavaDoc crc = new CRC32 JavaDoc();
1209        outEntry.setCrc(crc.getValue());
1210        outEntry.setSize(prop.size());
1211        outJar.putNextEntry(outEntry);
1212        prop.store(outJar, VAGlobals.NAME + " " + VAGlobals.VERSION);
1213        outEntry.setCrc(crc.getValue());
1214        outJar.closeEntry();
1215        jar.close();
1216        outJar.close();
1217        in.close();
1218        return oldlog;
1219    }
1220
1221    private VAShortcutEntry[] generateLaunchScripts(ObjectInputStream JavaDoc infos,
1222            LogInfo logInfo) throws IOException JavaDoc {
1223        VAInstallStep step = (VAInstallStep) step_;
1224        Vector JavaDoc scripts = null;
1225        try {
1226            scripts = (Vector JavaDoc) infos.readObject();
1227        } catch (ClassNotFoundException JavaDoc e) {
1228            ui_.showError(new Exception JavaDoc(VAGlobals
1229                    .i18n("Setup_UnableToGenerateScripts")));
1230            return null;
1231        }
1232        if (scripts == null) {
1233            step.status(VAGlobals.i18n("Setup_NoLaunchScript"));
1234            VAGlobals.printDebug("No launch script");
1235            return null;
1236        }
1237        if (!IS_WIN && !IS_UNIX) {
1238            ui_.showError(new Exception JavaDoc(VAGlobals
1239                    .i18n("Setup_SorryScriptsNotSupported")));
1240            return null;
1241        }
1242        String JavaDoc NL = System.getProperty("line.separator");
1243        ArrayList JavaDoc links = new ArrayList JavaDoc();
1244        for (int i = 0; i < scripts.size(); i++) {
1245            String JavaDoc sbloc = (String JavaDoc) scripts.get(i);
1246            StringTokenizer JavaDoc tk = new StringTokenizer JavaDoc(sbloc, "\n");
1247            if (tk.countTokens() % 2 != 0) {
1248                ui_.showError(new Exception JavaDoc(VAGlobals
1249                        .i18n("Setup_UnSupportedScriptSkipping")));
1250                System.err.println("bad bloc= " + sbloc);
1251                return null;
1252            }
1253
1254            Properties JavaDoc props = new Properties JavaDoc();
1255            while (tk.hasMoreTokens()) {
1256                props.put(tk.nextToken(), tk.nextToken());
1257            }
1258            //tk must not be used ...
1259
tk = null;
1260            final String JavaDoc cmd = props.getProperty("CMD");
1261            if ("JavaLauncher".equals(cmd) || "JarLauncher".equals(cmd)) {
1262                StringBuffer JavaDoc script = new StringBuffer JavaDoc(300);
1263                if (IS_WIN) {
1264                    script.append("REM Launch script").append(NL).append(NL);
1265                    script.append("set VA_APP_HOME=").append(
1266                            VAGlobals.DEST_PATH).append(File.separatorChar)
1267                            .append(NL);
1268                } else {
1269                    script.append("#!/bin/sh").append(NL);
1270                    script.append("### Launch Script for ").append(
1271                            VAGlobals.APP_NAME).append(NL).append(NL);
1272                    script.append("VA_APP_HOME=`dirname $0`").append(NL);
1273                }
1274                //cd to the request directory
1275
String JavaDoc cdTo = props.getProperty("ScriptChangeDirectory", null);
1276                if (cdTo != null) {
1277                    File JavaDoc dirTo = new File JavaDoc(expandDirectory(cdTo, false, uInfo_));
1278                    if (dirTo.exists()) {
1279                        if (IS_UNIX) {
1280                            script.append("cd ").append('"').append(
1281                                    dirTo.getAbsolutePath()).append('"')
1282                                    .append(NL);
1283                        } else {
1284                            String JavaDoc s = dirTo.getAbsolutePath();
1285                            int idx = s.indexOf(":");
1286                            //to split 'C:My Path' to
1287
//C:
1288
//cd 'My Path'
1289
if (idx > 0) {
1290                                script.append(s.substring(0, idx + 1)).append(
1291                                        NL);
1292                                script.append("cd ").append('"').append(s);
1293                                if (s.endsWith(":"))
1294                                    script.append(File.pathSeparatorChar);
1295                                script.append('"');
1296                            } else
1297                                script.append("cd ").append('"').append(s)
1298                                        .append('"');
1299                        }
1300                        script.append(NL);
1301                    }
1302                }
1303                StringBuffer JavaDoc commandBuf = new StringBuffer JavaDoc();
1304                String JavaDoc javaMode = props.getProperty("JavaMode", "console");
1305                if ("console".equals(javaMode)) {
1306                    commandBuf.append(JAVA_EXE_QUOTE).append(JAVA_EXE).append(
1307                            JAVA_EXE_QUOTE);
1308                } else {
1309                    //we use the start command to close the dos frame just
1310
// after java is launched
1311
if (IS_WIN)
1312                        commandBuf.append("start ");
1313                    commandBuf.append(JAVA_EXE_QUOTE).append(JAVAW_EXE).append(
1314                            JAVA_EXE_QUOTE);
1315                }
1316                //java args
1317
String JavaDoc JavaArgs = props.getProperty("JavaArgs", "");
1318                StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(JavaArgs, ",");
1319                while (tokenizer.hasMoreTokens())
1320                    commandBuf.append(" ").append(tokenizer.nextToken());
1321                //class path
1322
String JavaDoc classPath = props.getProperty("ClassPath", "");
1323                tokenizer = new StringTokenizer JavaDoc(classPath, ",");
1324                if (tokenizer.countTokens() > 0) {
1325                    commandBuf.append(" -cp \"");
1326                    int n = 0;
1327                    while (tokenizer.hasMoreElements()) {
1328                        String JavaDoc cp = "";
1329                        if (n++ > 0)
1330                            cp += File.pathSeparator;
1331                        String JavaDoc cpi = tokenizer.nextToken();
1332                        if (!new File JavaDoc(cpi).isAbsolute()) {
1333                            if (IS_WIN)
1334                                cp += "%VA_APP_HOME%";
1335                            else
1336                                cp += "$VA_APP_HOME/";
1337                        }
1338
1339                        cp += cpi;
1340                        if (File.separatorChar != '/')
1341                            cp = cp.replace('/', File.separatorChar);
1342                        commandBuf.append(cp);
1343                    }
1344                    commandBuf.append("\"");
1345                }
1346                String JavaDoc appArgs = "";
1347                if ("JavaLauncher".equals(cmd)) {
1348                    String JavaDoc tkClass = props.getProperty("Class");
1349                    commandBuf.append(" ").append(tkClass);
1350                    appArgs = props.getProperty("ClassArgs", "");
1351                } else if ("JarLauncher".equals(cmd)) {
1352                    String JavaDoc tkJar = props.getProperty("Jar");
1353                    if (!new File JavaDoc(tkJar).isAbsolute()) {
1354                        if (IS_WIN)
1355                            tkJar = "%VA_APP_HOME%" + tkJar;
1356                        else
1357                            tkJar = "$VA_APP_HOME/" + tkJar;
1358                    }
1359
1360                    commandBuf.append(" -jar \"").append(tkJar).append('"');
1361                    appArgs = props.getProperty("JarArgs", "");
1362                }
1363                tokenizer = new StringTokenizer JavaDoc(appArgs, ",");
1364                if (tokenizer.countTokens() > 0) {
1365                    while (tokenizer.hasMoreTokens()) {
1366                        commandBuf.append(" \"").append(tokenizer.nextToken())
1367                                .append("\"");
1368                    }
1369                }
1370                commandBuf = new StringBuffer JavaDoc(replace(commandBuf.toString(),
1371                        "[INSTALL_DIR]", new File JavaDoc(VAGlobals.DEST_PATH)
1372                                .getAbsolutePath()));
1373                if (IS_WIN)
1374                    commandBuf.append(" %1 %2 %3 %4 %5 %6 %7 %8 %9");
1375                else
1376                    commandBuf.append(" $*");
1377
1378                String JavaDoc sname = props.getProperty("ScriptName");
1379                String JavaDoc exe = computeLocalPath(sname);
1380                if (IS_WIN)
1381                    exe += ".bat";
1382                else
1383                    exe += ".sh";
1384                File JavaDoc sfile = new File JavaDoc(exe);
1385                step.details(sfile.getAbsolutePath());
1386                if (!logInfo.oldlog.contains(sfile.getAbsolutePath()))
1387                    logInfo.log.println(sfile.getAbsolutePath());
1388                PrintWriter JavaDoc scriptFile = null;
1389                try {
1390                    scriptFile = new PrintWriter JavaDoc(new FileWriter JavaDoc(sfile));
1391                    script.append(commandBuf.toString());
1392                    scriptFile.println(script.toString());
1393                } catch (IOException JavaDoc _e) {
1394                    _e.printStackTrace();
1395                    throw _e;
1396                } finally {
1397                    if (scriptFile != null)
1398                        scriptFile.close();
1399                }
1400
1401                VAShortcutEntry e = new VAShortcutEntry(exe);
1402                String JavaDoc s = props.getProperty("CreateShortcutOnDesktop", null);
1403                if (s != null && s.toLowerCase().equals("false")) {
1404                    e.setCreateOnDesktop(false);
1405                }
1406                if ("console".equals(javaMode))
1407                    e.setLaunchInTerminal(true);
1408                e.setName(sname);
1409                links.add(e);
1410            }
1411        }
1412        VAShortcutEntry[] r = new VAShortcutEntry[links.size()];
1413        links.toArray(r);
1414        return r;
1415    }
1416
1417    private void generateUninstallScripts(File JavaDoc destPath, LogInfo logInfo)
1418            throws IOException JavaDoc {
1419        VAInstallStep step = (VAInstallStep) step_;
1420        if (!IS_WIN && !IS_UNIX) {
1421            ui_.showError(new Exception JavaDoc(VAGlobals
1422                    .i18n("Setup_NotGenerateScript")));
1423            return;
1424        }
1425        destPath = new File JavaDoc(destPath, "vai_" + VAGlobals.APP_NAME + "_"
1426                + VAGlobals.APP_VERSION);
1427        if ((!destPath.exists()) && (!destPath.mkdirs())) {
1428            ui_.showError(new Exception JavaDoc(VAGlobals
1429                    .i18n("Setup_NotCreateDirectory")
1430                    + " " + destPath));
1431            return;
1432        }
1433        // nettoyage
1434
File JavaDoc[] ls = new File JavaDoc(VAGlobals.DEST_PATH)
1435                .listFiles(new SetupFileFilter("uninstall_"
1436                        + VAGlobals.APP_NAME + "_",
1437                        SetupFileFilter.STARTS_WITH, SetupFileFilter.FILTER));
1438        for (int i = 0; i < ls.length; i++) {
1439            ls[i].delete();
1440        }
1441        String JavaDoc sname = "uninstall_" + VAGlobals.APP_NAME + "_"
1442                + VAGlobals.APP_VERSION;
1443        sname = computeLocalPath(sname);
1444        if (IS_WIN)
1445            sname += ".bat";
1446        else
1447            sname += ".sh";
1448        step.details(sname);
1449        File JavaDoc sfile = new File JavaDoc(sname);
1450        PrintWriter JavaDoc script = new PrintWriter JavaDoc(new FileWriter JavaDoc(sfile));
1451        logInfo.log.println(sfile.getAbsolutePath());
1452        if (IS_WIN) {
1453            script.println("REM Uninstall script for " + VAGlobals.APP_NAME
1454                    + "_" + VAGlobals.APP_VERSION);
1455            script.println();
1456        } else {
1457            script.println("#!/bin/sh");
1458            script.println("### Uninstall script for " + VAGlobals.APP_NAME
1459                    + "_" + VAGlobals.APP_VERSION);
1460            script.println();
1461            script.println("stty -icanon");
1462        }
1463        String JavaDoc scriptStr = "";
1464        scriptStr += JAVA_EXE_QUOTE + JAVA_EXE + JAVA_EXE_QUOTE + " -cp \""
1465                + destPath.getAbsolutePath() + "\" ";
1466        if ("no".equalsIgnoreCase(System.getProperty("bluescreen")))
1467            scriptStr += "-Dbluescreen=no ";
1468        scriptStr += installClassName_ + " uninstall \""
1469                + destPath.getAbsolutePath() + "\"";
1470        script.println(scriptStr);
1471        if (IS_UNIX) {
1472            script.println("stty icanon");
1473        }
1474        script.close();
1475    }
1476
1477    private Vector JavaDoc loadLogFile(File JavaDoc _logfile) throws IOException JavaDoc {
1478        Vector JavaDoc res = new Vector JavaDoc();
1479        if (_logfile == null)
1480            return res;
1481        File JavaDoc logfile = _logfile;
1482        if (logfile != null && logfile.exists()) {
1483            LineNumberReader JavaDoc log = new LineNumberReader JavaDoc(new FileReader JavaDoc(logfile));
1484            String JavaDoc line = log.readLine();
1485            while (line != null) {
1486                res.add(line);
1487                line = log.readLine();
1488            }
1489            log.close();
1490        } else {
1491            VAGlobals.printDebug("log not found" + _logfile.getAbsoluteFile());
1492        }
1493        return res;
1494    }
1495
1496    private void unzip(InputStream JavaDoc archive, int nbrFiles, File JavaDoc sharedDir,
1497            boolean upgrade, LogInfo logInfo, File JavaDoc oldlogfile)
1498            throws IOException JavaDoc {
1499        VAInstallStep step = (VAInstallStep) step_;
1500        int count = 0;
1501        ZipInputStream JavaDoc zip = new ZipInputStream JavaDoc(new GZIPInputStream JavaDoc(archive));
1502        step.setProgression(0);
1503        dirty_ = true;
1504        Vector JavaDoc oldlog = loadLogFile(oldlogfile);
1505        PrintWriter JavaDoc log = logInfo.log;
1506        logInfo.oldlog = oldlog;
1507        for (int i = 1; i < oldlog.size(); i++) {
1508            String JavaDoc sentry = (String JavaDoc) oldlog.get(i);
1509            String JavaDoc s = sentry;
1510            int ind = sentry.lastIndexOf(File.separator);
1511            if (ind > 0)
1512                s = sentry.substring(ind + 1);
1513            if (!s.startsWith("uninstall_" + VAGlobals.APP_NAME + "_"))
1514                log.println(sentry);
1515        }
1516        ZipEntry JavaDoc entry = zip.getNextEntry();
1517        while (entry != null) {
1518            File JavaDoc dest = new File JavaDoc(computeLocalPath(entry.getName()));
1519            if (entry.isDirectory()) {
1520                if (!dest.exists()) {
1521                    makeDirs(dest, logInfo);
1522                    //zip.closeEntry(); close at line 1733
1523
}
1524            } else {
1525                File JavaDoc destParent = dest.getParentFile();
1526                if ((destParent != null) && (!destParent.exists())) {
1527                    makeDirs(destParent, logInfo);
1528                }
1529                step.details("F " + dest);
1530                boolean fileExist = dest.exists();
1531                if (fileExist && !dest.canWrite()) {
1532                    ui_.showError(new Exception JavaDoc(VAGlobals
1533                            .i18n("Setup_DirectoryNotAccessible")
1534                            + "\n" + dest.getAbsolutePath()));
1535                }
1536
1537                FileOutputStream JavaDoc out = null;
1538                try {
1539                    out = new FileOutputStream JavaDoc(dest);
1540                    byte buf[] = new byte[4096];
1541                    int read = zip.read(buf, 0, buf.length);
1542                    while (read > 0) {
1543                        out.write(buf, 0, read);
1544                        read = zip.read(buf, 0, buf.length);
1545                    }
1546                } catch (FileNotFoundException JavaDoc _e) {
1547
1548                } catch (IOException JavaDoc _e) {
1549                    if (fileExist)
1550                        ui_.showError(new Exception JavaDoc(VAGlobals
1551                                .i18n("Setup_FileNotCreated")
1552                                + "\n" + dest.getName()));
1553                    else
1554                        throw _e;
1555                    return;
1556                } finally {
1557                    if (out != null)
1558                        out.close();
1559                }
1560                stats_.addFile(dest, VAStats.SUCCESS);
1561                if (!oldlog.contains(dest.getAbsolutePath()))
1562                    log.println(dest.getAbsolutePath());
1563                step.setProgression(++count * 100 / nbrFiles);
1564            }
1565
1566            zip.closeEntry();
1567            entry = zip.getNextEntry();
1568        }
1569        zip.close();
1570    }
1571
1572    private void makeDirs(File JavaDoc dir, LogInfo logInfo) throws IOException JavaDoc {
1573        VAInstallStep step = (VAInstallStep) step_;
1574        File JavaDoc parent = dir.getParentFile();
1575        if ((parent != null) && (!parent.exists())) {
1576            makeDirs(parent, logInfo);
1577        }
1578        step.details("D " + dir);
1579        if (dir.mkdir()) {
1580            stats_.addDirectory(dir, VAStats.SUCCESS);
1581            if (!logInfo.oldlog.contains(dir.getAbsolutePath()))
1582                logInfo.log.println(dir.getAbsolutePath());
1583        } else {
1584            throw new IOException JavaDoc(VAGlobals.i18n("Setup_NotCreateDirectory")
1585                    + " " + dir);
1586        }
1587    }
1588
1589    protected void removeBackups() {
1590        File JavaDoc destPath = new File JavaDoc(sharedDir_, "vai_" + VAGlobals.APP_NAME + "_"
1591                + VAGlobals.APP_VERSION);
1592        if ((uInfo_ == null) || (!uInfo_.upgrade))
1593            return;
1594        File JavaDoc lastVerPath = new File JavaDoc(sharedDir_, "vai_" + VAGlobals.APP_NAME
1595                + "_" + uInfo_.lastVersion());
1596        if (destPath.equals(lastVerPath)) {
1597            lastVerPath = new File JavaDoc(destPath.getAbsolutePath() + ".bak");
1598        }
1599        if (lastVerPath.exists())
1600            deleteDirRecursive(lastVerPath);
1601    }
1602
1603    protected void updateWindowsRegistry(File JavaDoc sharedDir, boolean upgrade,
1604            String JavaDoc lastVer) throws IOException JavaDoc {
1605        File JavaDoc destPath = new File JavaDoc(sharedDir.getAbsolutePath() + File.separator
1606                + "vai_" + VAGlobals.APP_NAME + "_" + VAGlobals.APP_VERSION);
1607        if (upgrade) {
1608            try {
1609                RegistryKey uninstallKey = Registry.HKEY_LOCAL_MACHINE
1610                        .openSubKey(
1611                                "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall",
1612                                RegistryKey.ACCESS_WRITE);
1613                uninstallKey.deleteSubKey(VAGlobals.APP_NAME + " " + lastVer);
1614                uninstallKey.closeKey();
1615            } catch (Exception JavaDoc e) {
1616                ui_.showError(new Exception JavaDoc(VAGlobals
1617                        .i18n("Setup_NotDeleteRegistryKey")
1618                        + " " + VAGlobals.APP_NAME + " " + lastVer));
1619            }
1620        }
1621        try {
1622            RegistryKey newKey = Registry.HKEY_LOCAL_MACHINE.createSubKey(
1623                    "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\"
1624                            + VAGlobals.APP_NAME + " " + VAGlobals.APP_VERSION,
1625                    "", RegistryKey.ACCESS_WRITE);
1626            RegStringValue displayName = new RegStringValue(newKey,
1627                    "DisplayName");
1628            displayName.setData(VAGlobals.APP_NAME + " "
1629                    + VAGlobals.APP_VERSION);
1630            newKey.setValue(displayName);
1631            RegStringValue uninstallString = new RegStringValue(newKey,
1632                    "UninstallString");
1633            String JavaDoc scriptStr = "";
1634            scriptStr += JAVA_EXE_QUOTE + JAVA_EXE + JAVA_EXE_QUOTE + " -cp \""
1635                    + destPath.getAbsolutePath() + "\" ";
1636            if ("no".equalsIgnoreCase(System.getProperty("bluescreen")))
1637                scriptStr += "-Dbluescreen=no ";
1638            scriptStr += installClassName_ + " uninstall \""
1639                    + destPath.getAbsolutePath() + "\"";
1640            uninstallString.setData(scriptStr);
1641            newKey.setValue(uninstallString);
1642            newKey.closeKey();
1643        } catch (Exception JavaDoc e) {
1644            throw new IOException JavaDoc("" + e);
1645        }
1646    }
1647
1648    /**
1649     * 0 : not known 1 : java in path -1: not in path Comment for
1650     * <code>isJavaInPath</code>
1651     */

1652    static int isJavaInPath = 0;
1653
1654    /** @parm winsuffix should be either .exe or w.exe. */
1655    private static final String JavaDoc getJavaExe(String JavaDoc winsuffix) {
1656        StringBuffer JavaDoc sb = new StringBuffer JavaDoc(260);
1657        //fred we test if the the java executable is in path
1658
//if false, we use the full path to the exe
1659
if (isJavaInPath == 0) {
1660            if (VAGlobals.USE_FULL_JAVA_PATH) {
1661                isJavaInPath = -1;
1662            }
1663            //On MS Windows use full path for Java version
1664
// 1.2 or less
1665
else if (IS_WIN
1666                    && ("1.2".compareTo(System.getProperty("java.version")
1667                            .substring(0, 3)) > -1)) {
1668                isJavaInPath = -1;
1669            } else {
1670                try {
1671                    Runtime.getRuntime().exec(
1672                            new String JavaDoc[] { "java", "-version" });
1673                    isJavaInPath = 1;
1674                } catch (IOException JavaDoc _e) {
1675                    isJavaInPath = -1;
1676                }
1677                if (VAGlobals.DEBUG) {
1678                    if (isJavaInPath > 0)
1679                        VAGlobals.printDebug("java is in path");
1680                    else
1681                        VAGlobals.printDebug("java is NOT in path");
1682                }
1683
1684            }
1685        }
1686
1687        if (isJavaInPath < 0) {
1688            sb.append(JAVA_HOME).append(File.separator).append("bin").append(
1689                    File.separator);
1690        }
1691        sb.append("java").append(IS_WIN ? winsuffix : "");
1692        return sb.toString();
1693    }
1694
1695    /**
1696     * Replace parts of a string.
1697     *
1698     * @param _s
1699     * the initial string
1700     * @param _a
1701     * the string to be found
1702     * @param _b
1703     * the string which will replace
1704     * @return the modified string
1705     */

1706    public static final String JavaDoc replace(String JavaDoc _s, String JavaDoc _a, String JavaDoc _b) {
1707        String JavaDoc r = _s;
1708        int i = 0;
1709
1710        if (_b == null)
1711            _b = "";
1712
1713        while ((i = r.indexOf(_a, i)) >= 0) {
1714            r = r.substring(0, i) + _b + r.substring(i + _a.length());
1715            i = i + _b.length();
1716        }
1717        return r;
1718    }
1719
1720    private void restoreUnixExecutables(ObjectInputStream JavaDoc infos) {
1721        VAInstallStep step = (VAInstallStep) step_;
1722        try {
1723            Vector JavaDoc exes = (Vector JavaDoc) infos.readObject();
1724            String JavaDoc[] chmodStr = new String JavaDoc[4 + exes.size()];
1725            chmodStr[0] = "chmod";
1726            chmodStr[1] = "-R";
1727            chmodStr[2] = "a+x";
1728            chmodStr[3] = "";
1729            if (IS_WIN || IS_UNIX) {
1730                chmodStr[3] += computeLocalPath("uninstall_"
1731                        + VAGlobals.APP_NAME + "_" + VAGlobals.APP_VERSION);
1732                if (IS_WIN)
1733                    chmodStr[3] += ".bat";
1734                else
1735                    chmodStr[3] += ".sh";
1736            }
1737            for (int i = 0; i < exes.size(); i++) {
1738                String JavaDoc exe = (String JavaDoc) exes.get(i);
1739                if (exe.startsWith("[SCRIPT]")) {
1740                    exe = exe.substring(8);
1741                    if (IS_WIN)
1742                        exe += ".bat";
1743                    else
1744                        exe += ".sh";
1745                }
1746                chmodStr[4 + i] = computeLocalPath(exe);
1747                step.details(exe);
1748                stats_.addExecutable(new File JavaDoc(chmodStr[4 + i]));
1749            }
1750            String JavaDoc chmod = "";
1751            for (int i = 0; i < chmodStr.length; i++) {
1752                chmod += chmodStr[i] + " ";
1753            }
1754            VAGlobals.printDebug(chmod);
1755            // PrintStream out=System.out;
1756
// PrintStream err=System.err;
1757
// PrintStream nullStream=new PrintStream(new
1758
// ByteArrayOutputStream());
1759
// System.setErr(nullStream);
1760
// System.setOut(nullStream);
1761
Process JavaDoc p = Runtime.getRuntime().exec(chmodStr);
1762            boolean interr = true;
1763            while (interr) {
1764                try {
1765                    p.waitFor();
1766                    interr = false;
1767                } catch (InterruptedException JavaDoc e) {
1768                    interr = true;
1769                }
1770            }
1771            // nullStream.close();
1772
// System.setErr(err);
1773
// System.setOut(out);
1774
if (p.exitValue() != 0)
1775                throw new Exception JavaDoc();
1776        } catch (Exception JavaDoc e) {
1777            VAGlobals.printDebug(e.toString());
1778            ui_.showError(new Exception JavaDoc(VAGlobals
1779                    .i18n("Setup_ErrorRestoringExeAttributes")));
1780        }
1781    }
1782
1783    public static String JavaDoc getWithoutMacro(String JavaDoc dir) {
1784        if (dir == null)
1785            return "";
1786        if (!dir.startsWith("["))
1787            return dir;
1788        int index = dir.indexOf(']');
1789        return dir.substring(index + 1);
1790    }
1791
1792    public static String JavaDoc expandDirectory(String JavaDoc dir, boolean block,
1793            UpgradeInfo uInfo) throws IOException JavaDoc {
1794        String JavaDoc res = null;
1795        if (!dir.startsWith("["))
1796            res = dir;
1797        else {
1798            int index = dir.indexOf(']');
1799            String JavaDoc prefix = dir.substring(1, index).trim();
1800            // we'll try to handle lookup of environment varibles here. The
1801
// syntax is
1802
// [ENV{<name of environment variable}]
1803
// CVDL Debug
1804
/*
1805             * VAGlobals.printDebug("Trying to resolve a shortcut...");
1806             * //ENVIRONMENT VARIABLE if (prefix.startsWith("ENV")) {
1807             * VAGlobals.printDebug("Trying to resolve ENV (original: " +
1808             * prefix); int startOfEnvVariable = prefix.indexOf('{'); int
1809             * endOfEnvVariable = prefix.indexOf('}'); if (startOfEnvVariable >=
1810             * 0 && endOfEnvVariable > startOfEnvVariable + 1) { String
1811             * variableName = prefix.substring(startOfEnvVariable + 1,
1812             * endOfEnvVariable); try { // CVDL Debug
1813             * VAGlobals.printDebug("Trying to get environment variable for " +
1814             * variableName); res =
1815             * ReadEnv.getEnvVars().getProperty(variableName);
1816             * VAGlobals.printDebug("Resovled " + variableName + " to " + res); }
1817             * catch (Throwable e) { VAGlobals.printDebug("received exception " +
1818             * e); throw new IOException(e.getMessage()); } if (res == null) {
1819             * VAGlobals.printDebug("resolved path is null -> exception"); throw
1820             * new IOException("Cannot find variable named " + variableName); } }
1821             * else { new IllegalStateException("Cannot parse the destination
1822             * path!"); } } else
1823             */

1824            //END
1825
if ("HOME".equals(prefix)) {
1826                res = System.getProperty("user.home");
1827                if (IS_WIN && IS_ROOT) {
1828                    if ((res != null) && (res.length() > 3)
1829                            && (res.charAt(1) == ':'))
1830                        res = res.substring(0, 3);
1831                }
1832            }
1833            if ("INSTALL_DIR".equals(prefix)) {
1834                res = new File JavaDoc(VAGlobals.DEST_PATH).getAbsolutePath();
1835            } else if ("C:".equals(prefix)) {
1836                if (IS_WIN)
1837                    res = "C:\\";
1838                else if (IS_UNIX)
1839                    res = "/";
1840                else if (IS_MAC)
1841                    res = ":";
1842            } else if ("PROGRAM".equals(prefix)) {
1843                if (!IS_ROOT) {
1844                    res = System.getProperty("user.home");
1845                } else {
1846                    if (IS_WIN) {
1847                        try {
1848                            RegistryKey programDirKey = Registry.HKEY_LOCAL_MACHINE
1849                                    .openSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion");
1850                            res = programDirKey
1851                                    .getStringValue("ProgramFilesDir");
1852                            programDirKey.closeKey();
1853                        } catch (Exception JavaDoc re) {
1854                            if (block)
1855                                throw new IOException JavaDoc(re.getMessage());
1856                            res = null;
1857                        }
1858                        if (res == null) {
1859                            VAGlobals
1860                                    .printDebug("Could not find program dir in registry:");
1861                            VAGlobals.printDebug("using 'C:\\Program Files'");
1862                            res = "C:\\Program Files";
1863                        }
1864                    } else if (IS_UNIX)
1865                        res = "/usr/local";
1866                }
1867            } else if ("UPDATE".equals(prefix)) {
1868                if (uInfo.versions == null) {
1869                    uInfo.forceUpgrade = true;
1870                    return dir;
1871                } else
1872                    res = uInfo.lastPath().getAbsolutePath();
1873            } else if ("MODULE".equals(prefix)) {
1874                if (uInfo.versions == null) {
1875                    uInfo.forceUpgrade = true;
1876                    uInfo.module = true;
1877                    return dir;
1878                } else
1879                    res = uInfo.lastPath().getAbsolutePath();
1880            } else if ((prefix.length() == 2) && (prefix.endsWith(":"))) {
1881                if (IS_WIN)
1882                    res = prefix.substring(0, 2) + File.separator;
1883                else if (IS_UNIX)
1884                    res = "/";
1885            }
1886            String JavaDoc suffix = "";
1887            if (dir.length() > (index + 1)) {
1888                suffix += dir.substring(index + 1).trim();
1889                if (suffix.startsWith("/"))
1890                    suffix = suffix.substring(1);
1891            }
1892            if (res == null) {
1893                if (block)
1894                    throw new IOException JavaDoc(VAGlobals.i18n("Setup_InvalidDir")
1895                            + dir);
1896                res = System.getProperty("user.dir");
1897            }
1898            res += (File.separator + suffix);
1899        }
1900        return res;
1901    }
1902
1903    private String JavaDoc computeLocalPath(String JavaDoc entry) throws IOException JavaDoc {
1904        String JavaDoc res = expandDirectory(entry, false, uInfo_);
1905        if (res == null)
1906            throw new IOException JavaDoc(VAGlobals.i18n("Setup_InvalidPath") + entry);
1907        if ((!res.startsWith("/")) && (!res.startsWith("C:\\"))
1908                && (!res.startsWith(":")) && (!new File JavaDoc(res).isAbsolute()))
1909            res = VAGlobals.DEST_PATH + "/" + res;
1910        return res.replace('/', File.separatorChar);
1911    }
1912
1913    private void copyShortcutLog(File JavaDoc sharedDir, File JavaDoc oldShortcutLogFile)
1914            throws IOException JavaDoc {
1915        Vector JavaDoc oldlog = loadLogFile(oldShortcutLogFile);
1916        FileWriter JavaDoc filewrtr = new FileWriter JavaDoc(sharedDir.getAbsolutePath()
1917                + File.separator + "vai_" + VAGlobals.APP_NAME + "_"
1918                + VAGlobals.APP_VERSION + File.separator + "shortcuts.vai");
1919        PrintWriter JavaDoc log = new PrintWriter JavaDoc(filewrtr);
1920        for (int i = 0; i < oldlog.size(); i++) {
1921            String JavaDoc sentry = (String JavaDoc) oldlog.get(i);
1922            String JavaDoc s = sentry;
1923            log.println(sentry);
1924        }
1925        log.flush();
1926        log.close();
1927    }
1928
1929    private boolean copyOldSetupClass(File JavaDoc lastVerPath, File JavaDoc destPath)
1930            throws java.io.FileNotFoundException JavaDoc, IOException JavaDoc {
1931        byte[] buf;
1932        File JavaDoc oldClass = new File JavaDoc(lastVerPath.getAbsolutePath() + File.separator
1933                + installClassName_ + ".class");
1934        if (oldClass.exists()) {
1935            FileOutputStream JavaDoc out = new FileOutputStream JavaDoc(destPath
1936                    .getAbsolutePath()
1937                    + File.separator + installClassName_ + ".class");
1938            FileInputStream JavaDoc in = new FileInputStream JavaDoc(oldClass);
1939            buf = new byte[(new Long JavaDoc(oldClass.length())).intValue()];
1940            int read = in.read(buf, 0, buf.length);
1941            out.write(buf, 0, read);
1942            out.close();
1943            in.close();
1944            return true;
1945        } else
1946            return false;
1947    }
1948}
1949
1950class UpgradeInfo {
1951    public boolean module = false;
1952
1953    public boolean forceUpgrade = false;
1954
1955    public boolean upgrade = false;
1956
1957    public String JavaDoc[] versions = null;
1958
1959    public File JavaDoc[] paths = null;
1960
1961    public String JavaDoc lastVersion() {
1962        return versions == null ? null : versions[versions.length - 1];
1963    }
1964
1965    public File JavaDoc lastPath() {
1966        return paths == null ? null : paths[paths.length - 1];
1967    }
1968}
1969
1970class LogInfo {
1971    public PrintWriter JavaDoc log = null;
1972
1973    public FileWriter JavaDoc filewriter = null;
1974
1975    public Vector JavaDoc oldlog = null;
1976
1977    public void close() {
1978        if (log == null) {
1979            if (VAGlobals.DEBUG)
1980                System.out.println("log file null");
1981        } else {
1982            log.flush();
1983            log.close();
1984        }
1985        try {
1986            if (filewriter != null)
1987                filewriter.close();
1988        } catch (IOException JavaDoc e) {
1989            VAGlobals
1990                    .printDebug("LogInfo.close IOException: " + e.getMessage());
1991        }
1992        if (oldlog != null)
1993            oldlog.clear();
1994        oldlog = null;
1995    }
1996}
1997
1998class SetupFileFilter implements FilenameFilter JavaDoc {
1999    public final static int STARTS_WITH = 1;
2000
2001    public final static int ENDS_WITH = 2;
2002
2003    public final static int FILTER = 1;
2004
2005    public final static int EXCEPT = 2;
2006
2007    private String JavaDoc pattern_;
2008
2009    private int mode_;
2010
2011    private int filter_;
2012
2013    public SetupFileFilter(String JavaDoc patt, int mode, int filter) {
2014        pattern_ = patt;
2015        mode_ = mode;
2016        filter_ = filter;
2017    }
2018
2019    public boolean accept(File JavaDoc dir, String JavaDoc f) {
2020        boolean res = true;
2021        if (mode_ == STARTS_WITH)
2022            res = f.startsWith(pattern_);
2023        else if (mode_ == ENDS_WITH)
2024            res = f.endsWith(pattern_);
2025        if (filter_ == EXCEPT)
2026            res = !res;
2027        return res;
2028    }
2029}
2030//DONT WORK WITH JAVAW
2031
// class ReadEnv {
2032
// public static Properties getEnvVars() throws Throwable {
2033
// Process p = null;
2034
// Properties envVars = new Properties();
2035
// Runtime r = Runtime.getRuntime();
2036
// String OS = System.getProperty("os.name").toLowerCase();
2037
// // System.out.println(OS);
2038
// if (OS.indexOf("windows 9") > -1) {
2039
// p = r.exec( "command.com /c set" );
2040
// }
2041
// else if ( (OS.indexOf("nt") > -1) || (OS.indexOf("windows 2000") > -1) ) {
2042
// p = r.exec( "cmd.exe /c set" );
2043
// }
2044
// else {
2045
// // our last hope, we assume Unix (thanks to H. Ware for the fix)
2046
// p = r.exec( "env" );
2047
// }
2048
// BufferedReader br = new BufferedReader
2049
// ( new InputStreamReader( p.getInputStream() ) );
2050
// String line;
2051
// while( (line = br.readLine()) != null ) {
2052
// int idx = line.indexOf( '=' );
2053
// String key = line.substring( 0, idx );
2054
// String value = line.substring( idx+1 );
2055
// envVars.setProperty( key, value );
2056
// // System.out.println( key + " = " + value );
2057
// }
2058
// return envVars;
2059
// }
2060
// }
2061
//
2062
Popular Tags