1 /* 
2  * Copyright 2005 Paul Hinds
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.tp23.antinstaller.runtime;
17
18import java.io.File;
19import java.util.ResourceBundle;
20
21import org.tp23.antinstaller.InstallException;
22import org.tp23.antinstaller.InstallerContext;
23import org.tp23.antinstaller.renderer.MessageRenderer;
24import org.tp23.antinstaller.runtime.exe.ExecuteFilter;
25import org.tp23.antinstaller.runtime.exe.ExecuteRunnerFilter;
26import org.tp23.antinstaller.runtime.exe.FilterChain;
27import org.tp23.antinstaller.runtime.exe.FilterFactory;
28import org.tp23.antinstaller.runtime.exe.FinalizerFilter;
29import org.tp23.antinstaller.selfextract.SelfExtractor;
30
31
32
33/**
34 * This is the Applications entry point, it has a main method to run the
35 * installer. The main method is only for scripted installs.
36 * 
37 * It is here that the command line options are parsed and it
38 * is determined which type of install (swing or text) will be run.
39 * <p>Reads the config, determines the runner, runs it and outputs the
40 * properties file,  The Ant targets are then called by the AntRunner.
41 * This class also builds the internal Objects from the XML config file.</p>
42 * <p>This class can also be called by external tools to launch the installer
43 * currently two options are provided to lauch from Jars. </p>
44 * <p>Copyright: Copyright (c) 2004</p>
45 * <p>Company: tp23</p>
46 * @author Paul Hinds
47 * @version $Id: ExecInstall.java,v 1.9 2007/01/19 00:24:36 teknopaul Exp $
48 */
49public class ExecInstall {
50
51    private static final ResourceBundle res = ResourceBundle.getBundle("org.tp23.antinstaller.renderer.Res");
52    public static final String CONFIG_RESOURCE = "/org/tp23/antinstaller/runtime/exe/script.fconfig";
53    
54    private final InstallerContext ctx = new InstallerContext();
55    private FilterChain chain;
56    /**
57     * @param chain chain of filters to be executed
58     */
59    public ExecInstall(FilterChain chain){
60        this.chain = chain;
61    }
62
63
64
65    /**
66     * Execute the installer, this reads the config fetches a runner and runs the install.
67     * Once the install pages have finished an AntRunner is used to run Ant
68     */
69    public void exec() {
70    
71        ExecuteFilter[] filters = null;
72        try {
73            chain.init(ctx);
74            filters = chain.getFilters();
75        }
76        catch (Exception e) {
77            // This is a developer error or the package has not been built correctly
78            // It should never happen in a tested build
79            e.printStackTrace();
80            System.exit(1); // called manually since in Win it was not shutting down properly
81        }
82loop:   for (int i = 0; i < filters.length; i++) {
83            try{
84                ctx.log("Filter: " + filters[i].getClass().getName());
85                filters[i].exec(ctx);
86            }
87            catch (ExecuteRunnerFilter.AbortException abort){
88                MessageRenderer vLogger = ctx.getMessageRenderer();
89                vLogger.printMessage(abort.getMessage());
90                ctx.log("Aborted");
91                FinalizerFilter ff = (FinalizerFilter)filters[filters.length - 1];
92                ff.exec(ctx);
93                System.exit(1);
94            }
95            catch (Exception ex) {
96
97                // write errors to the log
98                ctx.log("Installation error: " + ex.getMessage() + ": " + ex.getClass().toString());
99                boolean verbose = true; // be verbose if we cant load the config
00                if(ctx.getInstaller() != null) {
01                    verbose =  ctx.getInstaller().isVerbose();
02                }
03                ctx.log(verbose, ex);
04
05                // write detailed errors to stdout for the GUI screens and text
06                if (ctx.getRunner() instanceof TextRunner) {
07                    if(verbose){
08                        ex.printStackTrace();
09                    }
10                }
11                else {
12                    if(verbose){
13                        ex.printStackTrace(System.err);
14                    }
15                }
16                
17                // report the error to the user
18                MessageRenderer vLogger = ctx.getMessageRenderer();
19                if(vLogger != null){
20                    vLogger.printMessage(res.getString("installationFailed") + "\n" + ex.getMessage());
21                    //Fixed BUG:1295944 vLogger.printMessage("Install failed\n" + ex.getMessage());
22                } else {
23                    System.err.println(res.getString("installationFailed") + ex.getClass().getName());
24                    System.err.println(ex.getMessage());
25                }
26
27                if(ctx.getRunner() != null){
28                    ctx.getRunner().fatalError();
29                    break loop;
30                }
31                else {  // the screens did not even start e.g. XML config error
32                    System.exit(1);
33                }
34            }
35        }
36
37    }
38
39
40
41
42
43    /**
44     * <p>Runs the installer from a script.</p>
45     * 
46     * This install can be run from a set of files for example from a CD.
47     * @see org.tp23.antinstaller.selfextract.NonExtractor
48     * @see org.tp23.antinstaller.selfextract.SelfExtractor
49     * 
50     * @param args String[]  args are "default" or "swing" or "text" followed by the root directory of the install
51     */
52    public static void main(String[] args) {
53        try {
54            FilterChain chain = FilterFactory.factory(CONFIG_RESOURCE);     
55            ExecInstall installExec = new ExecInstall(chain);
56            if(installExec.parseArgs(args, true)){
57                installExec.exec();
58            }
59        }
60        catch (InstallException e) {
61            // Installer developer error
62            System.out.println("Cant load filter chain:/org/tp23/antinstaller/runtime/exe/script.fconfig");
63            e.printStackTrace();
64        }
65    }
66    
67    /**
68     * This method has been designed for backward compatibility with
69     * existing scripts.  The root dir is passed on the command line for scripted
70     * installs but is determined automatically for installs from self-extracting Jars
71     * @param args
72     * @param requiresRootDir set to true if the args must include the root directory
73     */
74    public boolean parseArgs(String[] args, boolean requiresRootDir){
75        String uiOverride = null;
76        String installType = null;
77        String installRoot = null;
78        
79        int i = 0;
80        if(args.length > i && !args[i].startsWith("-")) {
81            uiOverride = args[i];
82            i++;
83            ctx.setUIOverride(uiOverride);
84        }
85        
86        if(requiresRootDir){
87            if(args.length > i && !args[i].startsWith("-")) {
88                installRoot = args[i];
89                i++;
90                ctx.setFileRoot(new File(installRoot));
91            }
92            else{
93                printUsage();
94                return false;
95            }
96        }
97        // additional params should all have a -something prefix
98        for (; i < args.length; i++) {
99            // RFE 1569628
00            if("-type".equals(args[i]) && args.length > i + 1){
01                installType = args[i + 1];
02                i++;
03                String configFileName = "antinstall-config-" + installType + ".xml";
04                String buildFileName = "build-" + installType + ".xml";
05                ctx.setInstallerConfigFile(configFileName);
06                ctx.setAntBuildFile(buildFileName);
07            }
08        }
09        
10        return true;
11    }
12
13    private static void printUsage(){
14        System.out.println("Usage java -cp $CLASSPATH org.tp23.antinstaller.ExecInstall [text|swing|default] [install root] (-type [buildtype])");
15    }
16
17
18    /**
19     * Sets the UI override from the command line
20     * @param installRoot
21     */
22//  public void setUIOverride(String override) {
23//      ctx.setUIOverride(override);
24//  }
25    /**
26     * This is generated by the Main class which knows where it has
27     * extracted or where it has run from
28     * @param installRoot
29     */
30    public void setInstallRoot(File installRoot) {
31        ctx.setFileRoot(installRoot);
32    }
33
34    /**
35     * This is AntInstalls temporary space which will generally be deleted
36     * except in debug mode when it is left to view the build process.
37     * installRoot and tempRoot can be the same if the directory
38     * is a new empty directory
39     * @param tempDir directory to be used for temporary storage
40     */
41    public void setTempRoot(File tempDir) {
42        addShutdownHook(tempDir);
43    }
44    /**
45     * This shutdown hook is to facilitate debugging the app can be left open
46     * in the GUI view and the resources will not be deleted.  Upon exit
47     * temporary files will be removed.  This is required because the 
48     * deleteOnExit() method fails if the directory is filled with files.
49     * @param tempDir
50     */
51    private void addShutdownHook(final File tempDir){
52        Runnable hook = new Runnable(){
53            public void run(){
54                if(ctx.getInstaller() != null &&
55                   ctx.getInstaller().isDebug()) return;
56                if(tempDir != null && tempDir.exists() && tempDir.isDirectory()){
57                    SelfExtractor.deleteRecursive(tempDir);
58                }
59            }
60        };
61        Thread cleanUp = new Thread(hook);
62        cleanUp.setDaemon(true);
63        Runtime.getRuntime().addShutdownHook(cleanUp);
64    }
65
66}
67