1
17package org.tp23.antinstaller.antmod;
18
19import java.io.File;
20import java.io.FileInputStream;
21import java.io.FileOutputStream;
22import java.io.IOException;
23import java.io.InputStream;
24import java.io.PrintStream;
25import java.util.Enumeration;
26import java.util.Properties;
27import java.util.Vector;
28
29import org.apache.tools.ant.BuildException;
30import org.apache.tools.ant.BuildListener;
31import org.apache.tools.ant.BuildLogger;
32import org.apache.tools.ant.DefaultLogger;
33import org.apache.tools.ant.Diagnostics;
34import org.apache.tools.ant.ExitStatusException;
35import org.apache.tools.ant.Project;
36import org.apache.tools.ant.ProjectHelper;
37import org.apache.tools.ant.Target;
38import org.apache.tools.ant.input.DefaultInputHandler;
39import org.apache.tools.ant.input.InputHandler;
40import org.apache.tools.ant.launch.AntMain;
41import org.apache.tools.ant.util.JavaEnvUtils;
42import org.tp23.antinstaller.InstallerContext;
43import org.tp23.antinstaller.PropertiesFileRenderer;
44
45
46
60public class Main implements AntMain {
61
62
63 public static final String DEFAULT_BUILD_FILENAME = "build.xml";
64
65
66 private int msgOutputLevel = Project.MSG_INFO;
67
68
69 private File buildFile;
70
71
72 private static PrintStream out = System.out;
73
74
75 private static PrintStream err = System.err;
76
77
78 private Vector targets = new Vector();
79
80
81 private Properties definedProps = new Properties();
82
83
84 private Vector listeners = new Vector(1);
85
86
87 private Vector propertyFiles = new Vector(1);
88
89
90 private boolean allowInput = true;
91
92
93 private boolean keepGoingMode = false;
94
95
00 private String loggerClassname = null;
01
02
06 private String inputHandlerClassname = null;
07
08
11 private boolean emacsMode = false;
12
13
17 private boolean readyToRun = false;
18
19
23 private boolean projectHelp = false;
24
25
29 private static boolean isLogFileUsed = false;
30
31
34 private Integer threadPriority = null;
35
38 private InstallerContext ctx = null;
39
40
47 private static void printMessage(Throwable t) {
48 String message = t.getMessage();
49 if (message != null) {
50 System.err.println(message);
51 }
52 }
53
54
66 public static void start(String[] args, Properties additionalUserProperties,
67 ClassLoader coreLoader) {
68 throw new UnsupportedOperationException("Required by Ant interface but not used");
69 }
72
73
74 public void startAnt(String[] args, Properties additionalUserProperties,
75 ClassLoader coreLoader) {
76 throw new UnsupportedOperationException("Required by Ant interface but not used");
77 }
79
89 public int startAnt(String[] args, Properties additionalUserProperties,
90 ClassLoader coreLoader, InstallerContext ctx) {
91 this.ctx = ctx;
92 out = ctx.getAntOutputRenderer().getOut();
93 err = ctx.getAntOutputRenderer().getErr();
94 try {
95 Diagnostics.validateVersion();
96 processArgs(args);
97 } catch (Throwable exc) {
98 handleLogfile();
99 printMessage(exc);
00 return 1;
01 }
02
03 if (additionalUserProperties != null) {
04 for (Enumeration e = additionalUserProperties.keys();
05 e.hasMoreElements();) {
06 String key = (String) e.nextElement();
07 String property = additionalUserProperties.getProperty(key);
08 definedProps.put(key, property);
09 }
10 }
11
12 int exitCode = 1;
14 try {
15 try {
16 runBuild(coreLoader);
17 exitCode = 0;
18 } catch (ExitStatusException ese) {
19 exitCode = ese.getStatus();
20 if (exitCode != 0) {
21 throw ese;
22 }
23 }
24 } catch (BuildException be) {
25 if (err != System.err) {
26 printMessage(be);
27 }
28 } catch (Throwable exc) {
29 exc.printStackTrace();
30 printMessage(exc);
31 } finally {
32 handleLogfile();
33 }
34 return exitCode;
36 }
38
39
44 private static void handleLogfile() {
45 if (isLogFileUsed) {
46 if (out != null) {
47 try {
48 out.close();
49 } catch (final Exception e) {
50 }
52 }
53 if (err != null) {
54 try {
55 err.close();
56 } catch (final Exception e) {
57 }
59 }
60 }
61 }
62
63
70
78 public Main() {
79 }
80
81
92 protected Main(String[] args) throws BuildException {
93 processArgs(args);
94 }
95
96
05 private void processArgs(String[] args) {
06 String searchForThis = null;
07 PrintStream logTo = null;
08
09
11 for (int i = 0; i < args.length; i++) {
12 String arg = args[i];
13
14 if (arg.equals("-help") || arg.equals("-h")) {
15 printUsage();
16 return;
17 } else if (arg.equals("-version")) {
18 printVersion();
19 return;
20 } else if (arg.equals("-diagnostics")) {
21 Diagnostics.doReport(System.out);
22 return;
23 } else if (arg.equals("-quiet") || arg.equals("-q")) {
24 msgOutputLevel = Project.MSG_WARN;
25 } else if (arg.equals("-verbose") || arg.equals("-v")) {
26 printVersion();
27 msgOutputLevel = Project.MSG_VERBOSE;
28 } else if (arg.equals("-debug") || arg.equals("-d")) {
29 printVersion();
30 msgOutputLevel = Project.MSG_DEBUG;
31 } else if (arg.equals("-noinput")) {
32 allowInput = false;
33 } else if (arg.equals("-logfile") || arg.equals("-l")) {
34 try {
35 File logFile = new File(args[i + 1]);
36 i++;
37 logTo = new PrintStream(new FileOutputStream(logFile));
38 isLogFileUsed = true;
39 } catch (IOException ioe) {
40 String msg = "Cannot write on the specified log file. "
41 + "Make sure the path exists and you have write "
42 + "permissions.";
43 throw new BuildException(msg);
44 } catch (ArrayIndexOutOfBoundsException aioobe) {
45 String msg = "You must specify a log file when "
46 + "using the -log argument";
47 throw new BuildException(msg);
48 }
49 } else if (arg.equals("-buildfile") || arg.equals("-file")
50 || arg.equals("-f")) {
51 try {
52 buildFile = new File(args[i + 1].replace('/', File.separatorChar));
53 i++;
54 } catch (ArrayIndexOutOfBoundsException aioobe) {
55 String msg = "You must specify a buildfile when "
56 + "using the -buildfile argument";
57 throw new BuildException(msg);
58 }
59 } else if (arg.equals("-listener")) {
60 try {
61 listeners.addElement(args[i + 1]);
62 i++;
63 } catch (ArrayIndexOutOfBoundsException aioobe) {
64 String msg = "You must specify a classname when "
65 + "using the -listener argument";
66 throw new BuildException(msg);
67 }
68 } else if (arg.startsWith("-D")) {
69
70
80
81 String name = arg.substring(2, arg.length());
82 String value = null;
83 int posEq = name.indexOf("=");
84 if (posEq > 0) {
85 value = name.substring(posEq + 1);
86 name = name.substring(0, posEq);
87 } else if (i < args.length - 1) {
88 value = args[++i];
89 } else {
90 throw new BuildException("Missing value for property "
91 + name);
92 }
93
94 definedProps.put(name, value);
95 } else if (arg.equals("-logger")) {
96 if (loggerClassname != null) {
97 throw new BuildException("Only one logger class may "
98 + " be specified.");
99 }
00 try {
01 loggerClassname = args[++i];
02 } catch (ArrayIndexOutOfBoundsException aioobe) {
03 throw new BuildException("You must specify a classname when"
04 + " using the -logger argument");
05 }
06 } else if (arg.equals("-inputhandler")) {
07 if (inputHandlerClassname != null) {
08 throw new BuildException("Only one input handler class may "
09 + "be specified.");
10 }
11 try {
12 inputHandlerClassname = args[++i];
13 } catch (ArrayIndexOutOfBoundsException aioobe) {
14 throw new BuildException("You must specify a classname when"
15 + " using the -inputhandler"
16 + " argument");
17 }
18 } else if (arg.equals("-emacs") || arg.equals("-e")) {
19 emacsMode = true;
20 } else if (arg.equals("-projecthelp") || arg.equals("-p")) {
21 projectHelp = true;
23 } else if (arg.equals("-find") || arg.equals("-s")) {
24 if (i < args.length - 1) {
26 searchForThis = args[++i];
27 } else {
28 searchForThis = DEFAULT_BUILD_FILENAME;
29 }
30 } else if (arg.startsWith("-propertyfile")) {
31 try {
32 propertyFiles.addElement(args[i + 1]);
33 i++;
34 } catch (ArrayIndexOutOfBoundsException aioobe) {
35 String msg = "You must specify a property filename when "
36 + "using the -propertyfile argument";
37 throw new BuildException(msg);
38 }
39 } else if (arg.equals("-k") || arg.equals("-keep-going")) {
40 keepGoingMode = true;
41 } else if (arg.equals("-nice")) {
42 try {
43 threadPriority=Integer.decode(args[i + 1]);
44 } catch (ArrayIndexOutOfBoundsException aioobe) {
45 throw new BuildException(
46 "You must supply a niceness value (1-10)"+
47 " after the -nice option");
48 } catch (NumberFormatException e) {
49 throw new BuildException("Unrecognized niceness value: " +
50 args[i + 1]);
51 }
52 i++;
53 if(threadPriority.intValue()<Thread.MIN_PRIORITY ||
54 threadPriority.intValue()>Thread.MAX_PRIORITY) {
55 throw new BuildException(
56 "Niceness value is out of the range 1-10");
57 }
58 } else if (arg.startsWith("-")) {
59 String msg = "Unknown argument: " + arg;
61 System.out.println(msg);
62 printUsage();
63 throw new BuildException("");
64 } else {
65 targets.addElement(arg);
67 }
68 }
69
70 if (buildFile == null) {
72 if (searchForThis != null) {
74 buildFile = findBuildFile(System.getProperty("user.dir"),
75 searchForThis);
76 } else {
77 buildFile = new File(DEFAULT_BUILD_FILENAME);
78 }
79 }
80
81 if (!buildFile.exists()) {
83 System.out.println("Buildfile: " + buildFile + " does not exist!");
84 throw new BuildException("Build failed");
85 }
86
87
90 if (buildFile.isDirectory()) {
91 System.out.println("What? Buildfile: " + buildFile + " is a dir!");
92 throw new BuildException("Build failed");
93 }
94
95 for (int propertyFileIndex = 0;
97 propertyFileIndex < propertyFiles.size();
98 propertyFileIndex++) {
99 String filename
00 = (String) propertyFiles.elementAt(propertyFileIndex);
01 Properties props = new Properties();
02 FileInputStream fis = null;
03 try {
04 fis = new FileInputStream(filename);
05 props.load(fis);
06 } catch (IOException e) {
07 System.out.println("Could not load property file "
08 + filename + ": " + e.getMessage());
09 } finally {
10 if (fis != null) {
11 try {
12 fis.close();
13 } catch (IOException e) {
14 }
16 }
17 }
18
19 Enumeration propertyNames = props.propertyNames();
21 while (propertyNames.hasMoreElements()) {
22 String name = (String) propertyNames.nextElement();
23 if (definedProps.getProperty(name) == null) {
24 definedProps.put(name, props.getProperty(name));
25 }
26 }
27 }
28
29 if (msgOutputLevel >= Project.MSG_INFO) {
30 System.out.println("Buildfile: " + buildFile);
31 }
32
33 if (logTo != null) {
34 out = logTo;
35 err = logTo;
36 System.setOut(out);
37 System.setErr(err);
38 }
39 readyToRun = true;
40 }
41
42
51 private File getParentFile(File file) {
52 File parent = file.getParentFile();
53
54 if (parent != null && msgOutputLevel >= Project.MSG_VERBOSE) {
55 System.out.println("Searching in " + parent.getAbsolutePath());
56 }
57
58 return parent;
59 }
60
61
78 private File findBuildFile(String start, String suffix)
79 throws BuildException {
80 if (msgOutputLevel >= Project.MSG_INFO) {
81 System.out.println("Searching for " + suffix + " ...");
82 }
83
84 File parent = new File(new File(start).getAbsolutePath());
85 File file = new File(parent, suffix);
86
87 while (!file.exists()) {
89 parent = getParentFile(parent);
91
92 if (parent == null) {
95 throw new BuildException("Could not locate a build file!");
96 }
97
98 file = new File(parent, suffix);
00 }
01
02 return file;
03 }
04
05
16 private void runBuild(ClassLoader coreLoader) throws BuildException {
17
18 if (!readyToRun) {
19 return;
20 }
21
22 final Project project = new Project();
23 project.setCoreLoader(coreLoader);
24
25 Throwable error = null;
26
27 try {
28 addBuildListeners(project);
29 addInputHandler(project);
30
31 PrintStream err = System.err;
32 PrintStream out = System.out;
33 InputStream in = System.in;
34
35 SecurityManager oldsm = null;
38 if (!JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_0)
39 && !JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_1)) {
40 oldsm = System.getSecurityManager();
41
42 }
47 try {
48 if (allowInput) {
49 project.setDefaultInputStream(System.in);
50 }
51
55
56 if (!projectHelp) {
57 project.fireBuildStarted();
58 }
59
60 if (threadPriority != null) {
62 try {
63 project.log("Setting Ant's thread priority to "
64 + threadPriority,Project.MSG_VERBOSE);
65 Thread.currentThread().setPriority(threadPriority.intValue());
66 } catch (SecurityException swallowed) {
67 project.log("A security manager refused to set the -nice value");
69 }
70 }
71
72 project.init();
73 project.setUserProperty("ant.version", getAntVersion());
74
75 Enumeration e = definedProps.keys();
77 while (e.hasMoreElements()) {
78 String arg = (String) e.nextElement();
79 String value = (String) definedProps.get(arg);
80 project.setUserProperty(arg, value);
81 }
82
83 project.setUserProperty("ant.file",
84 buildFile.getAbsolutePath());
85 project.setKeepGoingMode(keepGoingMode);
86
87 ProjectHelper.configureProject(project, buildFile);
88
89 project.setBasedir(definedProps.getProperty(PropertiesFileRenderer.FILE_ROOT_PROPERTY));
90
91
92 if (projectHelp) {
93 printDescription(project);
94 printTargets(project, msgOutputLevel > Project.MSG_INFO);
95 return;
96 }
97
98 if (targets.size() == 0) {
00 if (project.getDefaultTarget() != null) {
01 targets.addElement(project.getDefaultTarget());
02 }
03 }
04 project.executeTargets(targets);
05 } finally {
06 if (oldsm != null) {
09 System.setSecurityManager(oldsm);
10 }
11
12 System.setOut(out);
13 System.setErr(err);
14 System.setIn(in);
15 }
16 } catch (RuntimeException exc) {
17 error = exc;
18 throw exc;
19 } catch (Error err) {
20 error = err;
21 throw err;
22 } finally {
23 if (!projectHelp) {
24 project.fireBuildFinished(error);
25 } else if (error != null) {
26 project.log(error.toString(), Project.MSG_ERR);
27 }
28 }
29 }
30
31
38 protected void addBuildListeners(Project project) {
39
40 project.addBuildListener(createLogger());
42
43 if(ctx.getBuildListener()!=null){
45 project.addBuildListener(ctx.getBuildListener());
46 }
47
48 for (int i = 0; i < listeners.size(); i++) {
49 String className = (String) listeners.elementAt(i);
50 try {
51 BuildListener listener =
52 (BuildListener) Class.forName(className).newInstance();
53 if (project != null) {
54 project.setProjectReference(listener);
55 }
56 project.addBuildListener(listener);
57 } catch (Throwable exc) {
58 throw new BuildException("Unable to instantiate listener "
59 + className, exc);
60 }
61 }
62 }
63
64
72 private void addInputHandler(Project project) throws BuildException {
73 InputHandler handler = null;
74 if (inputHandlerClassname == null) {
75 handler = new DefaultInputHandler();
76 } else {
77 try {
78 handler = (InputHandler)
79 (Class.forName(inputHandlerClassname).newInstance());
80 if (project != null) {
81 project.setProjectReference(handler);
82 }
83 } catch (ClassCastException e) {
84 String msg = "The specified input handler class "
85 + inputHandlerClassname
86 + " does not implement the InputHandler interface";
87 throw new BuildException(msg);
88 } catch (Exception e) {
89 String msg = "Unable to instantiate specified input handler "
90 + "class " + inputHandlerClassname + " : "
91 + e.getClass().getName();
92 throw new BuildException(msg);
93 }
94 }
95 project.setInputHandler(handler);
96 }
97
98
08 private BuildLogger createLogger() {
09 BuildLogger logger = null;
10 if (loggerClassname != null) {
11 try {
12 Class loggerClass = Class.forName(loggerClassname);
13 logger = (BuildLogger) (loggerClass.newInstance());
14 } catch (ClassCastException e) {
15 System.err.println("The specified logger class "
16 + loggerClassname
17 + " does not implement the BuildLogger interface");
18 throw new RuntimeException();
19 } catch (Exception e) {
20 System.err.println("Unable to instantiate specified logger "
21 + "class " + loggerClassname + " : "
22 + e.getClass().getName());
23 throw new RuntimeException();
24 }
25 } else {
26 logger = new DefaultLogger();
27 }
28
29 logger.setMessageOutputLevel(msgOutputLevel);
30 logger.setOutputPrintStream(out);
31 logger.setErrorPrintStream(err);
32 logger.setEmacsMode(emacsMode);
33
34 return logger;
35 }
36
37
40 private static void printUsage() {
41 String lSep = System.getProperty("line.separator");
42 StringBuffer msg = new StringBuffer();
43 msg.append("ant [options] [target [target2 [target3] ...]]" + lSep);
44 msg.append("Options: " + lSep);
45 msg.append(" -help, -h print this message" + lSep);
46 msg.append(" -projecthelp, -p print project help information" + lSep);
47 msg.append(" -version print the version information and exit" + lSep);
48 msg.append(" -diagnostics print information that might be helpful to" + lSep);
49 msg.append(" diagnose or report problems." + lSep);
50 msg.append(" -quiet, -q be extra quiet" + lSep);
51 msg.append(" -verbose, -v be extra verbose" + lSep);
52 msg.append(" -debug, -d print debugging information" + lSep);
53 msg.append(" -emacs, -e produce logging information without adornments" + lSep);
54 msg.append(" -lib <path> specifies a path to search for jars and classes" + lSep);
55 msg.append(" -logfile <file> use given file for log" + lSep);
56 msg.append(" -l <file> ''" + lSep);
57 msg.append(" -logger <classname> the class which is to perform logging" + lSep);
58 msg.append(" -listener <classname> add an instance of class as a project listener" + lSep);
59 msg.append(" -noinput do not allow interactive input" + lSep);
60 msg.append(" -buildfile <file> use given buildfile" + lSep);
61 msg.append(" -file <file> ''" + lSep);
62 msg.append(" -f <file> ''" + lSep);
63 msg.append(" -D<property>=<value> use value for given property" + lSep);
64 msg.append(" -keep-going, -k execute all targets that do not depend" + lSep);
65 msg.append(" on failed target(s)" + lSep);
66 msg.append(" -propertyfile <name> load all properties from file with -D" + lSep);
67 msg.append(" properties taking precedence" + lSep);
68 msg.append(" -inputhandler <class> the class which will handle input requests" + lSep);
69 msg.append(" -find <file> (s)earch for buildfile towards the root of" + lSep);
70 msg.append(" -s <file> the filesystem and use it" + lSep);
71 msg.append(" -nice number A niceness value for the main thread:" + lSep +
72 " 1 (lowest) to 10 (highest); 5 is the default" + lSep);
73 System.out.println(msg.toString());
74 }
75
76
81 private static void printVersion() throws BuildException {
82 System.out.println(getAntVersion());
83 }
84
85
88 private static String antVersion = null;
89
90
00 public static synchronized String getAntVersion() throws BuildException {
01 if (antVersion == null) {
02 try {
03 Properties props = new Properties();
04 InputStream in =
05 Main.class.getResourceAsStream("/org/apache/tools/ant/version.txt");
06 props.load(in);
07 in.close();
08
09 StringBuffer msg = new StringBuffer();
10 msg.append("Apache Ant version ");
11 msg.append(props.getProperty("VERSION"));
12 msg.append(" compiled on ");
13 msg.append(props.getProperty("DATE"));
14 antVersion = msg.toString();
15 } catch (IOException ioe) {
16 throw new BuildException("Could not load the version information:"
17 + ioe.getMessage());
18 } catch (NullPointerException npe) {
19 throw new BuildException("Could not load the version information.");
20 }
21 }
22 return antVersion;
23 }
24
25
32 private static void printDescription(Project project) {
33 if (project.getDescription() != null) {
34 project.log(project.getDescription());
35 }
36 }
37
38
47 private static void printTargets(Project project, boolean printSubTargets) {
48 int maxLength = 0;
50 Enumeration ptargets = project.getTargets().elements();
51 String targetName;
52 String targetDescription;
53 Target currentTarget;
54 Vector topNames = new Vector();
57 Vector topDescriptions = new Vector();
58 Vector subNames = new Vector();
59
60 while (ptargets.hasMoreElements()) {
61 currentTarget = (Target) ptargets.nextElement();
62 targetName = currentTarget.getName();
63 if (targetName.equals("")) {
64 continue;
65 }
66 targetDescription = currentTarget.getDescription();
67 if (targetDescription == null) {
69 int pos = findTargetPosition(subNames, targetName);
70 subNames.insertElementAt(targetName, pos);
71 } else {
72 int pos = findTargetPosition(topNames, targetName);
73 topNames.insertElementAt(targetName, pos);
74 topDescriptions.insertElementAt(targetDescription, pos);
75 if (targetName.length() > maxLength) {
76 maxLength = targetName.length();
77 }
78 }
79 }
80
81 printTargets(project, topNames, topDescriptions, "Main targets:",
82 maxLength);
83 if (topNames.size() == 0) {
86 printSubTargets = true;
87 }
88 if (printSubTargets) {
89 printTargets(project, subNames, null, "Other targets:", 0);
90 }
91
92 String defaultTarget = project.getDefaultTarget();
93 if (defaultTarget != null && !"".equals(defaultTarget)) {
94 project.log("Default target: " + defaultTarget);
96 }
97 }
98
99
09 private static int findTargetPosition(Vector names, String name) {
10 int res = names.size();
11 for (int i = 0; i < names.size() && res == names.size(); i++) {
12 if (name.compareTo((String) names.elementAt(i)) < 0) {
13 res = i;
14 }
15 }
16 return res;
17 }
18
19
39 private static void printTargets(Project project, Vector names,
40 Vector descriptions, String heading,
41 int maxlen) {
42 String lSep = System.getProperty("line.separator");
44 String spaces = " ";
46 while (spaces.length() <= maxlen) {
47 spaces += spaces;
48 }
49 StringBuffer msg = new StringBuffer();
50 msg.append(heading);
51 msg.append(lSep);
52 msg.append(lSep);
53 for (int i = 0; i < names.size(); i++) {
54 msg.append(" ");
55 msg.append(names.elementAt(i));
56 if (descriptions != null) {
57 msg.append(spaces.substring(0, maxlen - ((String) names.elementAt(i)).length() + 2));
58 msg.append(descriptions.elementAt(i));
59 }
60 msg.append(lSep);
61 }
62 project.log(msg.toString());
63 }
64}
65