From aac7e58448f0e5a961075baca670dac1ae53ce98 Mon Sep 17 00:00:00 2001 From: Andy Clement Date: Fri, 1 Feb 2019 12:42:09 -0800 Subject: mavenizing build - wip --- build/.classpath | 9 - build/.cvsignore | 2 - build/.isJava5 | 1 - build/.project | 17 - build/local.properties | 12 - build/pom.xml | 33 + build/src/$installer$/org/aspectj/Main.java | 1861 -------------------- .../internal/tools/ant/taskdefs/AJInstaller.java | 364 ++++ .../internal/tools/ant/taskdefs/AJPush.java | 91 + .../internal/tools/ant/taskdefs/AntBuilder.java | 833 +++++++++ .../internal/tools/ant/taskdefs/BuildModule.java | 165 ++ .../internal/tools/ant/taskdefs/Checklics.java | 676 +++++++ .../tools/ant/taskdefs/ConditionalTask.java | 187 ++ .../ant/taskdefs/CopyAndInlineStylesheet.java | 120 ++ .../tools/ant/taskdefs/StripNonBodyHtml.java | 244 +++ .../tools/ant/taskdefs/TestBuildModule.java | 79 + .../tools/ant/taskdefs/VersionUptodate.java | 144 ++ .../tools/ant/taskdefs/taskdefs.properties | 21 + .../aspectj/internal/tools/build/BuildSpec.java | 80 + .../aspectj/internal/tools/build/Builder.java | 676 +++++++ .../internal/tools/build/Builder.properties | 20 + .../aspectj/internal/tools/build/Messager.java | 43 + .../java./aspectj/internal/tools/build/Module.java | 754 ++++++++ .../aspectj/internal/tools/build/Modules.java | 66 + .../internal/tools/build/ProductModule.java | 70 + .../java./aspectj/internal/tools/build/Result.java | 387 ++++ .../internal/tools/build/SampleGatherer.java | 1049 +++++++++++ .../java./aspectj/internal/tools/build/Util.java | 483 +++++ .../aspectj/internal/tools/build/package.html | 12 + .../main/java/$installer$/org/aspectj/Main.java | 1861 ++++++++++++++++++++ .../internal/tools/ant/taskdefs/AJInstaller.java | 364 ---- .../internal/tools/ant/taskdefs/AJPush.java | 91 - .../internal/tools/ant/taskdefs/AntBuilder.java | 833 --------- .../internal/tools/ant/taskdefs/BuildModule.java | 165 -- .../internal/tools/ant/taskdefs/Checklics.java | 676 ------- .../tools/ant/taskdefs/ConditionalTask.java | 187 -- .../ant/taskdefs/CopyAndInlineStylesheet.java | 120 -- .../tools/ant/taskdefs/StripNonBodyHtml.java | 244 --- .../tools/ant/taskdefs/TestBuildModule.java | 79 - .../tools/ant/taskdefs/VersionUptodate.java | 144 -- .../tools/ant/taskdefs/taskdefs.properties | 21 - .../aspectj/internal/tools/build/BuildSpec.java | 80 - .../org/aspectj/internal/tools/build/Builder.java | 676 ------- .../internal/tools/build/Builder.properties | 20 - .../org/aspectj/internal/tools/build/Messager.java | 43 - .../org/aspectj/internal/tools/build/Module.java | 754 -------- .../org/aspectj/internal/tools/build/Modules.java | 66 - .../internal/tools/build/ProductModule.java | 70 - .../org/aspectj/internal/tools/build/Result.java | 387 ---- .../internal/tools/build/SampleGatherer.java | 1049 ----------- .../src/org/aspectj/internal/tools/build/Util.java | 483 ----- .../org/aspectj/internal/tools/build/package.html | 12 - .../java/org/aspectj/build/BuildModuleTests.java | 304 ++++ .../aspectj/internal/build/BuildClasspathTest.java | 67 + .../aspectj/internal/build/BuildModuleTest.java | 468 +++++ .../org/aspectj/internal/build/ModulesTest.java | 304 ++++ .../aspectj/internal/tools/build/UtilsTest.01.MF | 8 + .../aspectj/internal/tools/build/UtilsTest.02.MF | 9 + .../aspectj/internal/tools/build/UtilsTest.03.MF | 9 + .../aspectj/internal/tools/build/UtilsTest.java | 200 +++ .../org/aspectj/build/BuildModuleTests.java | 304 ---- .../aspectj/internal/build/BuildClasspathTest.java | 67 - .../aspectj/internal/build/BuildModuleTest.java | 468 ----- .../org/aspectj/internal/build/ModulesTest.java | 304 ---- .../aspectj/internal/tools/build/UtilsTest.01.MF | 8 - .../aspectj/internal/tools/build/UtilsTest.02.MF | 9 - .../aspectj/internal/tools/build/UtilsTest.03.MF | 9 - .../aspectj/internal/tools/build/UtilsTest.java | 200 --- 68 files changed, 9827 insertions(+), 9835 deletions(-) delete mode 100644 build/.classpath delete mode 100644 build/.cvsignore delete mode 100644 build/.isJava5 delete mode 100644 build/.project delete mode 100644 build/local.properties create mode 100644 build/pom.xml delete mode 100644 build/src/$installer$/org/aspectj/Main.java create mode 100644 build/src/main/java./aspectj/internal/tools/ant/taskdefs/AJInstaller.java create mode 100644 build/src/main/java./aspectj/internal/tools/ant/taskdefs/AJPush.java create mode 100644 build/src/main/java./aspectj/internal/tools/ant/taskdefs/AntBuilder.java create mode 100644 build/src/main/java./aspectj/internal/tools/ant/taskdefs/BuildModule.java create mode 100644 build/src/main/java./aspectj/internal/tools/ant/taskdefs/Checklics.java create mode 100644 build/src/main/java./aspectj/internal/tools/ant/taskdefs/ConditionalTask.java create mode 100644 build/src/main/java./aspectj/internal/tools/ant/taskdefs/CopyAndInlineStylesheet.java create mode 100644 build/src/main/java./aspectj/internal/tools/ant/taskdefs/StripNonBodyHtml.java create mode 100644 build/src/main/java./aspectj/internal/tools/ant/taskdefs/TestBuildModule.java create mode 100644 build/src/main/java./aspectj/internal/tools/ant/taskdefs/VersionUptodate.java create mode 100644 build/src/main/java./aspectj/internal/tools/ant/taskdefs/taskdefs.properties create mode 100644 build/src/main/java./aspectj/internal/tools/build/BuildSpec.java create mode 100644 build/src/main/java./aspectj/internal/tools/build/Builder.java create mode 100644 build/src/main/java./aspectj/internal/tools/build/Builder.properties create mode 100644 build/src/main/java./aspectj/internal/tools/build/Messager.java create mode 100644 build/src/main/java./aspectj/internal/tools/build/Module.java create mode 100644 build/src/main/java./aspectj/internal/tools/build/Modules.java create mode 100644 build/src/main/java./aspectj/internal/tools/build/ProductModule.java create mode 100644 build/src/main/java./aspectj/internal/tools/build/Result.java create mode 100644 build/src/main/java./aspectj/internal/tools/build/SampleGatherer.java create mode 100644 build/src/main/java./aspectj/internal/tools/build/Util.java create mode 100644 build/src/main/java./aspectj/internal/tools/build/package.html create mode 100644 build/src/main/java/$installer$/org/aspectj/Main.java delete mode 100644 build/src/org/aspectj/internal/tools/ant/taskdefs/AJInstaller.java delete mode 100644 build/src/org/aspectj/internal/tools/ant/taskdefs/AJPush.java delete mode 100644 build/src/org/aspectj/internal/tools/ant/taskdefs/AntBuilder.java delete mode 100644 build/src/org/aspectj/internal/tools/ant/taskdefs/BuildModule.java delete mode 100644 build/src/org/aspectj/internal/tools/ant/taskdefs/Checklics.java delete mode 100644 build/src/org/aspectj/internal/tools/ant/taskdefs/ConditionalTask.java delete mode 100644 build/src/org/aspectj/internal/tools/ant/taskdefs/CopyAndInlineStylesheet.java delete mode 100644 build/src/org/aspectj/internal/tools/ant/taskdefs/StripNonBodyHtml.java delete mode 100644 build/src/org/aspectj/internal/tools/ant/taskdefs/TestBuildModule.java delete mode 100644 build/src/org/aspectj/internal/tools/ant/taskdefs/VersionUptodate.java delete mode 100644 build/src/org/aspectj/internal/tools/ant/taskdefs/taskdefs.properties delete mode 100644 build/src/org/aspectj/internal/tools/build/BuildSpec.java delete mode 100644 build/src/org/aspectj/internal/tools/build/Builder.java delete mode 100644 build/src/org/aspectj/internal/tools/build/Builder.properties delete mode 100644 build/src/org/aspectj/internal/tools/build/Messager.java delete mode 100644 build/src/org/aspectj/internal/tools/build/Module.java delete mode 100644 build/src/org/aspectj/internal/tools/build/Modules.java delete mode 100644 build/src/org/aspectj/internal/tools/build/ProductModule.java delete mode 100644 build/src/org/aspectj/internal/tools/build/Result.java delete mode 100644 build/src/org/aspectj/internal/tools/build/SampleGatherer.java delete mode 100644 build/src/org/aspectj/internal/tools/build/Util.java delete mode 100644 build/src/org/aspectj/internal/tools/build/package.html create mode 100644 build/src/test/java/org/aspectj/build/BuildModuleTests.java create mode 100644 build/src/test/java/org/aspectj/internal/build/BuildClasspathTest.java create mode 100644 build/src/test/java/org/aspectj/internal/build/BuildModuleTest.java create mode 100644 build/src/test/java/org/aspectj/internal/build/ModulesTest.java create mode 100644 build/src/test/java/org/aspectj/internal/tools/build/UtilsTest.01.MF create mode 100644 build/src/test/java/org/aspectj/internal/tools/build/UtilsTest.02.MF create mode 100644 build/src/test/java/org/aspectj/internal/tools/build/UtilsTest.03.MF create mode 100644 build/src/test/java/org/aspectj/internal/tools/build/UtilsTest.java delete mode 100644 build/testsrc/org/aspectj/build/BuildModuleTests.java delete mode 100644 build/testsrc/org/aspectj/internal/build/BuildClasspathTest.java delete mode 100644 build/testsrc/org/aspectj/internal/build/BuildModuleTest.java delete mode 100644 build/testsrc/org/aspectj/internal/build/ModulesTest.java delete mode 100644 build/testsrc/org/aspectj/internal/tools/build/UtilsTest.01.MF delete mode 100644 build/testsrc/org/aspectj/internal/tools/build/UtilsTest.02.MF delete mode 100644 build/testsrc/org/aspectj/internal/tools/build/UtilsTest.03.MF delete mode 100644 build/testsrc/org/aspectj/internal/tools/build/UtilsTest.java (limited to 'build') diff --git a/build/.classpath b/build/.classpath deleted file mode 100644 index 2eb26a332..000000000 --- a/build/.classpath +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/build/.cvsignore b/build/.cvsignore deleted file mode 100644 index 6654feb84..000000000 --- a/build/.cvsignore +++ /dev/null @@ -1,2 +0,0 @@ -bin -local.properties diff --git a/build/.isJava5 b/build/.isJava5 deleted file mode 100644 index 136d06384..000000000 --- a/build/.isJava5 +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/build/.project b/build/.project deleted file mode 100644 index 1f143eab5..000000000 --- a/build/.project +++ /dev/null @@ -1,17 +0,0 @@ - - - build - - - - - - org.eclipse.jdt.core.javabuilder - - - - - - org.eclipse.jdt.core.javanature - - diff --git a/build/local.properties b/build/local.properties deleted file mode 100644 index b93e1c816..000000000 --- a/build/local.properties +++ /dev/null @@ -1,12 +0,0 @@ -# for non-release builds, versions should all be DEVELOPMENT -# except for build.version.base -build.version=1.8.2 -build.version.base=1.8 -build.version.long=1.8.2 -build.version.short=1.8.2 -# Repo version is for maven (as built with 'ant repo') -repo.version=1.6.4 -java11.home=c:/home/apps/jdk11 -java13.home=c:/home/apps/jdk13 -java14.home=c:/home/apps/jdk14 -java15.home=c:/home/apps/jdk15 diff --git a/build/pom.xml b/build/pom.xml new file mode 100644 index 000000000..5dcf70b71 --- /dev/null +++ b/build/pom.xml @@ -0,0 +1,33 @@ + + 4.0.0 + + + org.aspectj + aspectj-parent + 1.9.3.BUILD-SNAPSHOT + .. + + + build + jar + build + + + + org.aspectj + testing-util + ${project.version} + + + + ant + ant + 1.0 + system + ${project.basedir}/../lib/ant/lib/ant.jar + + + + diff --git a/build/src/$installer$/org/aspectj/Main.java b/build/src/$installer$/org/aspectj/Main.java deleted file mode 100644 index 748b035ae..000000000 --- a/build/src/$installer$/org/aspectj/Main.java +++ /dev/null @@ -1,1861 +0,0 @@ -/* ******************************************************************* - * Copyright (c) 2000-2001 Xerox Corporation, - * 2002 Palo Alto Research Center, Incorporated (PARC). - * All rights reserved. - * This program and the accompanying materials are made available - * under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Xerox/PARC initial implementation - * ******************************************************************/ - -package $installer$.org.aspectj; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.Font; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Toolkit; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; -import java.io.BufferedOutputStream; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.PrintStream; -import java.lang.reflect.InvocationTargetException; -import java.net.URL; -import java.util.Map; -import java.util.Properties; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - -import javax.swing.BorderFactory; -import javax.swing.BoxLayout; -import javax.swing.Icon; -import javax.swing.JButton; -import javax.swing.JEditorPane; -import javax.swing.JFileChooser; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JProgressBar; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.SwingUtilities; -import javax.swing.border.Border; -import javax.swing.border.CompoundBorder; -import javax.swing.border.EmptyBorder; - -/** - * Invoke the Installer gui. There are two ways to run without GUI by passing parameters to main: - *
    - *
  1. pass -text {pathToPropertiesFile}: - *
      - *
    • "-text".equals(arg[0])
    • - *
    • arg[1] is the path to a properties file which defines name="output.dir" value="{path to output dir}" name="context.javaPath" - * value="{path to JDKDIR}", i.e,. - * - *
      - * output.dir=c:/latest
      - *   "context.javaPath=c:/apps/jdk1.3.1
      - * 
      - * - *
    • - *
    • outputDir must be created and empty (i.e., no overwriting
    • - *
    • the VM being invoked should be the target vm
    • - *
    - *
  2. - *
  3. pass -to {pathToTargetDir}: - *
      - *
    • "-to".equals(arg[0])
    • - *
    • arg[1] is the path to a writable install directory.
    • - *
    - *
  4. - */ -public class Main { - public static void main(String[] args) { - Options.loadArgs(args); - boolean hasGui = true; - Properties properties = new Properties(); - InputStream istream = null; - try { - istream = Main.class.getResourceAsStream(Installer.RESOURCE_DIR + "/properties.txt"); - if (istream == null) { - System.err.println("unable to load properties.txt using Main.class - exiting"); - Main.exit(-1); - } - properties.load(istream); - // when running outside GUI, load values into properties - // so that property-value resolution works - // (otherwise, could just set values below). - // XXX not sure if this indirection is actually needed. - if (null != Options.textProperties) { - istream.close(); - istream = new FileInputStream(Options.textProperties); - properties.load(istream); - hasGui = false; - } else if (null != Options.targetDir) { - String path = null; - try { - path = Options.targetDir.getCanonicalPath(); - } catch (IOException e) { - path = Options.targetDir.getAbsolutePath(); - } - String javaPath = ConfigureLauncherPane.getDefaultJavaHomeLocation(); - if (null == javaPath) { - System.err.println("using GUI - unable to find java"); - } else { - properties.setProperty("output.dir", path); - properties.setProperty("context.javaPath", javaPath); - hasGui = false; - } - } - } catch (IOException ioe) { - handleException(ioe); - } finally { - if (null != istream) { - try { - istream.close(); - } catch (IOException e) { - } // ignore - } - } - - try { - String className = (String) properties.get("installer.main.class"); - //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); - Installer installer = (Installer) Class.forName(className).newInstance(); - InstallContext installerContext = new InstallContext(properties); - installerContext.setHasGui(hasGui); - installer.setContext(installerContext); - if (installerContext.hasGui()) { // let context force whether or not to run gui - installer.runGUI(); - } else { - // set output dir and java path in context after minimal validation - String propName = "output.dir"; - String propValue = properties.getProperty(propName); - if (null == propValue) { - throw new Exception("expecting property " + propName); - } - String outputDirName = propValue; - propName = "context.javaPath"; - propValue = properties.getProperty(propName); - if (null == propValue) { - throw new Exception("expecting property " + propName); - } - String javaPath = propValue; - File outputDir = new File(outputDirName); - if (!outputDir.isDirectory()) { - throw new Exception("not a dir outputDirName: " + outputDirName + " dir: " + outputDir); - } - if (!outputDir.canWrite()) { - throw new Exception("cannot write outputDirName: " + outputDirName + " dir: " + outputDir); - } - InstallContext context = installer.getContext(); // todo: why not use installerContext? - context.setOutputDir(outputDir); - context.javaPath = new File(javaPath); - // todo: check javaPath for ... bin/java? lib/rt.jar? - if (!outputDir.isDirectory() || !outputDir.canRead()) { - throw new Exception("invalid javaPath: " + javaPath); - } - // directly set context and run - WizardPane.setContext(installerContext); - installer.run(); - } - } catch (Exception e) { - handleException(e); - } - } - - public static void handleException(Throwable e) { - System.out.println("internal error: " + e.toString()); - e.printStackTrace(); - Main.exit(-1); - } - - /** indirection for System.exit - todo apply cleanup here as necessary */ - public static void exit(int value) { - System.exit(value); - } -} // class Main - -class Options { - public static boolean verbose = false; - public static String textProperties = null; - public static File targetDir = null; - public static boolean forceError1 = false; - public static boolean forceError2 = false; - public static boolean forceHandConfigure = false; - - public static void loadArgs(String[] args) { - if (args == null) { - return; - } - for (int i = 0; i < args.length; i++) { - String arg = args[i]; - if (arg == null) { - continue; - } - - if (arg.equals("-verbose")) { - verbose = true; - } else if (arg.equals("-forceError1")) { - forceError1 = true; - } else if (arg.equals("-forceError2")) { - forceError2 = true; - } else if (arg.equals("-forceHandConfigure")) { - forceHandConfigure = true; - } else if (arg.equals("-text")) { - if (i + 1 < args.length) { - textProperties = args[++i]; - } - } else if (arg.equals("-to")) { - String next = "no argument"; - if (i + 1 < args.length) { - next = args[++i]; - File targDir = new File(next); - if (targDir.isDirectory() && targDir.canWrite()) { - targetDir = targDir; - } - } - if (null == targetDir) { - System.err.println("invalid -to dir: " + next); - } - } - } - } -} - -/** tools installer installs the entire 1.1+ distribution */ -class ToolsInstaller extends Installer { - public String getTitle() { - return "Installer for AspectJ(TM)"; - } - - public String getPrefix() { - return "tools"; - } - - public String getReadmeFilename() { - return "README-AspectJ.html"; - } - - public ToolsInstaller() { - InstallPane installPane = new InstallPane(true); - setInstallPane(installPane); - panes = new WizardPane[] { new IntroPane(), new ConfigureLauncherPane(), new LocationPane(), installPane, new FinishPane() }; - } -} - -class DocsInstaller extends Installer { - public String getTitle() { - return "AspectJ(TM) Documentation and Examples Installer"; - } - - public String getPrefix() { - return "docs"; - } - - public DocsInstaller() { - InstallPane installPane = new InstallPane(false); - setInstallPane(installPane); - panes = new WizardPane[] { new IntroPane(), new LocationPane(), installPane, new FinishPane() }; - } -} - -class AJDEForJBuilderInstaller extends Installer { - public String getTitle() { - return "AspectJ(TM) Support for JBuilder"; - } - - public String getPrefix() { - return "ajdeForJBuilder"; - } - - public AJDEForJBuilderInstaller() { - InstallPane installPane = new InstallPane(false); - setInstallPane(installPane); - panes = new WizardPane[] { new IntroPane(), new LocationPane() { - public String getDefaultLocation() { - if (context.onWindows()) { - // check some default locations - String[] paths = { "c:\\JBuilder6\\lib\\ext", "c:\\apps\\JBuilder6\\lib\\ext", - "c:\\Program Files\\JBuilder6\\lib\\ext" }; - int pathIndex = 0; - for (; pathIndex < paths.length; pathIndex++) { - if (new File(paths[pathIndex]).exists()) { - return paths[pathIndex]; - } - } - return "c:\\JBuilder6\\lib\\ext"; - } else { - return "/usr/JBuilder6/lib/ext"; - } - } - - /** - * Make sure that the old jar file gets removed. - */ - public void verify() { - File jbuilder = new File(location.getText() + "/../../lib/jbuilder.jar"); - if (!jbuilder.exists() && hasGui()) { - int ret = JOptionPane.showConfirmDialog(frame, "The location you specified does not seem to be a " - + "valid JBuilder install directory." + " Continue?", "Confirm Install", JOptionPane.YES_NO_OPTION, - JOptionPane.QUESTION_MESSAGE); - if (ret != JOptionPane.YES_OPTION) { - Main.exit(-1); - } else { - // do nothing - } - } - - File oldFile = new File(location.getText() + "/ajbuilder.jar"); - if (oldFile.exists() && hasGui()) { - int ret = JOptionPane.showConfirmDialog(frame, - "This old version of AJDE for JBuilder (\"ajbuilder.jar\") exists" - + " and must be removed from the install directory." + " OK to delete?", "Confirm Delete", - JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); - if (ret != JOptionPane.YES_OPTION) { - Main.exit(-1); - } else { - oldFile.delete(); - } - } - } - }, installPane, new FinishPane() }; - } -} - -class AJDEForForteInstaller extends Installer { - public String getTitle() { - return "AspectJ(TM) Support for Forte 4J"; - } - - public String getPrefix() { - return "ajdeForForte"; - } - - private String installLoc = ""; - - public AJDEForForteInstaller() { - InstallPane installPane = new InstallPane(false); - setInstallPane(installPane); - panes = new WizardPane[] { new IntroPane(), new LocationPane() { - public String getDefaultLocation() { - if (context.onWindows()) { - // check some default locations - String[] paths = { "c:\\forte4j\\modules", "c:\\apps\\forte4j\\modules", "c:\\Program Files\\forte4j\\modules" }; - int pathIndex = 0; - for (; pathIndex < paths.length; pathIndex++) { - if (new File(paths[pathIndex]).exists()) { - return paths[pathIndex]; - } - } - return "c:\\forte4j\\modules"; - } else { - return "/usr/forte4j/modules"; - } - } - - public void verify() { - File forte = new File(location.getText() + "/../lib/openide.jar"); - installLoc = location.getText(); - if (!forte.exists() && hasGui()) { - int ret = JOptionPane.showConfirmDialog(frame, "The location you specified does not seem to be a " - + "valid Forte install directory." + " Continue?", "Confirm Install", JOptionPane.YES_NO_OPTION, - JOptionPane.QUESTION_MESSAGE); - if (ret != JOptionPane.YES_OPTION) { - Main.exit(-1); - } else { - // do nothing - } - } - } - }, installPane, new FinishPane() { - public void finalActions() { // todo verify dir ../lib/ext exists? - // !!! this should be done with two install locations, not by moving a file - new File(installLoc + "/../lib/ext/aspectjrt.jar").delete(); - new File(installLoc + "/aspectjrt.jar").renameTo(new File((installLoc + "/../lib/ext/aspectjrt.jar"))); - new File(installLoc + "/aspectjrt.jar").delete(); - } - } }; - } -} - -class SrcInstaller extends Installer { - public String getTitle() { - return "AspectJ(TM) Compiler and Core Tools Sources Installer"; - } - - public String getPrefix() { - return "sources"; - } - - public SrcInstaller() { - InstallPane installPane = new InstallPane(false); - setInstallPane(installPane); - panes = new WizardPane[] { new IntroPane(), new LocationPane(), installPane, new FinishPane() }; - } -} - -abstract class Installer { - static final String EXIT_MESSAGE = "Are you sure you want to cancel the installation?"; - static final String EXIT_TITLE = "Exiting installer"; - /** - * relative directory in jar from package $installer$.org.aspectj for loading resources - todo must be tracked during build - */ - public static final String RESOURCE_DIR = "resources"; - - JFrame frame; - InstallContext context; - /** special pane that actually does the installation */ - InstallPane installPane; - - public Installer() { - } - - protected void setInstallPane(InstallPane installPane) { - this.installPane = installPane; - } - - public InstallPane getInstallPane() { - return installPane; - } - - /** directly run the install pane, if any */ - public void run() { - if (null != installPane) { - installPane.run(); - } - } - - public abstract String getPrefix(); - - public String getReadmeFilename() { - return "README-" + getPrefix().toUpperCase() + ".html"; - } - - public void setContext(InstallContext context) { - this.context = context; - context.installer = this; - } - - public InstallContext getContext() { - return context; - } - - public String getTitle() { - return "AspectJ(TM) Installer"; - } - - public int getWidth() { - return 640; - } - - public int getHeight() { - return 460; - } - - protected WizardPane[] panes = new WizardPane[0]; - - public WizardPane[] getPanes() { - return panes; - } - - public int findPaneIndex(WizardPane pane) { - for (int i = 0; i < panes.length; i++) { - if (panes[i] == pane) { - return i; - } - } - return -1; - } - - Component header, footer, body; - - public void runGUI() { - frame = new JFrame(getTitle()); - WindowListener wl = new WindowAdapter() { - public void windowClosing(WindowEvent arg0) { - Main.exit(-1); // -1 unless exiting through done button - } - }; - frame.addWindowListener(wl); - - if (Options.forceError1) { - throw new RuntimeException("forced error1 for testing purposes"); - } - - Dimension size = Toolkit.getDefaultToolkit().getScreenSize(); - - int x = (int) (size.getWidth() - getWidth()) / 2; - int y = (int) (size.getHeight() - getHeight()) / 2; - - //include a few sanity checks on starting position - if (x < 0) { - x = 0; - } - if (x > 600) { - x = 600; - } - if (y < 0) { - y = 0; - } - if (y > 400) { - y = 400; - } - - frame.setLocation(x, y); - frame.setSize(getWidth(), getHeight()); - moveToPane(getPanes()[0]); - frame.setVisible(true); - } - - public void moveToPane(WizardPane pane) { - WizardPane.setContext(this.context); - - Dimension size = frame.getContentPane().getSize(); - - JPanel contents = new JPanel(); - contents.setLayout(new BorderLayout()); - header = makeHeader(); - contents.add(header, BorderLayout.NORTH); - - body = pane.getPanel(); - contents.add(body, BorderLayout.CENTER); - - footer = pane.getButtons(); - contents.add(footer, BorderLayout.SOUTH); - - contents.revalidate(); - contents.setSize(size); - - frame.setContentPane(contents); - - //XXX deal with threading here? - pane.run(); - } - - public Icon loadImage(String name) { - return new javax.swing.ImageIcon(this.getClass().getResource(name)); - } - - public Component makeHeader() { - return new JLabel(loadImage(Installer.RESOURCE_DIR + "/aspectjBanner.gif")); - } - - public ActionListener makeNextAction(final WizardPane pane) { - int nextPaneIndex = findPaneIndex(pane) + 1; - if (nextPaneIndex >= getPanes().length) { - return null; - } - - final WizardPane nextPane = getPanes()[nextPaneIndex]; - return new ActionListener() { - public void actionPerformed(ActionEvent e) { - pane.finish(); - moveToPane(nextPane); - } - }; - } - - public ActionListener makeBackAction(final WizardPane pane) { - int nextPaneIndex = findPaneIndex(pane) - 1; - if (nextPaneIndex < 0) { - return null; - } - - final WizardPane nextPane = getPanes()[nextPaneIndex]; - return new ActionListener() { - public void actionPerformed(ActionEvent e) { - moveToPane(nextPane); - } - }; - } - - public ActionListener makeCancelAction(WizardPane pane) { - return new ActionListener() { - public void actionPerformed(ActionEvent e) { - int ret = JOptionPane.showConfirmDialog(frame, EXIT_MESSAGE, EXIT_TITLE, JOptionPane.YES_NO_OPTION, - JOptionPane.QUESTION_MESSAGE); - if (ret == JOptionPane.YES_OPTION) { - Main.exit(-1); - } - } - }; - } - - public ActionListener makeFinishAction(WizardPane pane) { - return new ActionListener() { - public void actionPerformed(ActionEvent e) { - Main.exit(0); - } - }; - } -} - -// willing to go up to 3 levels deep to find either jre or jdk - -// jre\[*\]lib\ext -// jdk*\lib\tools.jar - -/***** - * final static int MAX_DEPTH = 4; public static void findPaths(String prefix, File currentDir, int currentDepth) { if (currentDepth - * > MAX_DEPTH) return; if (!currentDir.exists() || !currentDir.isDirectory()) return; File [] files = currentDir.listFiles(); if - * (files == null) return; for (int i=0; i"); - int stopIndex = text.indexOf(""); - if (startIndex == -1 || stopIndex == -1) { - return text; - } - stopIndex += 7; - return text.substring(0, startIndex) + text.substring(stopIndex); - } - - static String styleHeader = "";/* - * "); + } + + + private static boolean isStyleSheet(String line) throws IOException { + line = line.toLowerCase(); + int len = line.length(); + int i = 0; + + while (true) { + if (i == len) return false; + if (! Character.isWhitespace(line.charAt(i))) break; + } + + return line.startsWith(" This task can take the following arguments:

    + * + *
      + *
    • srcdir
    • + *
    • destdir
    • + *
    • include
    • + *
    • exclude
    • + *
    + * + *

    Of these arguments, only sourcedir is required.

    + * + *

    When this task executes, it will scan the srcdir based on the + * include and exclude properties.

    + */ + +public class StripNonBodyHtml extends MatchingTask { + + private File srcDir; + private File destDir = null; + + public void setSrcdir(File srcDir) { + this.srcDir = srcDir; + } + + public void setDestdir(File destDir) { + this.destDir = destDir; + } + + public void execute() throws BuildException { + if (srcDir == null) { + throw new BuildException("srcdir attribute must be set!"); + } + if (!srcDir.exists()) { + throw new BuildException("srcdir does not exist!"); + } + if (!srcDir.isDirectory()) { + throw new BuildException("srcdir is not a directory!"); + } + if (destDir != null) { + if (!destDir.exists()) { + throw new BuildException("destdir does not exist!"); + } + if (!destDir.isDirectory()) { + throw new BuildException("destdir is not a directory!"); + } + } + + DirectoryScanner ds = super.getDirectoryScanner(srcDir); + String[] files = ds.getIncludedFiles(); + + log("stripping " + files.length + " files"); + int stripped = 0; + for (int i = 0, len = files.length; i < len; i++) { + if (processFile(files[i])) { + stripped++; + } else { + log(files[i] + " not stripped"); + } + } + log(stripped + " files successfully stripped"); + } + + boolean processFile(String filename) throws BuildException { + File srcFile = new File(srcDir, filename); + File destFile; + if (destDir == null) { + destFile = srcFile; + } else { + destFile = new File(destDir, filename); + destFile.getParentFile().mkdirs(); + } + try { + return strip(srcFile, destFile); + } catch (IOException e) { + throw new BuildException(e); + } + } + + private boolean strip(File f, File g) throws IOException { + BufferedInputStream in = + new BufferedInputStream(new FileInputStream(f)); + String s = readToString(in); + in.close(); + return writeBodyTo(s, g); + } + + private ByteArrayOutputStream temp = new ByteArrayOutputStream(); + private byte[] buf = new byte[2048]; + + private String readToString(InputStream in) throws IOException { + ByteArrayOutputStream temp = this.temp; + byte[] buf = this.buf; + String s = ""; + try { + while (true) { + int i = in.read(buf, 0, 2048); + if (i == -1) break; + temp.write(buf, 0, i); + + } + s = temp.toString(); + } finally { + temp.reset(); + } + return s; + } + + private boolean writeBodyTo(String s, File f) throws IOException { + int start;//, end; + try { + start = findStart(s); + findEnd(s, start); + } catch (ParseException e) { + return false; // if we get confused, just don't write the file. + } + s = processBody(s,f); + BufferedOutputStream out = + new BufferedOutputStream(new FileOutputStream(f)); + + out.write(s.getBytes()); + out.close(); + return true; + } + + /** + * Process body. This implemenation strips text + * between <!-- start strip --> + * and <!-- end strip --> + * inclusive. + */ + private String processBody(String body, File file) { + if (null == body) return body; + final String START = ""; + final String END = ""; + return stripTags(body, file.toString(), START, END); + } + + /** + * Strip 0..n substrings in input: "s/${START}.*${END}//g" + * @param input the String to strip + * @param source the name of the source for logging purposes + * @param start the starting tag (case sensitive) + * @param end the ending tag (case sensitive) + */ + String stripTags(String input, final String SOURCE, + final String START, final String END) { + if (null == input) return input; + StringBuffer buffer = new StringBuffer(input.length()); + String result = input; + int curLoc = 0; + while (true) { + int startLoc = input.indexOf(START, curLoc); + if (-1 == startLoc) { + buffer.append(input.substring(curLoc)); + result = buffer.toString(); + break; // <------------ valid exit + } else { + int endLoc = input.indexOf(END, startLoc); + if (-1 == endLoc) { + log(SOURCE + " stripTags - no end tag - startLoc=" + startLoc); + break; // <------------ invalid exit + } else if (endLoc < startLoc) { + log(SOURCE + " stripTags - impossible: startLoc=" + + startLoc + " > endLoc=" + endLoc); + break; // <------------ invalid exit + } else { + buffer.append(input.substring(curLoc, startLoc)); + curLoc = endLoc + END.length(); + } + } + } + return result; + } + + private int findStart(String s) throws ParseException { + int len = s.length(); + int start = 0; + while (true) { + start = s.indexOf("= len) throw barf(); + char ch = s.charAt(start); + if (ch == '>') return start + 1; + if (Character.isWhitespace(ch)) { + start = s.indexOf('>', start); + if (start == -1) return -1; + return start + 1; + } + } + } + + private int findEnd(String s, int start) throws ParseException { + int end; + end = s.indexOf("", start); + if (end == -1) { + end = s.indexOf("", start); + if (end == -1) throw barf(); + } + return end; + } + + private static class ParseException extends Exception { + private static final long serialVersionUID = -1l; + } + + private static ParseException barf() { + return new ParseException(); + } +} diff --git a/build/src/main/java./aspectj/internal/tools/ant/taskdefs/TestBuildModule.java b/build/src/main/java./aspectj/internal/tools/ant/taskdefs/TestBuildModule.java new file mode 100644 index 000000000..bd3b99609 --- /dev/null +++ b/build/src/main/java./aspectj/internal/tools/ant/taskdefs/TestBuildModule.java @@ -0,0 +1,79 @@ +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + + +package org.aspectj.internal.tools.ant.taskdefs; + +import java.io.File; +import java.util.Arrays; + +import org.apache.tools.ant.Project; +import org.aspectj.internal.tools.build.BuildSpec; +import org.aspectj.internal.tools.build.Builder; +import org.aspectj.internal.tools.build.Util; + +public class TestBuildModule { +// private static boolean REBUILD = false; + private static final String SYNTAX = "java {classname} <[product|module]dir>"; + public static void main(String[] args) { + + if ((null == args) || (1 > args.length) + || !Util.canReadDir(new File(args[0]))) { + System.err.println(SYNTAX); + return; + } + File dir = new File(args[0]); + // create a module + if (Util.canReadDir(new File(dir, "dist"))) { + createProduct(args); + } else if (Util.canReadFile(new File(dir, ".classpath"))) { + createModule(args); + } else { + System.err.println(SYNTAX); + } + } + + static void createModule(String[] args) { + File moduleDir = new File(args[0]); + File baseDir = moduleDir.getParentFile(); + if (null == baseDir) { + baseDir = new File("."); + } + File jarDir = new File(baseDir, "aj-build-jars"); + if (!(Util.canReadDir(jarDir) || jarDir.mkdirs())) { + System.err.println("createModule unable to create " + jarDir); + return; + } + + // set module dir or basedir plus module name + BuildSpec buildSpec = new BuildSpec(); + buildSpec.moduleDir = moduleDir; + buildSpec.jarDir = jarDir; + buildSpec.verbose = true; + buildSpec.failonerror = true; + buildSpec.trimTesting = true; + buildSpec.rebuild = true; + + File tempDir = null; + Project project = new Project(); + project.setProperty("verbose", "true"); + project.setName("TestBuildModule.createModule" + Arrays.asList(args)); + Builder builder = AntBuilder.getBuilder("", project, tempDir); + builder.build(buildSpec); + } + + static void createProduct(String[] args) { + throw new Error("unimplemented"); + } +} + diff --git a/build/src/main/java./aspectj/internal/tools/ant/taskdefs/VersionUptodate.java b/build/src/main/java./aspectj/internal/tools/ant/taskdefs/VersionUptodate.java new file mode 100644 index 000000000..92b271c69 --- /dev/null +++ b/build/src/main/java./aspectj/internal/tools/ant/taskdefs/VersionUptodate.java @@ -0,0 +1,144 @@ +/* ******************************************************************* + * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + +package org.aspectj.internal.tools.ant.taskdefs; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Task; + +/** + * Check if version source file has the specified build version, + * and ensure a tag file reflects whether it does or not. + */ +public class VersionUptodate extends Task { + public VersionUptodate() {} + + private String buildVersion; + private File versionSource; + private File versionTagFile; + + /** + * @param buildVersion String expected as Version.text - required + */ + public void setVersion(String buildVersion) { + this.buildVersion = buildVersion; + } + + /** + * @param versionSource the File Version.java containing text constant + * - required + */ + public void setVersionSourceFile(File versionSource) { + this.versionSource = versionSource; + } + + /** + * @param versionTagFile the File whose existence signals that the version + * is uptodate after this task executes - required. + */ + public void setVersionTagFile(File versionTagFile) { + this.versionTagFile = versionTagFile; + } + + /** + * If the Version.java source file contains the correct + * build version, then create the output tag file, + * else delete it if it exists. + * @throws BuildException if tagFile not creatable and version is incorrect + * or if version is correct and tagFile cannot be deleted. + */ + public void execute() throws BuildException { + if (null == buildVersion) { + throw new BuildException("require buildVersion"); + } + if ((null == versionSource) || !versionSource.canRead()){ + throw new BuildException("require versionSource"); + } + if (null == versionTagFile){ + throw new BuildException("require versionTagFile"); + } + if (sameVersion(versionSource, buildVersion)) { + if (!versionTagFile.exists()) { + createFile(versionTagFile, buildVersion); + } + } else if (null == versionTagFile) { + throw new BuildException("no tag file, and version out of date"); + } else if (versionTagFile.exists()) { + if (!versionTagFile.delete()) { + throw new BuildException("version out of date, but cannot delete " + versionTagFile); + } + } + } + + /** + * Detect whether version is correct in Java sources. + * @param versionSource + * @param buildVersion + * @return boolean + */ + private boolean sameVersion(File versionSource, String buildVersion) { + // XXX build and load instead of scanning? + FileReader fileReader = null; + try { + fileReader = new FileReader(versionSource); + BufferedReader reader = new BufferedReader(fileReader); + String line; + while (null != (line = reader.readLine())) { + int loc = line.indexOf("static final String text = "); + if (-1 != loc) { + return (-1 != line.indexOf(buildVersion , loc)); + } + } + return false; + } catch (IOException e) { + return false; + } finally { + if (null != fileReader) { + try { + fileReader.close(); + } catch (IOException e) { + } + } + } + } + + /** + * Create file with contents + */ + private void createFile(File versionTagFile, String contents) { + FileWriter writer = null; + try { + writer = new FileWriter(versionTagFile); + char[] buf = new char[contents.length()]; + contents.getChars(0, buf.length, buf, 0); + writer.write(contents); + } catch (IOException e) { + throw new BuildException("writing " + versionTagFile, e); + } finally { + if (null != writer) { + try { + writer.close(); + } catch (IOException e){ + // ignore + } + } + } + } + +} + diff --git a/build/src/main/java./aspectj/internal/tools/ant/taskdefs/taskdefs.properties b/build/src/main/java./aspectj/internal/tools/ant/taskdefs/taskdefs.properties new file mode 100644 index 000000000..884077a85 --- /dev/null +++ b/build/src/main/java./aspectj/internal/tools/ant/taskdefs/taskdefs.properties @@ -0,0 +1,21 @@ +ajinstaller=org.aspectj.internal.tools.ant.taskdefs.AJInstaller +ajpush=org.aspectj.internal.tools.ant.taskdefs.AJPush +ajbuild=org.aspectj.internal.tools.ant.taskdefs.BuildModule +versionuptodate=org.aspectj.internal.tools.ant.taskdefs.VersionUptodate +checklics=org.aspectj.internal.tools.ant.taskdefs.Checklics +stripnonbodyhtml=org.aspectj.internal.tools.ant.taskdefs.StripNonBodyHtml + +# ajclean=org.aspectj.internal.tools.ant.taskdefs.AJclean +# ajcvs=org.aspectj.internal.tools.ant.taskdefs.Ajcvs +# ajikes=org.aspectj.internal.tools.ant.taskdefs.AJikes +# ajinit=org.aspectj.internal.tools.ant.taskdefs.AjInit +# checkrelease=org.aspectj.internal.tools.ant.taskdefs.Checkrelease +# clear=org.aspectj.internal.tools.ant.taskdefs.Clear +# inlinestylesheetaj=org.aspectj.internal.tools.ant.taskdefs.CopyAndInlineStyleshee +# ensure=org.aspectj.internal.tools.ant.taskdefs.Ensure +# ensureproperties=org.aspectj.internal.tools.ant.taskdefs.EnsureProperties +# newdir=org.aspectj.internal.tools.ant.taskdefs.Newdir +# overwrite=org.aspectj.internal.tools.ant.taskdefs.Overwrite +# props2filters=org.aspectj.internal.tools.ant.taskdefs.Props2Filters +# tgz=org.aspectj.internal.tools.ant.taskdefs.Tgz +# vmcheck=org.aspectj.internal.tools.ant.taskdefs.VMCheck diff --git a/build/src/main/java./aspectj/internal/tools/build/BuildSpec.java b/build/src/main/java./aspectj/internal/tools/build/BuildSpec.java new file mode 100644 index 000000000..ed0a453e1 --- /dev/null +++ b/build/src/main/java./aspectj/internal/tools/build/BuildSpec.java @@ -0,0 +1,80 @@ +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC), + * 2005 Contributors. + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + + +package org.aspectj.internal.tools.build; + + +import java.io.File; + +/** + * Open struct for specifying builds for both modules and products. + * Separated from bulder to permit this to build many modules + * concurrently. + */ +public class BuildSpec { + public static final String DEFAULT_VERSION = "DEVELOPMENT"; + // shared + public File baseDir; + public File moduleDir; + public File jarDir; + public File tempDir; + public File stagingDir; + public String buildConfig; + public String version; + public boolean rebuild; + public boolean trimTesting; + public boolean assembleAll; + public boolean failonerror; + public boolean verbose; + + // building products + public File productDir; + public boolean createInstaller; + public File distDir; + + // building modules + public String module; + public BuildSpec() { + version = DEFAULT_VERSION; + } + + public boolean isProduct() { + return (Util.canReadDir(productDir)); + } + + public boolean isModule() { + return (!isProduct() && Util.canReadDir(moduleDir)); + } + + public boolean isValid() { + return (isProduct() || isModule()); + } + + public String toString() { + if (null != productDir) { + return "product " + productDir.getName(); + } else if (null != moduleDir) { + return "module " + moduleDir.getName(); + } else { + return ""; + } + } +} + diff --git a/build/src/main/java./aspectj/internal/tools/build/Builder.java b/build/src/main/java./aspectj/internal/tools/build/Builder.java new file mode 100644 index 000000000..72f53e901 --- /dev/null +++ b/build/src/main/java./aspectj/internal/tools/build/Builder.java @@ -0,0 +1,676 @@ +/* ******************************************************************* + * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC), + * 2003 Contributors. + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * PARC initial implementation + * ******************************************************************/ + +package org.aspectj.internal.tools.build; + +import java.io.File; +import java.io.FileFilter; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Properties; +import java.util.StringTokenizer; + +import org.apache.tools.ant.BuildException; +import org.aspectj.internal.tools.build.Result.Kind; + +/** + * Template class to build (eclipse) modules (and, weakly, products), including + * any required modules. When building modules, this assumes: + *
      + *
    • the name of the module is the base name of the module directory
    • + *
    • all module directories are in the same base (workspace) directory
    • + *
    • the name of the target module jar is {moduleName}.jar
    • + *
    • a module directory contains a .classpath file with + * (currently line-parseable) entries per Eclipse (XML) conventions
    • + *
    • Builder.RESOURCE_PATTERN identifies all resources to copy + * to output.
    • + *
    • This can safely trim test-related code: + *
        + *
      • source directories named "testsrc"
      • + *
      • libraries named "junit.jar"
      • + *
      • required modules whose names start with "testing"
      • + *
      + *
    • A file {moduleDir}/{moduleName}.properties is a property + * file possibly containing entries defining requirements to be merged with the + * output jar (deprecated mechanism - use assembleAll or products)
    • + *
    + * This currently provides no control over the compile or assembly process, but + * clients can harvest {moduleDir}/bin directories to re-use the + * results of eclipse compiles. + *

    + * When building products, this assumes: + *

      + *
    • the installer-resources directory is a peer of the products directory, + * itself the parent of the particular product directory.
    • + *
    • the dist, jar, product, and base (module) directory are set
    • + *
    • the product distribution consists of all (and only) the files in the + * dist sub-directory of the product directory
    • + *
    • files in the dist sub-directory that are empty and end with .jar + * represent modules to build, either as named or through aliases known here.
    • + *
    • When assembling the distribution, all non-binary files are to be + * filtered. + *
    • + *
    • the name of the product installer is + * aspectj-{productName}-{version}.jar, where {productName} is the base name of + * the product directory
    • + *
    + *

    + * When run using main(String[]), all relevant Ant libraries and properties must + * be defined. + *

    + * Written to compile standalone. Refactor if using utils, bridge, etc. + */ +public abstract class Builder { + + /** + * This has only weak forms for build instructions needed: - resource + * pattern - compiler selection and control + * + * Both assumed and generated paths are scattered; see XXXNameLiteral and + * XXXFileLiteral. + * + * Builder is supposed to be thread-safe, but currently caches build + * properties to tunnel for filters. hmm. + */ + + public static final String RESOURCE_PATTERN; + + public static final String BINARY_SOURCE_PATTERN; + + public static final String ALL_PATTERN; + + /** enable copy filter semantics */ + protected static final boolean FILTER_ON = true; + + /** disable copy filter semantics */ + protected static final boolean FILTER_OFF = false; + + /** define libraries to skip as comma-delimited values for this key */ + private static final String SKIP_LIBRARIES_KEY = "skip.libraries"; + + /** List (String) names of libraries to skip during assembly */ + private static final List SKIP_LIBRARIES; + + private static final String ERROR_KEY = "error loading properties"; + + private static final Properties PROPS; + static { + PROPS = new Properties(); + List skips = Collections.emptyList(); + String resourcePattern = "**/*.txt,**/*.rsc,**/*.gif,**/*.properties"; + String allPattern = "**/*"; + String binarySourcePattern = "**/*.rsc,**/*.gif,**/*.jar,**/*.zip"; + String name = Builder.class.getName().replace('.', '/') + ".properties"; + try { + InputStream in = Builder.class.getClassLoader() + .getResourceAsStream(name); + PROPS.load(in); + allPattern = PROPS.getProperty("all.pattern"); + resourcePattern = PROPS.getProperty("resource.pattern"); + binarySourcePattern = PROPS.getProperty("binarySource.pattern"); + skips = commaStrings(PROPS.getProperty(SKIP_LIBRARIES_KEY)); + } catch (Throwable t) { + if (t instanceof ThreadDeath) { + throw (ThreadDeath) t; + } + String m = "error loading " + name + ": " + t.getClass() + " " + t; + PROPS.setProperty(ERROR_KEY, m); + } + SKIP_LIBRARIES = skips; + ALL_PATTERN = allPattern; + BINARY_SOURCE_PATTERN = binarySourcePattern; + RESOURCE_PATTERN = resourcePattern; + } + + /** + * Splits strings into an unmodifable List of String using + * comma as the delimiter and trimming whitespace from the result. + * + * @param text + * String to split. + * @return unmodifiable List (String) of String delimited by comma in text + */ + public static List commaStrings(String text) { + if ((null == text) || (0 == text.length())) { + return Collections.EMPTY_LIST; + } + List strings = new ArrayList(); + StringTokenizer tok = new StringTokenizer(text, ","); + while (tok.hasMoreTokens()) { + String token = tok.nextToken().trim(); + if (0 < token.length()) { + strings.add(token); + } + } + return Collections.unmodifiableList(strings); + } + + /** + * Map delivered-jar name to created-module name + * + * @param jarName + * the String (lowercased) of the jar/zip to map + */ + private String moduleAliasFor(String jarName) { + String result = PROPS.getProperty("alias." + jarName, jarName); + if (verbose && result.equals(jarName)) { + String m = "expected alias for " + jarName; + handler.error(m + PROPS.getProperty(ERROR_KEY, "")); + } + return result; + } + + protected final Messager handler; + + protected boolean buildingEnabled; + + private final File tempDir; + + private final ArrayList tempFiles; + + private final boolean useEclipseCompiles; + + protected boolean verbose; + + protected Builder(File tempDir, boolean useEclipseCompiles, Messager handler) { + Util.iaxIfNull(handler, "handler"); + this.useEclipseCompiles = useEclipseCompiles; + this.handler = handler; + this.tempFiles = new ArrayList(); + if ((null == tempDir) || !tempDir.canWrite() || !tempDir.isDirectory()) { + this.tempDir = Util.makeTempDir("Builder"); + } else { + this.tempDir = tempDir; + } + buildingEnabled = true; + } + + /** tell builder to stop or that it's ok to run */ + public void setBuildingEnabled(boolean enabled) { + buildingEnabled = enabled; + } + + public void setVerbose(boolean verbose) { + this.verbose = verbose; + } + + private void verifyBuildSpec(BuildSpec buildSpec) { + if (null == buildSpec.productDir) { // ensure module properties + // derive moduleDir from baseDir + module + if (null == buildSpec.moduleDir) { + if (null == buildSpec.baseDir) { + throw new BuildException("require baseDir or moduleDir"); + } else if (null == buildSpec.module) { + throw new BuildException("require module with baseDir"); + } else { + if (null == buildSpec.baseDir) { + buildSpec.baseDir = new File("."); // user.home? + } + buildSpec.moduleDir = new File(buildSpec.baseDir, + buildSpec.module); + } + } else if (null == buildSpec.baseDir) { + // derive baseDir from moduleDir parent + buildSpec.baseDir = buildSpec.moduleDir.getParentFile(); + // rule: base is parent + if (null == buildSpec.baseDir) { + buildSpec.baseDir = new File("."); // user.home? + } + handler.log("Builder using derived baseDir: " + + buildSpec.baseDir); + } + Util.iaxIfNotCanReadDir(buildSpec.moduleDir, "moduleDir"); + if (null == buildSpec.module) { + // derive module name from directory + buildSpec.module = buildSpec.moduleDir.getName(); + if (null == buildSpec.module) { + throw new BuildException("no name, even from " + + buildSpec.moduleDir); + } + } + } + } + + /** + * Find the Result (and hence Module and Modules) for this BuildSpec. + */ + protected Result specifyResultFor(BuildSpec buildSpec) { + if (buildSpec.trimTesting + && (-1 != buildSpec.module.indexOf("testing"))) { // XXXNameLiteral + String warning = "Warning - cannot trimTesting for testing modules: "; + handler.log(warning + buildSpec.module); + } + Messager handler = new Messager(); + Modules modules = new Modules(buildSpec.baseDir, buildSpec.jarDir, + handler); + + final Module moduleToBuild = modules.getModule(buildSpec.module); + Kind kind = Result.kind(buildSpec.trimTesting, + buildSpec.assembleAll); + return moduleToBuild.getResult(kind); + } + + public final boolean build(BuildSpec buildSpec) { + if (!buildingEnabled) { + return false; + } + verifyBuildSpec(buildSpec); + + if (null != buildSpec.productDir) { + return buildProduct(buildSpec); + } + Result result = specifyResultFor(buildSpec); + ArrayList errors = new ArrayList(); + try { + return buildAll(result, errors); + } finally { + if (0 < errors.size()) { + String label = "error building " + buildSpec + ": "; + for (Iterator iter = errors.iterator(); iter.hasNext();) { + String m = label + iter.next(); + handler.error(m); + } + } + } + } + + /** + * Clean up any temporary files, etc. after build completes + */ + public boolean cleanup() { + boolean noErr = true; + for (ListIterator iter = tempFiles.listIterator(); iter.hasNext();) { + File file = (File) iter.next(); + if (!Util.deleteContents(file) || !file.delete()) { + if (noErr) { + noErr = false; + } + handler.log("unable to clean up " + file); + } + } + return noErr; + } + + protected final boolean isLogging() { + return (verbose && (null != this.handler)); + } + + protected Result[] skipUptodate(Result[] results) { + if (null == results) { + return new Result[0]; + } + Result[] done = new Result[results.length]; + int to = 0; + for (int i = 0; i < done.length; i++) { + if ((null != results[i]) && results[i].outOfDate()) { + done[to++] = results[i]; + } + } + if (to < results.length) { + Result[] newdone = new Result[to]; + System.arraycopy(done, 0, newdone, 0, newdone.length); + done = newdone; + } + return done; + } + + /** + * Build a result with all antecedants. + * + * @param result + * the Result to build + * @param errors + * the List sink for errors, if any + * @return false after successful build, when module jar should exist + */ + protected final boolean buildAll(Result result, List errors) { + Result[] buildList = skipUptodate(getAntecedantResults(result)); + ArrayList doneList = new ArrayList(); + if ((null != buildList) && (0 < buildList.length)) { + if (isLogging()) { + handler.log("modules to build: " + Arrays.asList(buildList)); + } + for (int i = 0; i < buildList.length; i++) { + Result required = buildList[i]; + if (!buildingEnabled) { + return false; + } + String requiredName = required.getName(); + if (!doneList.contains(requiredName)) { + doneList.add(requiredName); + if (!buildOnly(required, errors)) { + return false; + } + } + } + } + return true; + } + + /** + * Build a module but no antecedants. + * + * @param module + * the Module to build + * @param errors + * the List sink for errors, if any + * @return false after successful build, when module jar should exist + */ + protected final boolean buildOnly(Result result, List errors) { + if (!result.outOfDate()) { + return true; + } + if (isLogging()) { + handler.log("building " + result); + } + if (!buildingEnabled) { + return false; + } + if (result.getKind().assemble) { + return assembleAll(result, handler); + } + Module module = result.getModule(); + final File classesDir; + if (useEclipseCompiles) { + classesDir = new File(module.moduleDir, "bin"); // FileLiteral + } else { + String name = "classes-" + System.currentTimeMillis(); + classesDir = new File(tempDir, name); + } + if (verbose) { + handler.log("buildOnly " + module); + } + try { + return (compile(result, classesDir,useEclipseCompiles, errors)) + && assemble(result, classesDir, errors); + } finally { + if (!useEclipseCompiles && !Util.delete(classesDir)) { + errors.add("buildOnly unable to delete " + classesDir); + } + } + } + + /** + * Register temporary file or directory to be deleted when the build is + * complete, even if an Exception is thrown. + */ + protected void addTempFile(File tempFile) { + if (null != tempFile) { + tempFiles.add(tempFile); + } + } + + /** + * Build product by discovering any modules to build, building those, + * assembling the product distribution, and optionally creating an installer + * for it. + * + * @return true on success + */ + protected final boolean buildProduct(BuildSpec buildSpec) + throws BuildException { + Util.iaxIfNull(buildSpec, "buildSpec"); + + if (!buildSpec.trimTesting) { + buildSpec.trimTesting = true; + handler.log("testing trimmed for " + buildSpec); + } + Util.iaxIfNotCanReadDir(buildSpec.productDir, "productDir"); + Util.iaxIfNotCanReadDir(buildSpec.baseDir, "baseDir"); + Util.iaxIfNotCanWriteDir(buildSpec.distDir, "distDir"); + + // ---- discover modules to build, and build them + Modules modules = new Modules(buildSpec.baseDir, buildSpec.jarDir, + handler); + ProductModule[] productModules = discoverModules(buildSpec.productDir, + modules); + for (int i = 0; i < productModules.length; i++) { + if (buildSpec.verbose) { + handler.log("building product module " + productModules[i]); + } + if (!buildProductModule(productModules[i])) { + return false; + } + } + if (buildSpec.verbose) { + handler.log("assembling product module for " + buildSpec); + } + + // ---- assemble product distribution + final String productName = buildSpec.productDir.getName(); + final File targDir = new File(buildSpec.distDir, productName); + final String targDirPath = targDir.getPath(); + if (targDir.canWrite()) { + Util.deleteContents(targDir); + } + + if (!targDir.canWrite() && !targDir.mkdirs()) { + if (buildSpec.verbose) { + handler.log("buildProduct unable to create " + targDir); + } + return false; + } + + // copy non-binaries (with filter) + File distDir = new File(buildSpec.productDir, "dist"); + if (!copyNonBinaries(buildSpec, distDir, targDir)) { + return false; + } + + // copy binaries (but not module flag files) + String excludes = null; + { + StringBuffer buf = new StringBuffer(); + for (int i = 0; i < productModules.length; i++) { + if (0 < buf.length()) { + buf.append(","); + } + buf.append(productModules[i].relativePath); + } + if (0 < buf.length()) { + excludes = buf.toString(); + } + } + + if (!copyBinaries(buildSpec, distDir, targDir, excludes)) { + return false; + } + + // copy binaries associated with module flag files + for (int i = 0; i < productModules.length; i++) { + final ProductModule product = productModules[i]; + final Kind kind = Result.kind(Result.NORMAL, product.assembleAll); + Result result = product.module.getResult(kind); + String targPath = Util.path(targDirPath, product.relativePath); + File jarFile = result.getOutputFile(); + copyFile(jarFile, new File(targPath), FILTER_OFF); + } + handler.log("created product in " + targDir); + + // ---- create installer + if (buildSpec.createInstaller) { + return buildInstaller(buildSpec, targDirPath); + } else { + return true; + } + } + + protected boolean copyBinaries(BuildSpec buildSpec, File distDir, + File targDir, String excludes) { + String includes = Builder.BINARY_SOURCE_PATTERN; + return copyFiles(distDir, targDir, includes, excludes, FILTER_OFF); + } + + /** + * filter-copy everything but the binaries + */ + protected boolean copyNonBinaries(BuildSpec buildSpec, File distDir, + File targDir) { + String excludes = Builder.BINARY_SOURCE_PATTERN; + String includes = Builder.ALL_PATTERN; + return copyFiles(distDir, targDir, includes, excludes, FILTER_ON); + } + + protected final boolean buildProductModule(ProductModule module) { + ArrayList errors = new ArrayList(); + try { + Kind productKind = Result.kind(Result.NORMAL, Result.ASSEMBLE); + Result result = module.module.getResult(productKind); + return buildAll(result, errors); + } finally { + for (Iterator iter = errors.iterator(); iter.hasNext();) { + handler.error("error building " + module + ": " + iter.next()); + } + } + } + + /** + * Discover any modules that might need to be built in order to assemble the + * product distribution. This interprets empty .jar files as module + * deliverables. + */ + protected ProductModule[] discoverModules(File productDir, Modules modules) { + final ArrayList found = new ArrayList(); + FileFilter filter = new FileFilter() {// empty jar files + public boolean accept(File file) { + if ((null != file) && file.canRead() + && file.getPath().endsWith(".jar") // XXXFileLiteral + && (0l == file.length())) { + found.add(file); + } + return true; + } + }; + Util.visitFiles(productDir, filter); + ArrayList results = new ArrayList(); + for (File file: found) { + String jarName = moduleAliasFor(file.getName().toLowerCase()); + if (jarName.endsWith(".jar") || jarName.endsWith(".zip")) { // XXXFileLiteral + jarName = jarName.substring(0, jarName.length() - 4); + } else { + handler.log("can only replace .[jar|zip]: " + file); + // XXX error? + } + boolean assembleAll = jarName.endsWith("-all"); + // XXXFileLiteral + String name = (!assembleAll ? jarName : jarName.substring(0, + jarName.length() - 4)); + Module module = modules.getModule(name); + if (null == module) { + handler.log("unable to find module for " + file); + } else { + results.add(new ProductModule(productDir, file, module, + assembleAll)); + } + } + return (ProductModule[]) results.toArray(new ProductModule[0]); + } + + /** + * Subclasses should query whether to include library files in the assembly. + * + * @param module + * the Module being built + * @param libraries + * the List of File path to the jar to consider assembling + * @return true if the jar should be included, false otherwise. + */ + protected void removeLibraryFilesToSkip(Module module, List libraries) { + for (ListIterator liter = libraries.listIterator(); liter.hasNext();) { + File library = (File) liter.next(); + final String fname = library.getName(); + if (null != fname) { + for (Iterator iter = SKIP_LIBRARIES.iterator(); iter.hasNext();) { + String name = (String) iter.next(); + if (fname.equals(name)) { + liter.remove(); + break; + } + } + } + } + } + + /** + * @return String[] names of results to build for this module + */ + abstract protected Result[] getAntecedantResults(Result toBuild); + + /** + * Compile module classes to classesDir, saving String errors. + * + * @param module + * the Module to compile + * @param classesDir + * the File directory to compile to + * @param useExistingClasses + * if true, don't recompile and ensure classes are available + * @param errors + * the List to add error messages to + */ + abstract protected boolean compile(Result result, File classesDir, + boolean useExistingClasses, List errors); + + /** + * Assemble the module distribution from the classesDir, saving String + * errors. + * + * @see #removeLibraryFilesToSkip(Module, File) + */ + abstract protected boolean assemble(Result result, File classesDir, + List errors); + + /** + * Assemble the module distribution from the classesDir and all + * antecendants, saving String errors. + * + * @see #removeLibraryFilesToSkip(Module, File) + */ + abstract protected boolean assembleAll(Result result, Messager handler); + + /** + * Generate the installer for this product to targDirPath + */ + abstract protected boolean buildInstaller(BuildSpec buildSpec, + String targDirPath); + + /** + * Copy fromFile to toFile, optionally filtering contents + */ + abstract protected boolean copyFile(File fromFile, File toFile, + boolean filter); + + /** + * Copy toDir any fromDir included files without any exluded files, + * optionally filtering contents. + * + * @param fromDir + * File dir to read from - error if not readable + * @param toDir + * File dir to write to - error if not writable + * @param included + * String Ant pattern of included files (if null, include all) + * @param excluded + * String Ant pattern of excluded files (if null, exclude none) + * @param filter + * if FILTER_ON, then filter file contents using global + * token/value pairs + */ + abstract protected boolean copyFiles(File fromDir, File toDir, + String included, String excluded, boolean filter); +} diff --git a/build/src/main/java./aspectj/internal/tools/build/Builder.properties b/build/src/main/java./aspectj/internal/tools/build/Builder.properties new file mode 100644 index 000000000..3838514f4 --- /dev/null +++ b/build/src/main/java./aspectj/internal/tools/build/Builder.properties @@ -0,0 +1,20 @@ +# documented in build/readme-build-module.html + +# alias product/dist/lib/{name} to project jar +# used by Builder.moduleAliasFor(String) +alias.aspectjtools.jar=ajbrowser-all.jar +alias.aspectjrt.jar=aspectj5rt-all.jar +alias.aspectjweaver.jar=loadtime5-all.jar +# alias.aspectjlib.jar=org.aspectj.lib.jar +alias.org.aspectj.matcher.jar=org.aspectj.matcher-all.jar + +# libraries to avoid bundling (IBM JRE different, etc.) +# see build/readme-build-module.html, Builder.SKIP_LIBRARIES +skip.libraries=asm-3.1.jar,core.jar,graphics.jar,ant.jar,tools.jar,bcel-verifier.jar,asm-3.1.jar,junit.jar,xml-apis.jar,xercesImpl.jar,commons.jar,jrockit.jar + +# Ant patterns to gather and omit resources +# files copied during module jar assembly +resource.pattern=**/*.txt,**/*.rsc,**/*.gif,**/*.properties,**/*.xml,**/*.dtd +# files not filtered when copied during product assembly +binarySource.pattern=**/*.rsc,**/*.gif,**/*.jar,**/*.zip +all.pattern=**/* diff --git a/build/src/main/java./aspectj/internal/tools/build/Messager.java b/build/src/main/java./aspectj/internal/tools/build/Messager.java new file mode 100644 index 000000000..4752fd645 --- /dev/null +++ b/build/src/main/java./aspectj/internal/tools/build/Messager.java @@ -0,0 +1,43 @@ +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + + +package org.aspectj.internal.tools.build; + +/** logging stub XXX replace */ +public class Messager { + public Messager() { + } + public boolean log(String s) { + System.out.println(s); + return true; + } + + public boolean error(String s) { + System.out.println(s); + return true; + } + + public boolean logException(String context, Throwable thrown) { + System.err.println(context); + thrown.printStackTrace(System.err); + return true; + } +} + + + + + + + diff --git a/build/src/main/java./aspectj/internal/tools/build/Module.java b/build/src/main/java./aspectj/internal/tools/build/Module.java new file mode 100644 index 000000000..3f0afbfd9 --- /dev/null +++ b/build/src/main/java./aspectj/internal/tools/build/Module.java @@ -0,0 +1,754 @@ +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + +package org.aspectj.internal.tools.build; + +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Properties; +import java.util.StringTokenizer; + +import org.aspectj.internal.tools.build.Result.Kind; +import org.aspectj.internal.tools.build.Util.OSGIBundle; +import org.aspectj.internal.tools.build.Util.OSGIBundle.RequiredBundle; + + +/** + * This represents an (eclipse) build module/unit used by a Builder to compile + * classes and/or assemble zip file of classes, optionally with all antecedants. + * This implementation infers attributes from two files in the module directory: + *

      + *
    • an Eclipse project .classpath file containing required + * libraries and modules (collectively, "antecedants")
    • + *
    • a file {moduleName}.mf.txt is taken as the manifest of + * any .jar file produced, after filtering.
    • + *
    + * + * @see Builder + * @see Modules#getModule(String) + */ +public class Module { + private static final String[] ATTS = new String[] { "exported", "kind", + "path", "sourcepath" }; + +// private static final int getATTSIndex(String key) { +// for (int i = 0; i < ATTS.length; i++) { +// if (ATTS[i].equals(key)) +// return i; +// } +// return -1; +// } + + /** + * @return true if file is null or cannot be read or was last modified after + * time + */ + private static boolean outOfDate(long time, File file) { + return ((null == file) || !file.canRead() || (file.lastModified() > time)); + } + + /** @return all source files under srcDir */ + private static Iterator sourceFiles(File srcDir) { + ArrayList result = new ArrayList(); + sourceFiles(srcDir, result); + return result.iterator(); + } + + private static void sourceFiles(File srcDir, List result) { + if ((null == srcDir) || !srcDir.canRead() || !srcDir.isDirectory()) { + return; + } + File[] files = srcDir.listFiles(); + for (int i = 0; i < files.length; i++) { + if (files[i].isDirectory()) { + sourceFiles(files[i], result); + } else if (isSourceFile(files[i])) { + result.add(files[i]); + } + } + } + + private static void addIfNew(List source, List sink) { + for (File item: source) { + if (!sink.contains(item)) { + sink.add(item); + } + } + } + + /** + * Recursively find antecedant jars. + * + * @see findKnownJarAntecedants() + */ + static void doFindJarRequirements(Result result, List known) { + Util.iaxIfNull(result, "result"); + Util.iaxIfNull(known, "known"); + addIfNew(result.getLibJars(), known); + addIfNew(result.getExportedLibJars(), known); + Result[] reqs = result.getRequired(); + for (int i = 0; i < reqs.length; i++) { + Result requiredResult = reqs[i]; + File requiredJar = requiredResult.getOutputFile(); + if (!known.contains(requiredJar)) { + known.add(requiredJar); + doFindJarRequirements(requiredResult, known); + } + } + } + + /** @return true if this is a source file */ + private static boolean isSourceFile(File file) { + String path = file.getPath(); + return (path.endsWith(".java") || path.endsWith(".aj")); // XXXFileLiteral + } + +// /** @return List of File of any module or library jar ending with suffix */ +// private static ArrayList findJarsBySuffix(String suffix, Kind kind, +// List libJars, List required) { +// ArrayList result = new ArrayList(); +// if (null != suffix) { +// // library jars +// for (Iterator iter = libJars.iterator(); iter.hasNext();) { +// File file = (File) iter.next(); +// if (file.getPath().endsWith(suffix)) { +// result.add(file); +// } +// } +// // module jars +// for (Iterator iter = required.iterator(); iter.hasNext();) { +// Module module = (Module) iter.next(); +// Result moduleResult = module.getResult(kind); +// File file = moduleResult.getOutputFile(); +// if (file.getPath().endsWith(suffix)) { +// result.add(file); +// } +// } +// } +// return result; +// } + + public final boolean valid; + + public final File moduleDir; + + public final String name; + + /** reference back to collection for creating required modules */ + private final Modules modules; + + private final Result release; + + private final Result test; + + private final Result testAll; + + private final Result releaseAll; + + /** path to output jar - may not exist */ + private final File moduleJar; + + /** File list of library jars */ + private final List libJars; + + /** List of classpath variables */ + private final List classpathVariables; + + /** + * List of library jars exported to clients (duplicates some libJars + * entries) + */ + private final List exportedLibJars; + + /** File list of source directories */ + private final List srcDirs; + + /** properties from the modules {name}.properties file */ + private final Properties properties; + + /** List of required modules */ + private final List requiredModules; + + /** logger */ + private final Messager messager; + + Module(File moduleDir, File jarDir, String name, Modules modules, + Messager messager) { + Util.iaxIfNotCanReadDir(moduleDir, "moduleDir"); + Util.iaxIfNotCanReadDir(jarDir, "jarDir"); + Util.iaxIfNull(name, "name"); + Util.iaxIfNull(modules, "modules"); + this.moduleDir = moduleDir; + this.libJars = new ArrayList(); + this.exportedLibJars = new ArrayList(); + this.requiredModules = new ArrayList(); + this.srcDirs = new ArrayList(); + this.classpathVariables = new ArrayList(); + this.properties = new Properties(); + this.name = name; + this.modules = modules; + this.messager = messager; + this.moduleJar = new File(jarDir, name + ".jar"); + this.release = new Result(Result.RELEASE, this, jarDir); + this.releaseAll = new Result(Result.RELEASE_ALL, this, jarDir); + this.test = new Result(Result.TEST, this, jarDir); + this.testAll = new Result(Result.TEST_ALL, this, jarDir); + valid = init(); + } + + + /** @return Modules registry of known modules, including this one */ + public Modules getModules() { + return modules; + } + + /** + * @param kind + * the Kind of the result to recalculate + * @param recalculate + * if true, then force recalculation + * @return true if the target jar for this module is older than any source + * files in a source directory or any required modules or any + * libraries or if any libraries or required modules are missing + */ + public static boolean outOfDate(Result result) { + File outputFile = result.getOutputFile(); + if (!(outputFile.exists() && outputFile.canRead())) { + return true; + } + final long time = outputFile.lastModified(); + File file; + for (Iterator iter = result.getSrcDirs().iterator(); iter.hasNext();) { + File srcDir = iter.next(); + for (Iterator srcFiles = sourceFiles(srcDir); srcFiles.hasNext();) { + file = srcFiles.next(); + if (outOfDate(time, file)) { + return true; + } + } + } + // required modules + Result[] reqs = result.getRequired(); + for (int i = 0; i < reqs.length; i++) { + Result requiredResult = reqs[i]; + file = requiredResult.getOutputFile(); + if (outOfDate(time, file)) { + return true; + } + } + // libraries + for (Iterator iter = result.getLibJars().iterator(); iter.hasNext();) { + file = (File) iter.next(); + if (outOfDate(time, file)) { + return true; + } + } + return false; + } + + + + public String toString() { + return name; + } + + public String toLongString() { + return "Module [name=" + name + ", srcDirs=" + srcDirs + ", required=" + + requiredModules + ", moduleJar=" + moduleJar + ", libJars=" + + libJars + "]"; + } + + public Result getResult(Kind kind) { + return kind.assemble ? (kind.normal ? releaseAll : testAll) + : (kind.normal ? release : test); + } + + List srcDirs(Result result) { + myResult(result); + return srcDirs; + } + + List libJars(Result result) { + myResult(result); + return libJars; + } + + List classpathVariables(Result result) { + myResult(result); + return classpathVariables; + } + + List exportedLibJars(Result result) { + myResult(result); + return exportedLibJars; + } + + List requiredModules(Result result) { + myResult(result); + return requiredModules; + } + + private void myResult(Result result) { + if ((null == result) || this != result.getModule()) { + throw new IllegalArgumentException("not my result: " + result + ": " + this); + } + } + + private boolean init() { + boolean cp = initClasspath(); + boolean mf = initManifest(); + if (!cp && !mf) { + return false; + } + return initProperties() && reviewInit() && initResults(); + } + + /** read OSGI manifest.mf file XXX hacked */ + private boolean initManifest() { + File metaInf = new File(moduleDir, "META-INF"); + if (!metaInf.canRead() || !metaInf.isDirectory()) { + return false; + } + File file = new File(metaInf, "MANIFEST.MF"); // XXXFileLiteral + if (!file.exists()) { + return false; // ok, not OSGI + } + InputStream fin = null; + OSGIBundle bundle = null; + try { + fin = new FileInputStream(file); + bundle = new OSGIBundle(fin); + } catch (IOException e) { + messager.logException("IOException reading " + file, e); + return false; + } finally { + Util.closeSilently(fin); + } + RequiredBundle[] bundles = bundle.getRequiredBundles(); + for (int i = 0; i < bundles.length; i++) { + RequiredBundle required = bundles[i]; + update("src", "/" + required.name, required.text, false); + } + String[] libs = bundle.getClasspath(); + for (int i = 0; i < libs.length; i++) { + update("lib", libs[i], libs[i], false); + } + + return true; + } + + /** read eclipse .classpath file XXX line-oriented hack */ + private boolean initClasspath() { + // meaning testsrc directory, junit library, etc. + File file = new File(moduleDir, ".classpath"); // XXXFileLiteral + if (!file.exists()) { + return false; // OSGI??? + } + FileReader fin = null; + try { + fin = new FileReader(file); + BufferedReader reader = new BufferedReader(fin); + String line; + XMLItem item = new XMLItem("classpathentry", new ICB()); + while (null != (line = reader.readLine())) { + line = line.trim(); + // dumb - only handle comment-only lines + if (!line.startsWith("\"="; + StringTokenizer st = new StringTokenizer(line, DELIM, true); + ArrayList result = new ArrayList(); + StringBuffer quote = new StringBuffer(); + boolean inQuote = false; + while (st.hasMoreTokens()) { + String s = st.nextToken(); + if ((1 == s.length()) && (-1 != DELIM.indexOf(s))) { + if ("\"".equals(s)) { // end quote (or escaped) + if (inQuote) { + inQuote = false; + quote.append("\""); + result.add(quote.toString()); + quote.setLength(0); + } else { + quote.append("\""); + inQuote = true; + } + } else { + result.add(s); + } + } else { // not a delimiter + if (inQuote) { + quote.append(s); + } else { + result.add(s); + } + } + } + return (String[]) result.toArray(new String[0]); + } + + public void acceptLine(String line) { + String[] tokens = tokenize(line); + for (int i = 0; i < tokens.length; i++) { + next(tokens[i]); + } + } + + private Properties attributesToProperties() { + Properties result = new Properties(); + for (int i = 0; i < attributes.length; i++) { + String a = attributes[i]; + if (null != a) { + result.setProperty(ATTS[i], a); + } + } + return result; + } + + void errorIfNotNull(String name, String value) { + if (null != value) { + error("Did not expect " + name + ": " + value); + } + } + + void errorIfNull(String name, String value) { + if (null == value) { + error("expected value for " + name); + } + } + + boolean activeEntity() { + return targetEntity.equals(entityName); + } + + /** + * Assumes that comments and "".equals(s)) { + errorIfNull("entityName", entityName); + if ("/".equals(attributeName)) { + attributeName = null; + } else { + errorIfNotNull("attributeName", attributeName); + } + if (activeEntity()) { + callback.end(attributesToProperties()); + } + entityName = null; + } else if ("=".equals(s)) { + errorIfNull("entityName", entityName); + errorIfNull("attributeName", attributeName); + } else if (s.startsWith("\"")) { + errorIfNull("entityName", entityName); + errorIfNull("attributeName", attributeName); + writeAttribute(attributeName, s); + attributeName = null; + } else { + if (null == entityName) { + reset(); + entityName = s; + } else if (null == attributeName) { + attributeName = s; + } else { + System.out + .println("unknown state - not value, attribute, or entity: " + + s); + } + } + } + + void readAttribute(String s) { + for (int i = 0; i < ATTS.length; i++) { + if (s.equals(ATTS[i])) { + attributes[i] = ATT_STARTED; + break; + } + } + } + + void writeAttribute(String name, String value) { + for (int i = 0; i < ATTS.length; i++) { + if (name.equals(ATTS[i])) { + if (!value.startsWith("\"") || !value.endsWith("\"")) { + error("bad attribute value: " + value); + } + value = value.substring(1, value.length() - 1); + attributes[i] = value; + return; + } + } + } + + void error(String s) { + throw new Error(s + " at input " + input); + } + } +} diff --git a/build/src/main/java./aspectj/internal/tools/build/Modules.java b/build/src/main/java./aspectj/internal/tools/build/Modules.java new file mode 100644 index 000000000..83686820e --- /dev/null +++ b/build/src/main/java./aspectj/internal/tools/build/Modules.java @@ -0,0 +1,66 @@ +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + + +package org.aspectj.internal.tools.build; + +import java.io.File; +import java.util.Hashtable; + +/** + * Registration and factory for modules + * @see Module + * @see Builder + */ +public class Modules { + + private final Hashtable modules = new Hashtable(); + public final File baseDir; + public final File jarDir; + private final Messager handler; + + public Modules(File baseDir, File jarDir, Messager handler) { + this.baseDir = baseDir; + this.jarDir = jarDir; + this.handler = handler; + Util.iaxIfNotCanReadDir(baseDir, "baseDir"); + Util.iaxIfNotCanReadDir(jarDir, "jarDir"); + Util.iaxIfNull(handler, "handler"); + } + + + /** + * Get module associated with name. + * @return fail if unable to find or create module {name}. + */ + public Module getModule(String name) { + if (null == name) { + return null; + } + Module result = (Module) modules.get(name); + if (null == result) { + File moduleDir = new File(baseDir, name); + if (!Util.canReadDir(moduleDir)) { + handler.error("not a module: " + name); + } else { + result = new Module(moduleDir, jarDir, name, this, handler); + if (result.valid) { + modules.put(name, result); + } else { + handler.error("invalid module: " + result.toLongString()); + } + } + } + return result; + } +} \ No newline at end of file diff --git a/build/src/main/java./aspectj/internal/tools/build/ProductModule.java b/build/src/main/java./aspectj/internal/tools/build/ProductModule.java new file mode 100644 index 000000000..c695a4f8e --- /dev/null +++ b/build/src/main/java./aspectj/internal/tools/build/ProductModule.java @@ -0,0 +1,70 @@ +/* ******************************************************************* + * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ +package org.aspectj.internal.tools.build; + +import java.io.File; + +/** + * Struct associating module with target product distribution jar + * and assembly instructions. + * When building product distributions, a zero-length jar file + * in the dist directory may signify a module to be built, + * renamed, and included in the distribution. + */ +public class ProductModule { + /** name of distribution directory in product directory */ + private static final String DIST = "dist"; + + /** top-level product directory being produced */ + public final File productDir; + + /** path to file in distribution template dir for this module jar */ + public final File replaceFile; + + /** relative path within distribution of this product module jar */ + public final String relativePath; + + /** the module jar is the file to replace */ + public final Module module; + + /** if true, assemble all when building module */ + public final boolean assembleAll; + + public ProductModule(File productDir, File replaceFile, Module module, boolean assembleAll) { + this.replaceFile = replaceFile; + this.module = module; + this.productDir = productDir; + this.assembleAll = assembleAll; + Util.iaxIfNull(module, "module"); + Util.iaxIfNotCanReadDir(productDir, "productDir"); + Util.iaxIfNotCanReadFile(replaceFile, "replaceFile"); + String productDirPath = productDir.getAbsolutePath(); + String replaceFilePath = replaceFile.getAbsolutePath(); + if (!replaceFilePath.startsWith(productDirPath)) { + String m = "\"" + replaceFilePath + + "\" does not start with \"" + + productDirPath + + "\""; + throw new IllegalArgumentException(m); + } + replaceFilePath = replaceFilePath.substring(1+productDirPath.length()); + if (!replaceFilePath.startsWith(DIST)) { + String m = "\"" + replaceFilePath + + "\" does not start with \"" + DIST + "\""; + throw new IllegalArgumentException(m); + } + relativePath = replaceFilePath.substring(1 + DIST.length()); + } + public String toString() { + return "" + module + " for " + productDir; + } +} diff --git a/build/src/main/java./aspectj/internal/tools/build/Result.java b/build/src/main/java./aspectj/internal/tools/build/Result.java new file mode 100644 index 000000000..e12ba4e29 --- /dev/null +++ b/build/src/main/java./aspectj/internal/tools/build/Result.java @@ -0,0 +1,387 @@ +/* ******************************************************************* + * Copyright (c) 2005 Contributors. + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://eclipse.org/legal/epl-v10.html + * + * Contributors: + * Wes Isberg initial implementation + * ******************************************************************/ + +package org.aspectj.internal.tools.build; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; + +/** + * Represents a prospective build result and any requirements for it. Used for + * [testing|normal][jar|assembled-jar|classesDir?]. + */ +public class Result { + public static final boolean NORMAL = true; + + public static final boolean ASSEMBLE = true; + + static final Kind RELEASE = new Kind("RELEASE", NORMAL, !ASSEMBLE); + + static final Kind RELEASE_ALL = new Kind("RELEASE_ALL", NORMAL, ASSEMBLE); + + static final Kind TEST = new Kind("TEST", !NORMAL, !ASSEMBLE); + + static final Kind TEST_ALL = new Kind("TEST_ALL", !NORMAL, ASSEMBLE); + + private static final Kind[] KINDS = { RELEASE, TEST, RELEASE_ALL, TEST_ALL }; + + private static final HashMap nameToResult = new HashMap(); + + public static boolean isTestingJar(String name) { + name = name.toLowerCase(); + return "junit.jar".equals(name); + } + + public static boolean isTestingDir(String name) { + name = name.toLowerCase(); + return (Util.Constants.TESTSRC.equals(name) || Util.Constants.JAVA5_TESTSRC + .equals(name)); + } + + public static boolean isTestingModule(Module module) { + String name = module.name.toLowerCase(); + return name.startsWith("testing") || "tests".equals(name); + } + + public static synchronized Result getResult(String name) { + if (null == name) { + throw new IllegalArgumentException("null name"); + } + return (Result) nameToResult.get(name); + } + + public static Result[] getResults(String[] names) { + if (null == names) { + return new Result[0]; + } + Result[] results = new Result[names.length]; + + for (int i = 0; i < results.length; i++) { + String name = names[i]; + if (null == name) { + String m = "no name at " + i + ": " + Arrays.asList(names); + throw new IllegalArgumentException(m); + } + Result r = Result.getResult(name); + if (null == r) { + String m = "no result [" + i + "]: " + name + ": " + + Arrays.asList(names); + throw new IllegalArgumentException(m); + } + results[i] = r; + } + return results; + + } + + public static Kind[] KINDS() { + Kind[] result = new Kind[KINDS.length]; + System.arraycopy(KINDS, 0, result, 0, result.length); + return result; + } + + public static void iaxUnlessNormal(Result result) { + if ((null == result) || !result.getKind().normal) { + throw new IllegalArgumentException("not normal: " + result); + } + } + + public static void iaxUnlessAssembly(Result result) { + if ((null == result) || !result.getKind().assemble) { + throw new IllegalArgumentException("not assembly: " + result); + } + } + + public static Kind kind(boolean normal, boolean assemble) { + return (normal == NORMAL ? (assemble == ASSEMBLE ? RELEASE_ALL + : RELEASE) : (assemble == ASSEMBLE ? TEST_ALL : TEST)); + } + + public static class Kind { + final String name; + + final boolean normal; + + final boolean assemble; + + private Kind(String name, boolean normal, boolean assemble) { + this.name = name; + this.normal = normal; + this.assemble = assemble; + } + + public final boolean isAssembly() { + return assemble; + } + + public final boolean isNormal() { + return normal; + } + + public final String toString() { + return name; + } + } + + /** path to output jar - may not exist */ + private final File outputFile; + + /** List of required Result */ + private final List requiredResults; + + /** List of library jars */ + private final List libJars; + + /** List of classpath variables */ + private final List classpathVariables; + + transient String toLongString; + + /** + * List of library jars exported to clients (duplicates some libJars + * entries) + */ + private final List exportedLibJars; + + /** List of source directories */ + private final List srcDirs; + + /** true if this has calculated List fields. */ + private boolean requiredDone; + + /** true if this has been found to be out of date */ + private boolean outOfDate; + + /** true if we have calculated whether this is out of date */ + private boolean outOfDateSet; + + private final Kind kind; + + private final Module module; + + private final String name; + + Result(Kind kind, Module module, File jarDir) { + this.kind = kind; + this.module = module; + this.libJars = new ArrayList(); + this.exportedLibJars = new ArrayList(); + this.srcDirs = new ArrayList(); + this.classpathVariables = new ArrayList(); + this.requiredResults = new ArrayList(); + String name = module.name; + if (!kind.normal) { + name += "-test"; + } + if (kind.assemble) { + name += "-all"; + } + this.name = name; + this.outputFile = new File(jarDir, name + ".jar"); + nameToResult.put(name, this); + } + + public String getName() { + return name; + } + + public File getOutputFile() { + return outputFile; + } + + public void clearOutOfDate() { + outOfDateSet = false; + outOfDate = false; + } + + public boolean outOfDate() { + if (!outOfDateSet) { + outOfDate = Module.outOfDate(this); + outOfDateSet = true; + } + return outOfDate; + } + + /** @return List (File) of jar's required */ + public List findJarRequirements() { + ArrayList result = new ArrayList(); + Module.doFindJarRequirements(this, result); + return result; + } + + /** @return unmodifiable List of String classpath variables */ + public List getClasspathVariables() { + return safeList(classpathVariables); + } + + // + /** @return unmodifiable List of required modules String names */ + public Result[] getRequired() { + return safeResults(requiredResults); + } + + /** + * @return unmodifiable list of exported library files, guaranteed readable + */ + public List getExportedLibJars() { + return safeList(exportedLibJars); + } + + /** + * @return unmodifiable list of required library files, guaranteed readable + */ + public List getLibJars() { + requiredDone(); + return safeList(libJars); + } + + /** + * @return unmodifiable list of required library files, guaranteed readable + */ + // public List getMerges() { + // requiredDone(); + // return safeList(merges); + // } + /** @return unmodifiable list of source directories, guaranteed readable */ + public List getSrcDirs() { + return safeList(srcDirs); + } + + public Module getModule() { + return module; + } + + public Kind getKind() { + return kind; + } + + public String toLongString() { + if (null == toLongString) { + toLongString = name + "[outputFile=" + outputFile + + ", requiredResults=" + requiredResults + ", srcDirs=" + + srcDirs + ", libJars=" + libJars + "]"; + } + return toLongString; + } + + public String toString() { + return name; + } + + private List safeList(List l) { + requiredDone(); + return Collections.unmodifiableList(l); + } + + private Result[] safeResults(List list) { + requiredDone(); + if (null == list) { + return new Result[0]; + } + return (Result[]) list.toArray(new Result[0]); + } + + private void initSrcDirs() { + srcDirs.addAll(getModule().srcDirs(this)); + if (getKind().normal) { + // trim testing source directories + for (ListIterator iter = srcDirs.listIterator(); iter.hasNext();) { + File srcDir = iter.next(); + if (isTestingDir(srcDir.getName())) { + iter.remove(); + } + } + } + } + + private void initLibJars() { + libJars.addAll(getModule().libJars(this)); + if (getKind().normal && !isTestingModule(getModule())) { + // trim testing libraries + for (ListIterator iter = libJars.listIterator(); iter.hasNext();) { + File libJar = iter.next(); + if (isTestingJar(libJar.getName())) { + iter.remove(); + } + } + } + } + + private void assertKind(Kind kind) { + if (kind != getKind()) { + throw new IllegalArgumentException("expected " + getKind() + + " got " + kind); + } + } + + private void initRequiredResults() { + final Module module = getModule(); + final Kind kind = getKind(); + if (kind.assemble) { + if (kind.normal) { + assertKind(RELEASE_ALL); + requiredResults.add(module.getResult(RELEASE)); + } else { + assertKind(TEST_ALL); + requiredResults.add(module.getResult(TEST)); + requiredResults.add(module.getResult(RELEASE)); + } + } else if (!kind.normal) { + assertKind(TEST); + requiredResults.add(module.getResult(RELEASE)); + } else { + assertKind(RELEASE); + } + // externally-required: + List modules = module.requiredModules(this); + final boolean adoptTests = !kind.normal || isTestingModule(module); + for (Module required: modules) { + if (adoptTests) { + // testing builds can rely on other release and test results + requiredResults.add(required.getResult(TEST)); + requiredResults.add(required.getResult(RELEASE)); + } else if (!isTestingModule(required)){ + // release builds can only rely on non-testing results + // from non-testing modules + requiredResults.add(required.getResult(RELEASE)); + } // else skip release dependencies on testing-* (testing-util) + } + } + + private void initClasspathVariables() { + // no difference + classpathVariables.addAll(getModule().classpathVariables(this)); + } + + private void initExportedLibJars() { + // no difference + exportedLibJars.addAll(getModule().exportedLibJars(this)); + } + + private synchronized void requiredDone() { + if (!requiredDone) { + initSrcDirs(); + initLibJars(); + initRequiredResults(); + initClasspathVariables(); + initExportedLibJars(); + requiredDone = true; + } + } + +} diff --git a/build/src/main/java./aspectj/internal/tools/build/SampleGatherer.java b/build/src/main/java./aspectj/internal/tools/build/SampleGatherer.java new file mode 100644 index 000000000..0b023e6c5 --- /dev/null +++ b/build/src/main/java./aspectj/internal/tools/build/SampleGatherer.java @@ -0,0 +1,1049 @@ +/* ******************************************************************* + * Copyright (c) 2003 Contributors. + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Wes Isberg initial implementation + * ******************************************************************/ + +/* + * A quickie hack to extract sample code from testable sources. + * This could reuse a lot of code from elsewhere, + * but currently doesn't, + * to keep it in the build module which avoids dependencies. + * (Too bad we can't use scripting languages...) + */ +package org.aspectj.internal.tools.build; + +import java.io.*; +import java.text.DateFormat; +import java.util.*; + +/** + * This gathers sample code delimited with [START..END]-SAMPLE + * from source files under a base directory, + * along with any @author info. + *
    // START-SAMPLE {anchorName} {anchorText}
    + *    ... sample code ...
    + *   // END-SAMPLE {anchorName}
    + *   
    + * where {anchorName} need not be unique and might be + * hierarchical wrt "-", e.g., "genus-species-individual". + */ +public class SampleGatherer { + + /** EOL String for gathered lines */ + public static final String EOL = "\n"; // XXX + + static final String START = "START-SAMPLE"; + static final String END = "END-SAMPLE"; + static final String AUTHOR = "@author"; + static final String FLAG = "XXX"; + +// private static void test(String[] args){ +// String[] from = new String[] { "
    ", "
    " }; +// String[] to = new String[] { "<pre>", "</pre>" }; +// String source = "in this
     day and 
    age of
    ";
    +//        System.err.println("from " + source);
    +//        System.err.println("  to " + SampleUtil.replace(source, from, to));
    +//        source = "
     day and 
    "; +// System.err.println("from " + source); +// System.err.println(" to " + SampleUtil.replace(source, from, to)); +// source = "
     0) && (start < line.length())) {
    +            line = line.substring(start);
    +        }
    +        line = line.trim();
    +        if (line.endsWith("*/")) {
    +            line = line.substring(0, line.length()-2).trim();
    +        } else if (line.endsWith("-->")) {
    +            line = line.substring(0, line.length()-3).trim();
    +        }
    +        return line;
    +    }
    +        
    +    private static void doGather(File source, Samples sink) 
    +            throws IOException {
    +        if (source.isFile()) {
    +            if (isSource(source)) {
    +                gatherFromFile(source, sink);
    +            }
    +        } else if (source.isDirectory() && source.canRead()) {
    +            File[] files = source.listFiles();
    +            for (int i = 0; i < files.length; i++) {
    +                doGather(files[i], sink);
    +            }
    +        }
    +    }
    +
    +    private static boolean isSource(File file) {
    +        if ((null == file) || !file.isFile() || !file.canRead()) {
    +            return false;
    +        }
    +        String path = file.getName().toLowerCase();
    +        String[] suffixes = Sample.Kind.SOURCE_SUFFIXES;
    +        for (int i = 0; i < suffixes.length; i++) {
    +            if (path.endsWith(suffixes[i])) {
    +                return true;
    +            }
    +        }
    +        return false;
    +    }
    +    
    +    private static void gatherFromFile(final File source, final Samples sink) 
    +            throws IOException {
    +        Reader reader = null;
    +        try {
    +            String author = null;
    +            StringBuffer sampleCode = new StringBuffer();
    +            String anchorName = null;
    +            String anchorTitle = null;
    +            ArrayList flags = new ArrayList();
    +            int startLine = -1; // seeking
    +            int endLine = Integer.MAX_VALUE; // not seeking
    +            reader = new FileReader(source);
    +            LineNumberReader lineReader = new LineNumberReader(reader);
    +            String line;
    +
    +            while (null != (line = lineReader.readLine())) { // XXX naive
    +                // found start?
    +                int loc = line.indexOf(START);
    +                if (-1 != loc) {
    +                    int lineNumber = lineReader.getLineNumber();
    +                    if (-1 != startLine) {
    +                        abort("unexpected " + START, source, line, lineNumber);
    +                    }
    +                    startLine = lineNumber;
    +                    endLine = -1;
    +                    anchorName = trimCommentEnd(line, loc + START.length());
    +                    loc = anchorName.indexOf(" ");
    +                    if (-1 == loc) {
    +                        anchorTitle = null;
    +                    } else {
    +                        anchorTitle = anchorName.substring(1+loc).trim();
    +                        anchorName = anchorName.substring(0, loc);
    +                    }
    +                    continue;
    +                } 
    +
    +                // found end?
    +                loc = line.indexOf(END);
    +                if (-1 != loc) {
    +                    int lineNumber = lineReader.getLineNumber();
    +                    if (Integer.MAX_VALUE == endLine) {
    +                        abort("unexpected " + END, source, line, lineNumber);
    +                    }
    +                    String newtag = trimCommentEnd(line, loc + END.length());
    +                    if ((newtag.length() > 0) && !newtag.equals(anchorName)) {
    +                        String m = "expected " + anchorName
    +                            + " got " + newtag;
    +                        abort(m, source, line, lineNumber);
    +                    }
    +                    endLine = lineNumber;
    +                    Sample sample = new Sample(anchorName,
    +                            anchorTitle,
    +                            author, 
    +                            sampleCode.toString(), 
    +                            source, 
    +                            startLine, 
    +                            endLine,
    +                            (String[]) flags.toArray(new String[flags.size()]));
    +                    sink.addSample(sample);
    +
    +                    // back to seeking start
    +                    sampleCode.setLength(0);
    +                    startLine = -1;
    +                    endLine = Integer.MAX_VALUE;
    +                    continue;
    +                } 
    +
    +                // found author?
    +                loc = line.indexOf(AUTHOR);
    +                if (-1 != loc) {
    +                    author = trimCommentEnd(line, loc + AUTHOR.length());
    +                }
    +                // found flag comment?
    +                loc = line.indexOf(FLAG);
    +                if (-1 != loc) {
    +                    flags.add(trimCommentEnd(line, loc + FLAG.length()));
    +                }
    +                
    +                // reading?
    +                if ((-1 != startLine) && (-1 == endLine)) {
    +                    sampleCode.append(line);
    +                    sampleCode.append(EOL);
    +                }
    +            }
    +            if (-1 == endLine) {
    +                abort("incomplete sample", source, "", lineReader.getLineNumber());
    +            }
    +        } finally {
    +            if (null != reader) {
    +                reader.close();
    +            }
    +        }
    +    }
    +    private static void abort(String why, File file, String line, int lineNumber)
    +            throws Abort {
    +        throw new Abort(why + " at " + file + ":" + lineNumber + ": " + line);
    +    }
    +//    private static void delay(Object toDelay) {
    +//        synchronized (toDelay) { // XXX sleep instead?
    +//            toDelay.notifyAll();
    +//        }
    +//    }
    +    static class Abort extends IOException {
    +        private static final long serialVersionUID = -1l;
    +        Abort(String s) {
    +            super(s);
    +        }
    +    }
    +}
    +
    +/**
    + * Data associated with sample code - struct class.
    + */
    +class Sample {
    +    public static final String ASPECTJ_TEAM = "The AspectJ Team";
    +
    +    /** sort by anchorName, file path, and start/end location */
    +    static Comparator NAME_SOURCE_COMPARER = new Comparator() {
    +        public int compare(Sample left, Sample right) {
    +            if (null == left) {
    +                return (null == right ? 0 : -1);
    +            } 
    +            if (null == right) {
    +                return 1;
    +            } 
    +            int result = left.anchorName.compareTo(right.anchorName);
    +            if (0 != result) {
    +                return result;                
    +            }
    +            result = left.sourcePath.compareTo(right.sourcePath);
    +            if (0 != result) {
    +                return result;                
    +            }
    +            result = right.startLine - left.startLine;
    +            if (0 != result) {
    +                return result;                
    +            }
    +            return right.endLine - left.endLine;
    +        }
    +    };
    +
    +    /** sort by author, then NAME_SOURCE_COMPARER */
    +    static Comparator AUTHOR_NAME_SOURCE_COMPARER = new Comparator() {
    +        public int compare(Sample left, Sample right) {
    +            if (null == left) {
    +                return (null == right ? 0 : -1);
    +            } 
    +            if (null == right) {
    +                return 1;
    +            } 
    +            int result = left.author.compareTo(right.author);
    +            if (0 != result) {
    +                return result;                
    +            }
    +            return NAME_SOURCE_COMPARER.compare(left,right);
    +        }
    +    };
    +    
    +    final String anchorName;
    +    final String anchorTitle;
    +    final String author;
    +    final String sampleCode;
    +    final File sourcePath;
    +    final int startLine;
    +    final int endLine;
    +    final Kind kind;
    +    /** List of String flags found in the sample */
    +    final List flags;
    +    public Sample(
    +        String anchorName,
    +        String anchorTitle,
    +        String author,
    +        String sampleCode,
    +        File sourcePath,
    +        int startLine,
    +        int endLine,
    +        String[] flags) {
    +        this.anchorName = anchorName;
    +        this.anchorTitle = anchorTitle;
    +        this.author = (null != author ? author : ASPECTJ_TEAM);
    +        this.sampleCode = sampleCode;
    +        this.sourcePath = sourcePath;
    +        this.startLine = startLine;
    +        this.endLine = endLine;
    +        this.kind = Kind.getKind(sourcePath);
    +//        List theFlags;
    +        if ((null == flags) || (0 == flags.length)) {
    +            this.flags = Collections.EMPTY_LIST;
    +        } else {
    +            this.flags = Collections.unmodifiableList(Arrays.asList(flags));
    +        }
    +    }
    +
    +    public String toString() {
    +        return sampleCode;
    +    }
    +
    +    public static class Kind {
    +        
    +        /** lowercase source suffixes identify files to gather samples from */
    +        public static final String[] SOURCE_SUFFIXES = new String[]
    +        { ".java", ".aj", ".sh", ".ksh", 
    +        ".txt", ".text", ".html", ".htm", ".xml" };
    +        static final Kind XML = new Kind();
    +        static final Kind HTML = new Kind();
    +        static final Kind PROGRAM = new Kind();
    +        static final Kind SCRIPT = new Kind();
    +        static final Kind TEXT = new Kind();
    +        static final Kind OTHER = new Kind();
    +        public static Kind getKind(File file) {
    +            if (null == file) {
    +                return OTHER;
    +            }
    +            String name = file.getName().toLowerCase();
    +            if ((name.endsWith(".java") || name.endsWith(".aj"))) {
    +                return PROGRAM;
    +            }
    +            if ((name.endsWith(".html") || name.endsWith(".htm"))) {
    +                return HTML;
    +            }
    +            if ((name.endsWith(".sh") || name.endsWith(".ksh"))) {
    +                return SCRIPT;
    +            }
    +            if ((name.endsWith(".txt") || name.endsWith(".text"))) {
    +                return TEXT;
    +            }
    +            if (name.endsWith(".xml")) {
    +                return XML;
    +            }
    +            return OTHER;
    +        }
    +        private Kind() {
    +        }
    +    }
    +}
    +
    +/**
    + * type-safe Collection of samples.
    + */
    +class Samples {
    +    private ArrayList samples = new ArrayList();
    +    int size() {
    +        return samples.size();
    +    }
    +    void addSample(Sample sample) {
    +        samples.add(sample);
    +    }
    +    /**
    +     * @return List copy, sorted by Sample.NAME_SOURCE_COMPARER
    +     */
    +    List getSortedSamples() {
    +        return getSortedSamples(Sample.NAME_SOURCE_COMPARER);
    +    }
    +    
    +    List getSortedSamples(Comparator comparer) {
    +        ArrayList result = new ArrayList();
    +        result.addAll(samples);
    +        Collections.sort(result, comparer);
    +        return result;
    +    }
    +}
    +
    +
    +/**
    + * Render samples by using method visitors.
    + */
    +class SamplesRenderer {
    +    public static SamplesRenderer ME = new SamplesRenderer();
    +    protected SamplesRenderer() {        
    +    }
    +    public static final String EOL = "\n"; // XXX
    +    public static final String INFO = 
    +      "

    This contains contributions from the AspectJ community of " + + "

    • sample code for AspectJ programs,
    • " + + "
    • sample code for extensions to AspectJ tools using the public API's,
    • " + + "
    • sample scripts for invoking AspectJ tools, and
    • " + + "
    • documentation trails showing how to do given tasks" + + " using AspectJ, AJDT, or various IDE or deployment" + + " environments.

    " + + "

    Find complete source files in the AspectJ CVS repository at " + + "org.aspectj/modules/docs/sandbox. " + + "For instructions on downloading code from the CVS repository, " + + "see the FAQ entry " + + "\"buildingsource\".

    "; + + public static final String COPYRIGHT = + "

    Copyright 2003 Contributors. All Rights Reserved. " + + "This sample code is made available under the Common Public " + "License version 1.0 available at " + + "" + + "http://www.eclipse.org/legal/epl-v10.html." + + "Contributors are listed in this document as authors. " + + "Permission to republish portions of this sample code " + + "is hereby granted if the publication acknowledges " + + "the author by name and " + + "the source by reference to the AspectJ project home page " + + " at http://eclipse.org/aspectj.

    " + + EOL; + + /** template algorithm to render */ + public final StringBuffer render(Samples samples, StringBuffer sink) { + if (null == sink) { + sink = new StringBuffer(); + } + if ((null == samples) || (0 == samples.size())) { + return sink; + } + startList(samples, sink); + List list = samples.getSortedSamples(); + String anchorName = null; + for (ListIterator iter = list.listIterator(); + iter.hasNext();) { + Sample sample = (Sample) iter.next(); + String newAnchorName = sample.anchorName; + if ((null == anchorName) + || (!anchorName.equals(newAnchorName))) { + endAnchorName(anchorName, sink); + startAnchorName(newAnchorName, sample.anchorTitle, sink); + anchorName = newAnchorName; + } + render(sample, sink); + } + endAnchorName(anchorName, sink); + endList(samples, sink); + return sink; + } + protected void startList(Samples samples, StringBuffer sink) { + sink.append("Printing " + samples.size() + " samples"); + sink.append(EOL); + } + + protected void startAnchorName(String name, String title, StringBuffer sink) { + sink.append("anchor " + name); + sink.append(EOL); + } + + protected void render(Sample sample, StringBuffer sink) { + SampleUtil.render(sample, "=", ", ",sink); + sink.setLength(sink.length()-2); + sink.append(EOL); + } + + /** + * @param name the String name being ended - ignore if null + * @param sink + */ + protected void endAnchorName(String name, StringBuffer sink) { + if (null == name) { + return; + } + } + + protected void endList(Samples samples, StringBuffer sink) { + sink.append("Printed " + samples.size() + " samples"); + sink.append(EOL); + } + +} + +// XXX need DocBookSamplesRenderer + +/** + * Output the samples as a single HTML file, with a table of contents + * and sorting the samples by their anchor tags. + */ +class HTMLSamplesRenderer extends SamplesRenderer { + public static SamplesRenderer ME = new HTMLSamplesRenderer(); + // XXX move these + public static boolean doHierarchical = true; + public static boolean doFlags = false; + + + final StringBuffer tableOfContents; + final StringBuffer sampleSection; + String[] lastAnchor = new String[0]; + String currentAnchor; + String currentAuthor; + + protected HTMLSamplesRenderer() { + sampleSection = new StringBuffer(); + tableOfContents = new StringBuffer(); + } + + protected void startAnchorName(String name, String title, StringBuffer sink) { + if (doHierarchical) { + doContentTree(name); + } + // ---- now do anchor + tableOfContents.append("
  5. " + title + "
  6. "); + tableOfContents.append(EOL); + currentAnchor = name; + } + + protected void startList(Samples samples, StringBuffer sink) { + } + + protected void render(Sample sample, StringBuffer sink) { + if (null != currentAnchor) { + if (!currentAnchor.equals(sample.anchorName)) { + String m = "expected " + currentAnchor + + " got " + sample.anchorName; + throw new Error(m); + } + currentAnchor = null; + } + + // do heading then code + renderHeading(sample.anchorName, sample.anchorTitle, sampleSection); + if (sample.kind == Sample.Kind.HTML) { + renderHTML(sample); + } else if (sample.kind == Sample.Kind.XML) { + renderXML(sample); + } else { + renderPre(sample); + } + } + + protected boolean doRenderAuthor(Sample sample) { + return (null != sample.author); + // && !sample.author.equals(currentAuthor) + } + + protected void renderStandardHeader(Sample sample) { + // XXX starting same as pre + if (doRenderAuthor(sample)) { + currentAuthor = sample.author; + sampleSection.append("

    |   " + currentAuthor); + sampleSection.append(EOL); + } + sampleSection.append("  |  "); + sampleSection.append(SampleUtil.renderCodePath(sample.sourcePath)); + sampleSection.append(":" + sample.startLine); + sampleSection.append("  |"); + sampleSection.append(EOL); + sampleSection.append("

    "); + sampleSection.append(EOL); + if (doFlags) { + boolean flagHeaderDone = false; + for (Iterator iter = sample.flags.iterator(); iter.hasNext();) { + String flag = (String) iter.next(); + if (!flagHeaderDone) { + sampleSection.append("

    Comments flagged:

      "); + sampleSection.append(EOL); + flagHeaderDone = true; + } + sampleSection.append("
    • "); + sampleSection.append(flag); + sampleSection.append("
    • "); + } + if (flagHeaderDone) { + sampleSection.append("
    "); + sampleSection.append(EOL); + } + } + } + + protected void renderXML(Sample sample) { + renderStandardHeader(sample); + sampleSection.append("
    ");
    +        sampleSection.append(EOL);
    +        sampleSection.append(prepareXMLSample(sample.sampleCode));
    +        sampleSection.append(EOL);
    +        sampleSection.append("    
    "); + sampleSection.append(EOL); + } + + protected void renderHTML(Sample sample) { + renderStandardHeader(sample); + sampleSection.append(EOL); + sampleSection.append(prepareHTMLSample(sample.sampleCode)); + sampleSection.append(EOL); + } + + protected void renderPre(Sample sample) { + renderStandardHeader(sample); + sampleSection.append("
    ");
    +        sampleSection.append(EOL);
    +        sampleSection.append(prepareCodeSample(sample.sampleCode));
    +        sampleSection.append("    
    "); + sampleSection.append(EOL); + } + + protected void endAnchorName(String name, StringBuffer sink) { + if (null == name) { + return; + } + currentAnchor = null; + currentAuthor = null; // authors don't span anchors + } + + protected void endList(Samples samples, StringBuffer sink) { + sink.append(""); + sink.append(EOL); + sink.append("AspectJ sample code"); + sink.append(EOL); + sink.append(""); + sink.append(EOL); + sink.append(" "); + sink.append(EOL); + sink.append("

    AspectJ sample code

    "); + sink.append(INFO); + sink.append(EOL); + sink.append(COPYRIGHT); + sink.append(EOL); + sink.append("

    Generated on "); + sink.append(DateFormat.getDateInstance().format(new Date())); + sink.append(" by SamplesGatherer"); + sink.append(EOL); + sink.append("

    Contents

    "); + sink.append(EOL); + sink.append("
      "); + sink.append(EOL); + sink.append(tableOfContents.toString()); + // unwind to common prefix, if necessary + for (int i = 0; i < lastAnchor.length ; i++) { + sink.append("
    "); + } + + sink.append("
  7. Author Index
  8. "); + sink.append(" "); + sink.append("

    Listings

    "); + sink.append(EOL); + sink.append(sampleSection.toString()); + renderAuthorIndex(samples, sink); + sink.append(""); + sink.append(EOL); + } + + protected String prepareXMLSample(String sampleCode) { + String[] from = new String[] {"\t", "<"}; + String[] to = new String[] {" ", "<"}; + return (SampleUtil.replace(sampleCode, from, to)); + } + + protected String prepareHTMLSample(String sampleCode) { + String[] from = new String[20]; + String[] to = new String[20]; + for (int i = 0; i < to.length; i++) { + String h = "h" + i + ">"; + from[i] = "<" + h; + to[i] = "

    "; + from[++i] = "

    "; + } + return (SampleUtil.replace(sampleCode, from, to)); + } + + protected String prepareCodeSample(String sampleCode) { + String[] from = new String[] { "

    ", "
    " }; + String[] to = new String[] { "<pre>", "</pre>" }; + return (SampleUtil.replace(sampleCode, from, to)); + } + + protected void renderHeading(String anchor, String title, StringBuffer sink) { + sink.append(" "); + sink.append(EOL); + if ((null == title) || (0 == title.length())) { + title = anchor; + } + sink.append("

    " + title + "

    "); + sink.append(EOL); + sink.append("back to top"); + sink.append(EOL); + } + + /** + * Manage headings in both table of contents and listings. + * @param name the String anchor + */ + protected void doContentTree(String name) { + if (name.equals(lastAnchor)) { + return; + } + // ---- handle trees + String[] parts = SampleUtil.splitAnchorName(name); + //String[] lastAnchor = (String[]) lastAnchors.peek(); + int firstDiff = SampleUtil.commonPrefix(parts, lastAnchor); + // unwind to common prefix, if necessary + if (firstDiff+1 < lastAnchor.length) { + for (int i = 1; i < lastAnchor.length-firstDiff ; i++) { + tableOfContents.append(" "); + tableOfContents.append(EOL); + } + } + // build up prefix + StringBuffer branchAnchor = new StringBuffer(); + for (int i = 0; i < firstDiff;) { + branchAnchor.append(parts[i]); + i++; + branchAnchor.append("-"); + } + // emit leading headers, but not anchor itself + for (int i = firstDiff; i < (parts.length-1); i++) { + branchAnchor.append(parts[i]); + String prefixName = branchAnchor.toString(); + branchAnchor.append("-"); + tableOfContents.append("
  9. " + prefixName + "
  10. "); + tableOfContents.append(EOL); + tableOfContents.append("
      "); + tableOfContents.append(EOL); + + renderHeading(prefixName, prefixName, sampleSection); + } + lastAnchor = parts; + } + + protected void renderAuthorIndex(Samples samples, StringBuffer sink) { + sink.append("

      Author Index

      "); + List list = samples.getSortedSamples(Sample.AUTHOR_NAME_SOURCE_COMPARER); + String lastAuthor = null; + for (ListIterator iter = list.listIterator(); iter.hasNext();) { + Sample sample = (Sample)iter.next(); + String author = sample.author; + if (!author.equals(lastAuthor)) { + if (null != lastAuthor) { + sink.append("
    "); + } + sink.append("
  11. "); + sink.append(author); + sink.append(EOL); + sink.append("
      "); + sink.append(EOL); + lastAuthor = author; + } + sink.append("
    • "); + if (null == sample.anchorTitle) { + sink.append(sample.anchorName); + } else { + sink.append(sample.anchorTitle); + } + sink.append("
    • "); + } + } +} + +class SampleUtil { + public static final String SAMPLE_BASE_DIR_NAME = "sandbox"; + + public static void simpleRender(Samples result, StringBuffer sink) { + List sortedSamples = result.getSortedSamples(); + int i = 0; + for (ListIterator iter = sortedSamples.listIterator(); + iter.hasNext();) { + Sample sample = (Sample) iter.next(); + sink.append(i++ + ": " + sample); + } + } + + /** result struct for getPackagePath */ + static class JavaFile { + /** input File possibly signifying a java file */ + final File path; + + /** String java path suffix in form "com/company/Bar.java" + * null if this is not a java file + */ + final String javaPath; + + /** any prefix before java path suffix in the original path */ + final String prefix; + + /** error handling */ + final Throwable thrown; + JavaFile(File path, String javaPath, String prefix, Throwable thrown) { + this.path = path; + this.javaPath = javaPath; + this.prefix = prefix; + this.thrown = thrown; + } + } + + /** + * Read any package statement in the file to determine + * the package path of the file + * @param path the File to seek the package in + * @return the JavaFile with the components of the path + */ + public static JavaFile getJavaFile(File path) { + if (null == path) { + throw new IllegalArgumentException("null path"); + } + String result = path.getPath().replace('\\', '/'); + String packag = ""; + String javaPath = null; + String prefix = null; + Throwable thrown = null; + if (result.endsWith(".java") || result.endsWith(".aj")) { + FileReader reader = null; + try { + reader = new FileReader(path); + BufferedReader br = new BufferedReader(reader); + String line; + while (null != (line = br.readLine())) { + int loc = line.indexOf("package"); + if (-1 != loc) { + int end = line.indexOf(";"); + if (-1 == loc) { + String m = "unterminated package statement \""; + throw new Error(m + line + "\" in " + path); + } + packag = (line.substring(loc + 7, end) + ".") + .trim() + .replace('.', '/'); + break; + } + loc = line.indexOf("import"); + if (-1 != loc) { + break; + } + } + } catch (IOException e) { + thrown = e; + } finally { + if (null != reader) { + try { + reader.close(); + } catch (IOException e1) { + // ignore + } + } + } + if (null == thrown) { + javaPath = packag + path.getName(); + int loc = result.indexOf(javaPath); + if (-1 == loc) { + String m = "expected suffix " + javaPath + " in "; + throw new Error(m + result); + } + prefix = result.substring(0, loc); + } + } + return new JavaFile(path, javaPath, prefix, thrown); + } + + /** + * Extract file path relative to base of package directory + * and directory in SAMPLE_BASE_DIR_NAME for this file. + * @param path the File to render from SAMPLE_BASE_DIR_NAME + * @return String "baseDir {path}" + */ + public static String renderCodePath(File path) { + JavaFile javaFile = getJavaFile(path); + if (javaFile.thrown != null) { + throw new Error(javaFile.thrown.getClass() + + ": " + javaFile.thrown.getMessage()); + } + + String file = javaFile.javaPath; // can be null... + String prefix = javaFile.prefix; + if (prefix == null) { + prefix = path.getPath().replace('\\', '/'); + } + int loc = prefix.lastIndexOf(SAMPLE_BASE_DIR_NAME); + if (-1 == loc) { + String m = "not after " + SAMPLE_BASE_DIR_NAME; + throw new IllegalArgumentException(m + "?: " + path); + } + prefix = prefix.substring(loc + 1 + SAMPLE_BASE_DIR_NAME.length()); + + if (file == null) { + int slash = prefix.lastIndexOf('/'); + if (-1 == slash) { + file = prefix; + prefix = ""; + } else { + file = prefix.substring(slash+1); + prefix = prefix.substring(0, slash); + } + } + if (prefix.endsWith("/")) { + prefix = prefix.substring(0, prefix.length()-1); + } + return (prefix + " " + file).trim(); + } + + public static int commonPrefix(String[] lhs, String[] rhs) { + final int max = smallerSize(lhs, rhs); + int firstDiff = 0; + while (firstDiff < max) { + if (!lhs[firstDiff].equals(rhs[firstDiff])) { + break; + } + firstDiff++; + } + return firstDiff; + } + + private static int smallerSize(Object[] one, Object[] two) { + if ((null == one) || (null == two)) { + return 0; + } + return (one.length > two.length ? two.length : one.length); + } + + public static String[] splitAnchorName(Sample sample) { + return splitAnchorName(sample.anchorName); + } + + public static String[] splitAnchorName(String anchorName) { + ArrayList result = new ArrayList(); + int start = 0; + int loc = anchorName.indexOf("-", start); + String next; + while (loc != -1) { + next = anchorName.substring(start, loc); + result.add(next); + start = loc+1; + loc = anchorName.indexOf("-", start); + } + next = anchorName.substring(start); + result.add(next); + return (String[]) result.toArray(new String[result.size()]); + } + /** + * Replace literals with literals in source string + * @param source the String to modify + * @param from the String[] of literals to replace + * @param to the String[] of literals to use when replacing + * @return the String source as modified by the replaces + */ + public static String replace(String source, String[] from, String[] to) { + if ((null == source) || (0 == source.length())) { + return source; + } + if (from.length != to.length) { + throw new IllegalArgumentException("unmatched from/to"); + } + StringBuffer result = new StringBuffer(); + int LEN = source.length(); + int start = 0; + for (int i = 0; i < LEN; i++) { + String suffix = source.substring(i); + for (int j = 0; j < from.length; j++) { + if (suffix.startsWith(from[j])) { + result.append(source.substring(start, i)); + result.append(to[j]); + start = i + from[j].length(); + i = start-1; + break; + } + } + } + if (start < source.length()) { + result.append(source.substring(start)); + } + return result.toString(); + } + + public static void render( + Sample sample, + String fieldDelim, + String valueDelim, + StringBuffer sink) { + if ((null == sink) || (null == sample)) { + return; + } + if (null == fieldDelim) { + fieldDelim = ""; + } + if (null == valueDelim) { + valueDelim = ""; + } + sink.append("anchorName"); + sink.append(valueDelim); + sink.append(sample.anchorName); + sink.append(fieldDelim); + sink.append("author"); + sink.append(valueDelim); + sink.append(sample.author); + sink.append(fieldDelim); + sink.append("sourcePath"); + sink.append(valueDelim); + sink.append(sample.sourcePath.toString()); + sink.append(fieldDelim); + sink.append("startLine"); + sink.append(valueDelim); + sink.append(sample.startLine); + sink.append(fieldDelim); + sink.append("endLine"); + sink.append(valueDelim); + sink.append(sample.endLine); + sink.append(fieldDelim); + sink.append("sampleCode"); + sink.append(valueDelim); + sink.append(sample.sampleCode.toString()); + sink.append(fieldDelim); + } + private SampleUtil(){} +} diff --git a/build/src/main/java./aspectj/internal/tools/build/Util.java b/build/src/main/java./aspectj/internal/tools/build/Util.java new file mode 100644 index 000000000..2fc2dcb72 --- /dev/null +++ b/build/src/main/java./aspectj/internal/tools/build/Util.java @@ -0,0 +1,483 @@ +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + + +package org.aspectj.internal.tools.build; + +import java.io.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.StringTokenizer; +import java.util.jar.Attributes; +import java.util.jar.Manifest; +import java.util.jar.Attributes.Name; + +/** + * Build-only utilities. + * Many mirror utils module APIs. + */ +public class Util { + public static class Constants { + public static final String TESTSRC = "testsrc"; + public static final String JAVA5_SRC = "java5-src"; + public static final String JAVA5_TESTSRC = "java5-testsrc"; + } + // XXX quick hack for Java 5 support + public static final boolean JAVA5_VM; + static { + boolean java5VM = false; + try { + java5VM = (null != Class.forName("java.lang.annotation.Annotation")); + } catch (Throwable t) { + // ignore + } + JAVA5_VM = java5VM; + } + + /** + * Map version in long form to short, + * e.g., replacing "alpha" with "a" + */ + public static String shortVersion(String version) { + version = Util.replace(version, "alpha", "a"); + version = Util.replace(version, "beta", "b"); + version = Util.replace(version, "candidate", "rc"); + version = Util.replace(version, "development", "d"); + version = Util.replace(version, "dev", "d"); + return version; + } + + /** + * Replace any instances of {replace} in {input} with {with}. + * @param input the String to search/replace + * @param replace the String to search for in input + * @param with the String to replace with in input + * @return input if it has no replace, otherwise a new String + */ + public static String replace(String input, String replace, String with) { + int loc = input.indexOf(replace); + if (-1 != loc) { + String result = input.substring(0, loc); + result += with; + int start = loc + replace.length(); + if (start < input.length()) { + result += input.substring(start); + } + input = result; + } + return input; + } + + /** @return false if filter returned false for any file in baseDir subtree */ + public static boolean visitFiles(File baseDir, FileFilter filter) { + Util.iaxIfNotCanReadDir(baseDir, "baseDir"); + Util.iaxIfNull(filter, "filter"); + File[] files = baseDir.listFiles(); + boolean passed = true; + for (int i = 0; passed && (i < files.length); i++) { + passed = files[i].isDirectory() + ? visitFiles(files[i], filter) + : filter.accept(files[i]); + } + return passed; + } + + /** @throws IllegalArgumentException if cannot read dir */ + public static void iaxIfNotCanReadDir(File dir, String name) { + if (!canReadDir(dir)) { + throw new IllegalArgumentException(name + " dir not readable: " + dir); + } + } + + /** @throws IllegalArgumentException if cannot read file */ + public static void iaxIfNotCanReadFile(File file, String name) { + if (!canReadFile(file)) { + throw new IllegalArgumentException(name + " file not readable: " + file); + } + } + + /** @throws IllegalArgumentException if cannot write dir */ + public static void iaxIfNotCanWriteDir(File dir, String name) { + if (!canWriteDir(dir)) { + throw new IllegalArgumentException(name + " dir not writeable: " + dir); + } + } + + /** @throws IllegalArgumentException if input is null */ + public static void iaxIfNull(Object input, String name) { + if (null == input) { + throw new IllegalArgumentException("null " + name); + } + } + + /** render exception to String */ + public static String renderException(Throwable thrown) { + if (null == thrown) { + return "(Throwable) null"; + } + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw, true); + pw.println(thrown.getMessage()); + thrown.printStackTrace(pw); + pw.flush(); + return sw.getBuffer().toString(); + } + + /** @return true if dir is a writable directory */ + public static boolean canWriteDir(File dir) { + return (null != dir) && dir.canWrite() && dir.isDirectory(); + } + + public static String path(String first, String second) { + return first + File.separator + second; + } + + public static String path(String[] segments) { + StringBuffer sb = new StringBuffer(); + if ((null != segments)) { + for (int i = 0; i < segments.length; i++) { + if (0 < i) { + sb.append(File.separator); + } + sb.append(segments[i]); + } + } + return sb.toString(); + } + + /** @return true if dir is a readable directory */ + public static boolean canReadDir(File dir) { + return (null != dir) && dir.canRead() && dir.isDirectory(); + } + + /** @return true if dir is a readable file */ + public static boolean canReadFile(File file) { + return (null != file) && file.canRead() && file.isFile(); + } + + /** + * Delete file or directory. + * @param dir the File file or directory to delete. + * @return true if all contents of dir were deleted + */ + public static boolean delete(File dir) { + return deleteContents(dir) && dir.delete(); + } + + /** + * Delete contents of directory. + * The directory itself is not deleted. + * @param dir the File directory whose contents should be deleted. + * @return true if all contents of dir were deleted + */ + public static boolean deleteContents(File dir) { + if ((null == dir) || !dir.canWrite()) { + return false; + } else if (dir.isDirectory()) { + File[] files = dir.listFiles(); + for (int i = 0; i < files.length; i++) { + if (!deleteContents(files[i]) || !files[i].delete()) { + return false; + } + } + } + return true; + } + + /** @return File temporary directory with the given prefix */ + public static File makeTempDir(String prefix) { + if (null == prefix) { + prefix = "tempDir"; + } + File tempFile = null; + for (int i = 0; i < 10; i++) { + try { + tempFile = File.createTempFile(prefix,"tmp"); + tempFile.delete(); + if (tempFile.mkdirs()) { + break; + } + tempFile = null; + } catch (IOException e) { + } + } + return tempFile; + } + /** + * Close stream with the usual checks. + * @param stream the InputStream to close - ignored if null + * @return null if closed without IOException, message otherwise + */ + public static String close(Writer stream) { + String result = null; + if (null != stream) { + try { + stream.close(); + } catch(IOException e) { + result = e.getMessage(); + } + } + return result; + } + + /** + * @param list the Object[] to test + * @return true if list is null or empty + */ + public static boolean isEmpty(Object[] list) { + return ((null == list) || (0 == list.length)); + } + + public static void closeSilently(InputStream in) { + if (null != in) { + try { + in.close(); + } catch (IOException e) { + // do nothing + } + } + } + + public static void closeSilently(Reader in) { + if (null != in) { + try { + in.close(); + } catch (IOException e) { + // do nothing + } + } + } + + /** + * Report whether actual has different members than expected + * @param expected the String[] of expected members (none null) + * @param actual the String[] of actual members + * @param sb StringBuffer sink for any differences in membership + * @return true if any diffs found and sink updated + */ + public static final boolean reportMemberDiffs(String[] expected, String[] actual, StringBuffer sb) { + expected = copy(expected); + actual = copy(actual); + int hits = 0; + for (int i = 0; i < expected.length; i++) { + int curHit = hits; + for (int j = 0; (curHit == hits) && (j < actual.length); j++) { + if (null == expected[i]) { + throw new IllegalArgumentException("null at " + i); + } + if (expected[i].equals(actual[j])) { + expected[i] = null; + actual[j] = null; + hits++; + } + } + } + if ((hits != expected.length) || (hits != actual.length)) { + sb.append("unexpected ["); + String prefix = ""; + for (int i = 0; i < actual.length; i++) { + if (null != actual[i]) { + sb.append(prefix); + prefix = ", "; + sb.append("\""); + sb.append(actual[i]); + sb.append("\""); + } + } + sb.append("] missing ["); + prefix = ""; + for (int i = 0; i < expected.length; i++) { + if (null != expected[i]) { + sb.append(prefix); + prefix = ", "; + sb.append("\""); + sb.append(expected[i]); + sb.append("\""); + } + } + sb.append("]"); + return true; + } + return false; + } + + private static final String[] copy(String[] ra) { + if (null == ra) { + return new String[0]; + } + String[] result = new String[ra.length]; + System.arraycopy(ra, 0, result, 0, ra.length); + return result; + } + + /** + * Support for OSGI bundles read from manifest files. + * Currently very limited, and will only support the subset of + * features that we use. + * sources: + * http://www-128.ibm.com/developerworks/library/os-ecl-osgi/index.html + * http://help.eclipse.org/help30/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/osgi/org/osgi/framework/Constants.html + */ + public static class OSGIBundle { + public static final Name BUNDLE_NAME = new Name("Bundle-Name"); + + public static final Name BUNDLE_SYMBOLIC_NAME = new Name( + "Bundle-SymbolicName"); + + public static final Name BUNDLE_VERSION = new Name("Bundle-Version"); + + public static final Name BUNDLE_ACTIVATOR = new Name("Bundle-Activator"); + + public static final Name BUNDLE_VENDOR = new Name("Bundle-Vendor"); + + public static final Name REQUIRE_BUNDLE = new Name("Require-Bundle"); + + public static final Name IMPORT_PACKAGE = new Name("Import-Package"); + + public static final Name BUNDLE_CLASSPATH = new Name("Bundle-ClassPath"); + + /** unmodifiable list of all valid OSGIBundle Name's */ + public static final List NAMES; + static { + ArrayList names = new ArrayList(); + names.add(BUNDLE_NAME); + names.add(BUNDLE_SYMBOLIC_NAME); + names.add(BUNDLE_VERSION); + names.add(BUNDLE_ACTIVATOR); + names.add(BUNDLE_VENDOR); + names.add(REQUIRE_BUNDLE); + names.add(IMPORT_PACKAGE); + names.add(BUNDLE_CLASSPATH); + NAMES = Collections.unmodifiableList(names); + } + + private final Manifest manifest; + + private final Attributes attributes; + + /** + * + * @param manifestInputStream + * the InputStream of the manifest.mf - will be closed. + * @throws IOException + * if unable to read or close the manifest input stream. + */ + public OSGIBundle(InputStream manifestInputStream) throws IOException { + manifest = new Manifest(); + manifest.read(manifestInputStream); + manifestInputStream.close(); + attributes = manifest.getMainAttributes(); + } + + public String getAttribute(Name attributeName) { + return attributes.getValue(attributeName); + } + + public String[] getClasspath() { + String cp = getAttribute(OSGIBundle.BUNDLE_CLASSPATH); + if (null == cp) { + return new String[0]; + } + StringTokenizer st = new StringTokenizer(cp, " ,"); + String[] result = new String[st.countTokens()]; + int i = 0; + while (st.hasMoreTokens()) { + result[i++] = st.nextToken(); + } + return result; + } + + /** + * XXX ugly/weak hack only handles a single version comma + * {name};bundle-version="[1.5.0,1.5.5]";resolution:=optional + * @return + */ + public RequiredBundle[] getRequiredBundles() { + String value = getAttribute(OSGIBundle.REQUIRE_BUNDLE); + if (null == value) { + return new RequiredBundle[0]; + } + StringTokenizer st = new StringTokenizer(value, " ,"); + RequiredBundle[] result = new RequiredBundle[st.countTokens()]; + int i = 0; + int skips = 0; + while (st.hasMoreTokens()) { + String token = st.nextToken(); + int first = token.indexOf("\""); + if (-1 != first) { + if (!st.hasMoreTokens()) { + throw new IllegalArgumentException(token); + } + // just assume only one quoted "," for version? + token += "," + st.nextToken(); + skips++; + } + result[i++] = new RequiredBundle(token); + } + if (skips > 0) { + RequiredBundle[] patch = new RequiredBundle[result.length-skips]; + System.arraycopy(result, 0, patch, 0, patch.length); + result = patch; + } + return result; + } + + /** + * Wrap each dependency on another bundle + */ + public static class RequiredBundle { + + /** unparsed entry text, for debugging */ + final String text; + + /** Symbolic name of the required bundle */ + final String name; + + /** if not null, then start/end versions of required bundle + * in the format of the corresponding manifest entry + */ + final String versions; + + /** if true, then required bundle is optional */ + final boolean optional; + + private RequiredBundle(String entry) { + text = entry; + StringTokenizer st = new StringTokenizer(entry, ";"); + name = st.nextToken(); + String vers = null; + String opt = null; + // bundle-version="[1.5.0,1.5.5]";resolution:=optiona + final String RESOLUTION = "resolution:="; + final String VERSION = "bundle-version=\""; + while (st.hasMoreTokens()) { + String token = st.nextToken(); + if (token.startsWith(VERSION)) { + int start = VERSION.length(); + int end = token.lastIndexOf("\""); + vers = token.substring(start, end); + // e.g., [1.5.0,1.5.5) + } else if (token.startsWith(RESOLUTION)) { + int start = RESOLUTION.length(); + int end = token.length(); + opt = token.substring(start, end); + } + } + versions = vers; + optional = "optional".equals(opt); + } + } + } +} + diff --git a/build/src/main/java./aspectj/internal/tools/build/package.html b/build/src/main/java./aspectj/internal/tools/build/package.html new file mode 100644 index 000000000..3fa443812 --- /dev/null +++ b/build/src/main/java./aspectj/internal/tools/build/package.html @@ -0,0 +1,12 @@ + + + +The build taskdef relies on the classes in this package for +behavior independent of Ant. + + diff --git a/build/src/main/java/$installer$/org/aspectj/Main.java b/build/src/main/java/$installer$/org/aspectj/Main.java new file mode 100644 index 000000000..748b035ae --- /dev/null +++ b/build/src/main/java/$installer$/org/aspectj/Main.java @@ -0,0 +1,1861 @@ +/* ******************************************************************* + * Copyright (c) 2000-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + +package $installer$.org.aspectj; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.PrintStream; +import java.lang.reflect.InvocationTargetException; +import java.net.URL; +import java.util.Map; +import java.util.Properties; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +import javax.swing.BorderFactory; +import javax.swing.BoxLayout; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JEditorPane; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JProgressBar; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import javax.swing.SwingUtilities; +import javax.swing.border.Border; +import javax.swing.border.CompoundBorder; +import javax.swing.border.EmptyBorder; + +/** + * Invoke the Installer gui. There are two ways to run without GUI by passing parameters to main: + *
        + *
      1. pass -text {pathToPropertiesFile}: + *
          + *
        • "-text".equals(arg[0])
        • + *
        • arg[1] is the path to a properties file which defines name="output.dir" value="{path to output dir}" name="context.javaPath" + * value="{path to JDKDIR}", i.e,. + * + *
          + * output.dir=c:/latest
          + *   "context.javaPath=c:/apps/jdk1.3.1
          + * 
          + * + *
        • + *
        • outputDir must be created and empty (i.e., no overwriting
        • + *
        • the VM being invoked should be the target vm
        • + *
        + *
      2. + *
      3. pass -to {pathToTargetDir}: + *
          + *
        • "-to".equals(arg[0])
        • + *
        • arg[1] is the path to a writable install directory.
        • + *
        + *
      4. + */ +public class Main { + public static void main(String[] args) { + Options.loadArgs(args); + boolean hasGui = true; + Properties properties = new Properties(); + InputStream istream = null; + try { + istream = Main.class.getResourceAsStream(Installer.RESOURCE_DIR + "/properties.txt"); + if (istream == null) { + System.err.println("unable to load properties.txt using Main.class - exiting"); + Main.exit(-1); + } + properties.load(istream); + // when running outside GUI, load values into properties + // so that property-value resolution works + // (otherwise, could just set values below). + // XXX not sure if this indirection is actually needed. + if (null != Options.textProperties) { + istream.close(); + istream = new FileInputStream(Options.textProperties); + properties.load(istream); + hasGui = false; + } else if (null != Options.targetDir) { + String path = null; + try { + path = Options.targetDir.getCanonicalPath(); + } catch (IOException e) { + path = Options.targetDir.getAbsolutePath(); + } + String javaPath = ConfigureLauncherPane.getDefaultJavaHomeLocation(); + if (null == javaPath) { + System.err.println("using GUI - unable to find java"); + } else { + properties.setProperty("output.dir", path); + properties.setProperty("context.javaPath", javaPath); + hasGui = false; + } + } + } catch (IOException ioe) { + handleException(ioe); + } finally { + if (null != istream) { + try { + istream.close(); + } catch (IOException e) { + } // ignore + } + } + + try { + String className = (String) properties.get("installer.main.class"); + //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + Installer installer = (Installer) Class.forName(className).newInstance(); + InstallContext installerContext = new InstallContext(properties); + installerContext.setHasGui(hasGui); + installer.setContext(installerContext); + if (installerContext.hasGui()) { // let context force whether or not to run gui + installer.runGUI(); + } else { + // set output dir and java path in context after minimal validation + String propName = "output.dir"; + String propValue = properties.getProperty(propName); + if (null == propValue) { + throw new Exception("expecting property " + propName); + } + String outputDirName = propValue; + propName = "context.javaPath"; + propValue = properties.getProperty(propName); + if (null == propValue) { + throw new Exception("expecting property " + propName); + } + String javaPath = propValue; + File outputDir = new File(outputDirName); + if (!outputDir.isDirectory()) { + throw new Exception("not a dir outputDirName: " + outputDirName + " dir: " + outputDir); + } + if (!outputDir.canWrite()) { + throw new Exception("cannot write outputDirName: " + outputDirName + " dir: " + outputDir); + } + InstallContext context = installer.getContext(); // todo: why not use installerContext? + context.setOutputDir(outputDir); + context.javaPath = new File(javaPath); + // todo: check javaPath for ... bin/java? lib/rt.jar? + if (!outputDir.isDirectory() || !outputDir.canRead()) { + throw new Exception("invalid javaPath: " + javaPath); + } + // directly set context and run + WizardPane.setContext(installerContext); + installer.run(); + } + } catch (Exception e) { + handleException(e); + } + } + + public static void handleException(Throwable e) { + System.out.println("internal error: " + e.toString()); + e.printStackTrace(); + Main.exit(-1); + } + + /** indirection for System.exit - todo apply cleanup here as necessary */ + public static void exit(int value) { + System.exit(value); + } +} // class Main + +class Options { + public static boolean verbose = false; + public static String textProperties = null; + public static File targetDir = null; + public static boolean forceError1 = false; + public static boolean forceError2 = false; + public static boolean forceHandConfigure = false; + + public static void loadArgs(String[] args) { + if (args == null) { + return; + } + for (int i = 0; i < args.length; i++) { + String arg = args[i]; + if (arg == null) { + continue; + } + + if (arg.equals("-verbose")) { + verbose = true; + } else if (arg.equals("-forceError1")) { + forceError1 = true; + } else if (arg.equals("-forceError2")) { + forceError2 = true; + } else if (arg.equals("-forceHandConfigure")) { + forceHandConfigure = true; + } else if (arg.equals("-text")) { + if (i + 1 < args.length) { + textProperties = args[++i]; + } + } else if (arg.equals("-to")) { + String next = "no argument"; + if (i + 1 < args.length) { + next = args[++i]; + File targDir = new File(next); + if (targDir.isDirectory() && targDir.canWrite()) { + targetDir = targDir; + } + } + if (null == targetDir) { + System.err.println("invalid -to dir: " + next); + } + } + } + } +} + +/** tools installer installs the entire 1.1+ distribution */ +class ToolsInstaller extends Installer { + public String getTitle() { + return "Installer for AspectJ(TM)"; + } + + public String getPrefix() { + return "tools"; + } + + public String getReadmeFilename() { + return "README-AspectJ.html"; + } + + public ToolsInstaller() { + InstallPane installPane = new InstallPane(true); + setInstallPane(installPane); + panes = new WizardPane[] { new IntroPane(), new ConfigureLauncherPane(), new LocationPane(), installPane, new FinishPane() }; + } +} + +class DocsInstaller extends Installer { + public String getTitle() { + return "AspectJ(TM) Documentation and Examples Installer"; + } + + public String getPrefix() { + return "docs"; + } + + public DocsInstaller() { + InstallPane installPane = new InstallPane(false); + setInstallPane(installPane); + panes = new WizardPane[] { new IntroPane(), new LocationPane(), installPane, new FinishPane() }; + } +} + +class AJDEForJBuilderInstaller extends Installer { + public String getTitle() { + return "AspectJ(TM) Support for JBuilder"; + } + + public String getPrefix() { + return "ajdeForJBuilder"; + } + + public AJDEForJBuilderInstaller() { + InstallPane installPane = new InstallPane(false); + setInstallPane(installPane); + panes = new WizardPane[] { new IntroPane(), new LocationPane() { + public String getDefaultLocation() { + if (context.onWindows()) { + // check some default locations + String[] paths = { "c:\\JBuilder6\\lib\\ext", "c:\\apps\\JBuilder6\\lib\\ext", + "c:\\Program Files\\JBuilder6\\lib\\ext" }; + int pathIndex = 0; + for (; pathIndex < paths.length; pathIndex++) { + if (new File(paths[pathIndex]).exists()) { + return paths[pathIndex]; + } + } + return "c:\\JBuilder6\\lib\\ext"; + } else { + return "/usr/JBuilder6/lib/ext"; + } + } + + /** + * Make sure that the old jar file gets removed. + */ + public void verify() { + File jbuilder = new File(location.getText() + "/../../lib/jbuilder.jar"); + if (!jbuilder.exists() && hasGui()) { + int ret = JOptionPane.showConfirmDialog(frame, "The location you specified does not seem to be a " + + "valid JBuilder install directory." + " Continue?", "Confirm Install", JOptionPane.YES_NO_OPTION, + JOptionPane.QUESTION_MESSAGE); + if (ret != JOptionPane.YES_OPTION) { + Main.exit(-1); + } else { + // do nothing + } + } + + File oldFile = new File(location.getText() + "/ajbuilder.jar"); + if (oldFile.exists() && hasGui()) { + int ret = JOptionPane.showConfirmDialog(frame, + "This old version of AJDE for JBuilder (\"ajbuilder.jar\") exists" + + " and must be removed from the install directory." + " OK to delete?", "Confirm Delete", + JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); + if (ret != JOptionPane.YES_OPTION) { + Main.exit(-1); + } else { + oldFile.delete(); + } + } + } + }, installPane, new FinishPane() }; + } +} + +class AJDEForForteInstaller extends Installer { + public String getTitle() { + return "AspectJ(TM) Support for Forte 4J"; + } + + public String getPrefix() { + return "ajdeForForte"; + } + + private String installLoc = ""; + + public AJDEForForteInstaller() { + InstallPane installPane = new InstallPane(false); + setInstallPane(installPane); + panes = new WizardPane[] { new IntroPane(), new LocationPane() { + public String getDefaultLocation() { + if (context.onWindows()) { + // check some default locations + String[] paths = { "c:\\forte4j\\modules", "c:\\apps\\forte4j\\modules", "c:\\Program Files\\forte4j\\modules" }; + int pathIndex = 0; + for (; pathIndex < paths.length; pathIndex++) { + if (new File(paths[pathIndex]).exists()) { + return paths[pathIndex]; + } + } + return "c:\\forte4j\\modules"; + } else { + return "/usr/forte4j/modules"; + } + } + + public void verify() { + File forte = new File(location.getText() + "/../lib/openide.jar"); + installLoc = location.getText(); + if (!forte.exists() && hasGui()) { + int ret = JOptionPane.showConfirmDialog(frame, "The location you specified does not seem to be a " + + "valid Forte install directory." + " Continue?", "Confirm Install", JOptionPane.YES_NO_OPTION, + JOptionPane.QUESTION_MESSAGE); + if (ret != JOptionPane.YES_OPTION) { + Main.exit(-1); + } else { + // do nothing + } + } + } + }, installPane, new FinishPane() { + public void finalActions() { // todo verify dir ../lib/ext exists? + // !!! this should be done with two install locations, not by moving a file + new File(installLoc + "/../lib/ext/aspectjrt.jar").delete(); + new File(installLoc + "/aspectjrt.jar").renameTo(new File((installLoc + "/../lib/ext/aspectjrt.jar"))); + new File(installLoc + "/aspectjrt.jar").delete(); + } + } }; + } +} + +class SrcInstaller extends Installer { + public String getTitle() { + return "AspectJ(TM) Compiler and Core Tools Sources Installer"; + } + + public String getPrefix() { + return "sources"; + } + + public SrcInstaller() { + InstallPane installPane = new InstallPane(false); + setInstallPane(installPane); + panes = new WizardPane[] { new IntroPane(), new LocationPane(), installPane, new FinishPane() }; + } +} + +abstract class Installer { + static final String EXIT_MESSAGE = "Are you sure you want to cancel the installation?"; + static final String EXIT_TITLE = "Exiting installer"; + /** + * relative directory in jar from package $installer$.org.aspectj for loading resources - todo must be tracked during build + */ + public static final String RESOURCE_DIR = "resources"; + + JFrame frame; + InstallContext context; + /** special pane that actually does the installation */ + InstallPane installPane; + + public Installer() { + } + + protected void setInstallPane(InstallPane installPane) { + this.installPane = installPane; + } + + public InstallPane getInstallPane() { + return installPane; + } + + /** directly run the install pane, if any */ + public void run() { + if (null != installPane) { + installPane.run(); + } + } + + public abstract String getPrefix(); + + public String getReadmeFilename() { + return "README-" + getPrefix().toUpperCase() + ".html"; + } + + public void setContext(InstallContext context) { + this.context = context; + context.installer = this; + } + + public InstallContext getContext() { + return context; + } + + public String getTitle() { + return "AspectJ(TM) Installer"; + } + + public int getWidth() { + return 640; + } + + public int getHeight() { + return 460; + } + + protected WizardPane[] panes = new WizardPane[0]; + + public WizardPane[] getPanes() { + return panes; + } + + public int findPaneIndex(WizardPane pane) { + for (int i = 0; i < panes.length; i++) { + if (panes[i] == pane) { + return i; + } + } + return -1; + } + + Component header, footer, body; + + public void runGUI() { + frame = new JFrame(getTitle()); + WindowListener wl = new WindowAdapter() { + public void windowClosing(WindowEvent arg0) { + Main.exit(-1); // -1 unless exiting through done button + } + }; + frame.addWindowListener(wl); + + if (Options.forceError1) { + throw new RuntimeException("forced error1 for testing purposes"); + } + + Dimension size = Toolkit.getDefaultToolkit().getScreenSize(); + + int x = (int) (size.getWidth() - getWidth()) / 2; + int y = (int) (size.getHeight() - getHeight()) / 2; + + //include a few sanity checks on starting position + if (x < 0) { + x = 0; + } + if (x > 600) { + x = 600; + } + if (y < 0) { + y = 0; + } + if (y > 400) { + y = 400; + } + + frame.setLocation(x, y); + frame.setSize(getWidth(), getHeight()); + moveToPane(getPanes()[0]); + frame.setVisible(true); + } + + public void moveToPane(WizardPane pane) { + WizardPane.setContext(this.context); + + Dimension size = frame.getContentPane().getSize(); + + JPanel contents = new JPanel(); + contents.setLayout(new BorderLayout()); + header = makeHeader(); + contents.add(header, BorderLayout.NORTH); + + body = pane.getPanel(); + contents.add(body, BorderLayout.CENTER); + + footer = pane.getButtons(); + contents.add(footer, BorderLayout.SOUTH); + + contents.revalidate(); + contents.setSize(size); + + frame.setContentPane(contents); + + //XXX deal with threading here? + pane.run(); + } + + public Icon loadImage(String name) { + return new javax.swing.ImageIcon(this.getClass().getResource(name)); + } + + public Component makeHeader() { + return new JLabel(loadImage(Installer.RESOURCE_DIR + "/aspectjBanner.gif")); + } + + public ActionListener makeNextAction(final WizardPane pane) { + int nextPaneIndex = findPaneIndex(pane) + 1; + if (nextPaneIndex >= getPanes().length) { + return null; + } + + final WizardPane nextPane = getPanes()[nextPaneIndex]; + return new ActionListener() { + public void actionPerformed(ActionEvent e) { + pane.finish(); + moveToPane(nextPane); + } + }; + } + + public ActionListener makeBackAction(final WizardPane pane) { + int nextPaneIndex = findPaneIndex(pane) - 1; + if (nextPaneIndex < 0) { + return null; + } + + final WizardPane nextPane = getPanes()[nextPaneIndex]; + return new ActionListener() { + public void actionPerformed(ActionEvent e) { + moveToPane(nextPane); + } + }; + } + + public ActionListener makeCancelAction(WizardPane pane) { + return new ActionListener() { + public void actionPerformed(ActionEvent e) { + int ret = JOptionPane.showConfirmDialog(frame, EXIT_MESSAGE, EXIT_TITLE, JOptionPane.YES_NO_OPTION, + JOptionPane.QUESTION_MESSAGE); + if (ret == JOptionPane.YES_OPTION) { + Main.exit(-1); + } + } + }; + } + + public ActionListener makeFinishAction(WizardPane pane) { + return new ActionListener() { + public void actionPerformed(ActionEvent e) { + Main.exit(0); + } + }; + } +} + +// willing to go up to 3 levels deep to find either jre or jdk + +// jre\[*\]lib\ext +// jdk*\lib\tools.jar + +/***** + * final static int MAX_DEPTH = 4; public static void findPaths(String prefix, File currentDir, int currentDepth) { if (currentDepth + * > MAX_DEPTH) return; if (!currentDir.exists() || !currentDir.isDirectory()) return; File [] files = currentDir.listFiles(); if + * (files == null) return; for (int i=0; i"); + int stopIndex = text.indexOf(""); + if (startIndex == -1 || stopIndex == -1) { + return text; + } + stopIndex += 7; + return text.substring(0, startIndex) + text.substring(stopIndex); + } + + static String styleHeader = "";/* + * "); - } - - - private static boolean isStyleSheet(String line) throws IOException { - line = line.toLowerCase(); - int len = line.length(); - int i = 0; - - while (true) { - if (i == len) return false; - if (! Character.isWhitespace(line.charAt(i))) break; - } - - return line.startsWith(" This task can take the following arguments:

        - * - *
          - *
        • srcdir
        • - *
        • destdir
        • - *
        • include
        • - *
        • exclude
        • - *
        - * - *

        Of these arguments, only sourcedir is required.

        - * - *

        When this task executes, it will scan the srcdir based on the - * include and exclude properties.

        - */ - -public class StripNonBodyHtml extends MatchingTask { - - private File srcDir; - private File destDir = null; - - public void setSrcdir(File srcDir) { - this.srcDir = srcDir; - } - - public void setDestdir(File destDir) { - this.destDir = destDir; - } - - public void execute() throws BuildException { - if (srcDir == null) { - throw new BuildException("srcdir attribute must be set!"); - } - if (!srcDir.exists()) { - throw new BuildException("srcdir does not exist!"); - } - if (!srcDir.isDirectory()) { - throw new BuildException("srcdir is not a directory!"); - } - if (destDir != null) { - if (!destDir.exists()) { - throw new BuildException("destdir does not exist!"); - } - if (!destDir.isDirectory()) { - throw new BuildException("destdir is not a directory!"); - } - } - - DirectoryScanner ds = super.getDirectoryScanner(srcDir); - String[] files = ds.getIncludedFiles(); - - log("stripping " + files.length + " files"); - int stripped = 0; - for (int i = 0, len = files.length; i < len; i++) { - if (processFile(files[i])) { - stripped++; - } else { - log(files[i] + " not stripped"); - } - } - log(stripped + " files successfully stripped"); - } - - boolean processFile(String filename) throws BuildException { - File srcFile = new File(srcDir, filename); - File destFile; - if (destDir == null) { - destFile = srcFile; - } else { - destFile = new File(destDir, filename); - destFile.getParentFile().mkdirs(); - } - try { - return strip(srcFile, destFile); - } catch (IOException e) { - throw new BuildException(e); - } - } - - private boolean strip(File f, File g) throws IOException { - BufferedInputStream in = - new BufferedInputStream(new FileInputStream(f)); - String s = readToString(in); - in.close(); - return writeBodyTo(s, g); - } - - private ByteArrayOutputStream temp = new ByteArrayOutputStream(); - private byte[] buf = new byte[2048]; - - private String readToString(InputStream in) throws IOException { - ByteArrayOutputStream temp = this.temp; - byte[] buf = this.buf; - String s = ""; - try { - while (true) { - int i = in.read(buf, 0, 2048); - if (i == -1) break; - temp.write(buf, 0, i); - - } - s = temp.toString(); - } finally { - temp.reset(); - } - return s; - } - - private boolean writeBodyTo(String s, File f) throws IOException { - int start;//, end; - try { - start = findStart(s); - findEnd(s, start); - } catch (ParseException e) { - return false; // if we get confused, just don't write the file. - } - s = processBody(s,f); - BufferedOutputStream out = - new BufferedOutputStream(new FileOutputStream(f)); - - out.write(s.getBytes()); - out.close(); - return true; - } - - /** - * Process body. This implemenation strips text - * between <!-- start strip --> - * and <!-- end strip --> - * inclusive. - */ - private String processBody(String body, File file) { - if (null == body) return body; - final String START = ""; - final String END = ""; - return stripTags(body, file.toString(), START, END); - } - - /** - * Strip 0..n substrings in input: "s/${START}.*${END}//g" - * @param input the String to strip - * @param source the name of the source for logging purposes - * @param start the starting tag (case sensitive) - * @param end the ending tag (case sensitive) - */ - String stripTags(String input, final String SOURCE, - final String START, final String END) { - if (null == input) return input; - StringBuffer buffer = new StringBuffer(input.length()); - String result = input; - int curLoc = 0; - while (true) { - int startLoc = input.indexOf(START, curLoc); - if (-1 == startLoc) { - buffer.append(input.substring(curLoc)); - result = buffer.toString(); - break; // <------------ valid exit - } else { - int endLoc = input.indexOf(END, startLoc); - if (-1 == endLoc) { - log(SOURCE + " stripTags - no end tag - startLoc=" + startLoc); - break; // <------------ invalid exit - } else if (endLoc < startLoc) { - log(SOURCE + " stripTags - impossible: startLoc=" - + startLoc + " > endLoc=" + endLoc); - break; // <------------ invalid exit - } else { - buffer.append(input.substring(curLoc, startLoc)); - curLoc = endLoc + END.length(); - } - } - } - return result; - } - - private int findStart(String s) throws ParseException { - int len = s.length(); - int start = 0; - while (true) { - start = s.indexOf("= len) throw barf(); - char ch = s.charAt(start); - if (ch == '>') return start + 1; - if (Character.isWhitespace(ch)) { - start = s.indexOf('>', start); - if (start == -1) return -1; - return start + 1; - } - } - } - - private int findEnd(String s, int start) throws ParseException { - int end; - end = s.indexOf("", start); - if (end == -1) { - end = s.indexOf("", start); - if (end == -1) throw barf(); - } - return end; - } - - private static class ParseException extends Exception { - private static final long serialVersionUID = -1l; - } - - private static ParseException barf() { - return new ParseException(); - } -} diff --git a/build/src/org/aspectj/internal/tools/ant/taskdefs/TestBuildModule.java b/build/src/org/aspectj/internal/tools/ant/taskdefs/TestBuildModule.java deleted file mode 100644 index bd3b99609..000000000 --- a/build/src/org/aspectj/internal/tools/ant/taskdefs/TestBuildModule.java +++ /dev/null @@ -1,79 +0,0 @@ -/* ******************************************************************* - * Copyright (c) 1999-2001 Xerox Corporation, - * 2002 Palo Alto Research Center, Incorporated (PARC). - * All rights reserved. - * This program and the accompanying materials are made available - * under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Xerox/PARC initial implementation - * ******************************************************************/ - - -package org.aspectj.internal.tools.ant.taskdefs; - -import java.io.File; -import java.util.Arrays; - -import org.apache.tools.ant.Project; -import org.aspectj.internal.tools.build.BuildSpec; -import org.aspectj.internal.tools.build.Builder; -import org.aspectj.internal.tools.build.Util; - -public class TestBuildModule { -// private static boolean REBUILD = false; - private static final String SYNTAX = "java {classname} <[product|module]dir>"; - public static void main(String[] args) { - - if ((null == args) || (1 > args.length) - || !Util.canReadDir(new File(args[0]))) { - System.err.println(SYNTAX); - return; - } - File dir = new File(args[0]); - // create a module - if (Util.canReadDir(new File(dir, "dist"))) { - createProduct(args); - } else if (Util.canReadFile(new File(dir, ".classpath"))) { - createModule(args); - } else { - System.err.println(SYNTAX); - } - } - - static void createModule(String[] args) { - File moduleDir = new File(args[0]); - File baseDir = moduleDir.getParentFile(); - if (null == baseDir) { - baseDir = new File("."); - } - File jarDir = new File(baseDir, "aj-build-jars"); - if (!(Util.canReadDir(jarDir) || jarDir.mkdirs())) { - System.err.println("createModule unable to create " + jarDir); - return; - } - - // set module dir or basedir plus module name - BuildSpec buildSpec = new BuildSpec(); - buildSpec.moduleDir = moduleDir; - buildSpec.jarDir = jarDir; - buildSpec.verbose = true; - buildSpec.failonerror = true; - buildSpec.trimTesting = true; - buildSpec.rebuild = true; - - File tempDir = null; - Project project = new Project(); - project.setProperty("verbose", "true"); - project.setName("TestBuildModule.createModule" + Arrays.asList(args)); - Builder builder = AntBuilder.getBuilder("", project, tempDir); - builder.build(buildSpec); - } - - static void createProduct(String[] args) { - throw new Error("unimplemented"); - } -} - diff --git a/build/src/org/aspectj/internal/tools/ant/taskdefs/VersionUptodate.java b/build/src/org/aspectj/internal/tools/ant/taskdefs/VersionUptodate.java deleted file mode 100644 index 92b271c69..000000000 --- a/build/src/org/aspectj/internal/tools/ant/taskdefs/VersionUptodate.java +++ /dev/null @@ -1,144 +0,0 @@ -/* ******************************************************************* - * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). - * All rights reserved. - * This program and the accompanying materials are made available - * under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Xerox/PARC initial implementation - * ******************************************************************/ - -package org.aspectj.internal.tools.ant.taskdefs; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Task; - -/** - * Check if version source file has the specified build version, - * and ensure a tag file reflects whether it does or not. - */ -public class VersionUptodate extends Task { - public VersionUptodate() {} - - private String buildVersion; - private File versionSource; - private File versionTagFile; - - /** - * @param buildVersion String expected as Version.text - required - */ - public void setVersion(String buildVersion) { - this.buildVersion = buildVersion; - } - - /** - * @param versionSource the File Version.java containing text constant - * - required - */ - public void setVersionSourceFile(File versionSource) { - this.versionSource = versionSource; - } - - /** - * @param versionTagFile the File whose existence signals that the version - * is uptodate after this task executes - required. - */ - public void setVersionTagFile(File versionTagFile) { - this.versionTagFile = versionTagFile; - } - - /** - * If the Version.java source file contains the correct - * build version, then create the output tag file, - * else delete it if it exists. - * @throws BuildException if tagFile not creatable and version is incorrect - * or if version is correct and tagFile cannot be deleted. - */ - public void execute() throws BuildException { - if (null == buildVersion) { - throw new BuildException("require buildVersion"); - } - if ((null == versionSource) || !versionSource.canRead()){ - throw new BuildException("require versionSource"); - } - if (null == versionTagFile){ - throw new BuildException("require versionTagFile"); - } - if (sameVersion(versionSource, buildVersion)) { - if (!versionTagFile.exists()) { - createFile(versionTagFile, buildVersion); - } - } else if (null == versionTagFile) { - throw new BuildException("no tag file, and version out of date"); - } else if (versionTagFile.exists()) { - if (!versionTagFile.delete()) { - throw new BuildException("version out of date, but cannot delete " + versionTagFile); - } - } - } - - /** - * Detect whether version is correct in Java sources. - * @param versionSource - * @param buildVersion - * @return boolean - */ - private boolean sameVersion(File versionSource, String buildVersion) { - // XXX build and load instead of scanning? - FileReader fileReader = null; - try { - fileReader = new FileReader(versionSource); - BufferedReader reader = new BufferedReader(fileReader); - String line; - while (null != (line = reader.readLine())) { - int loc = line.indexOf("static final String text = "); - if (-1 != loc) { - return (-1 != line.indexOf(buildVersion , loc)); - } - } - return false; - } catch (IOException e) { - return false; - } finally { - if (null != fileReader) { - try { - fileReader.close(); - } catch (IOException e) { - } - } - } - } - - /** - * Create file with contents - */ - private void createFile(File versionTagFile, String contents) { - FileWriter writer = null; - try { - writer = new FileWriter(versionTagFile); - char[] buf = new char[contents.length()]; - contents.getChars(0, buf.length, buf, 0); - writer.write(contents); - } catch (IOException e) { - throw new BuildException("writing " + versionTagFile, e); - } finally { - if (null != writer) { - try { - writer.close(); - } catch (IOException e){ - // ignore - } - } - } - } - -} - diff --git a/build/src/org/aspectj/internal/tools/ant/taskdefs/taskdefs.properties b/build/src/org/aspectj/internal/tools/ant/taskdefs/taskdefs.properties deleted file mode 100644 index 884077a85..000000000 --- a/build/src/org/aspectj/internal/tools/ant/taskdefs/taskdefs.properties +++ /dev/null @@ -1,21 +0,0 @@ -ajinstaller=org.aspectj.internal.tools.ant.taskdefs.AJInstaller -ajpush=org.aspectj.internal.tools.ant.taskdefs.AJPush -ajbuild=org.aspectj.internal.tools.ant.taskdefs.BuildModule -versionuptodate=org.aspectj.internal.tools.ant.taskdefs.VersionUptodate -checklics=org.aspectj.internal.tools.ant.taskdefs.Checklics -stripnonbodyhtml=org.aspectj.internal.tools.ant.taskdefs.StripNonBodyHtml - -# ajclean=org.aspectj.internal.tools.ant.taskdefs.AJclean -# ajcvs=org.aspectj.internal.tools.ant.taskdefs.Ajcvs -# ajikes=org.aspectj.internal.tools.ant.taskdefs.AJikes -# ajinit=org.aspectj.internal.tools.ant.taskdefs.AjInit -# checkrelease=org.aspectj.internal.tools.ant.taskdefs.Checkrelease -# clear=org.aspectj.internal.tools.ant.taskdefs.Clear -# inlinestylesheetaj=org.aspectj.internal.tools.ant.taskdefs.CopyAndInlineStyleshee -# ensure=org.aspectj.internal.tools.ant.taskdefs.Ensure -# ensureproperties=org.aspectj.internal.tools.ant.taskdefs.EnsureProperties -# newdir=org.aspectj.internal.tools.ant.taskdefs.Newdir -# overwrite=org.aspectj.internal.tools.ant.taskdefs.Overwrite -# props2filters=org.aspectj.internal.tools.ant.taskdefs.Props2Filters -# tgz=org.aspectj.internal.tools.ant.taskdefs.Tgz -# vmcheck=org.aspectj.internal.tools.ant.taskdefs.VMCheck diff --git a/build/src/org/aspectj/internal/tools/build/BuildSpec.java b/build/src/org/aspectj/internal/tools/build/BuildSpec.java deleted file mode 100644 index ed0a453e1..000000000 --- a/build/src/org/aspectj/internal/tools/build/BuildSpec.java +++ /dev/null @@ -1,80 +0,0 @@ -/* ******************************************************************* - * Copyright (c) 1999-2001 Xerox Corporation, - * 2002 Palo Alto Research Center, Incorporated (PARC), - * 2005 Contributors. - * All rights reserved. - * This program and the accompanying materials are made available - * under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Xerox/PARC initial implementation - * ******************************************************************/ - - -package org.aspectj.internal.tools.build; - - -import java.io.File; - -/** - * Open struct for specifying builds for both modules and products. - * Separated from bulder to permit this to build many modules - * concurrently. - */ -public class BuildSpec { - public static final String DEFAULT_VERSION = "DEVELOPMENT"; - // shared - public File baseDir; - public File moduleDir; - public File jarDir; - public File tempDir; - public File stagingDir; - public String buildConfig; - public String version; - public boolean rebuild; - public boolean trimTesting; - public boolean assembleAll; - public boolean failonerror; - public boolean verbose; - - // building products - public File productDir; - public boolean createInstaller; - public File distDir; - - // building modules - public String module; - public BuildSpec() { - version = DEFAULT_VERSION; - } - - public boolean isProduct() { - return (Util.canReadDir(productDir)); - } - - public boolean isModule() { - return (!isProduct() && Util.canReadDir(moduleDir)); - } - - public boolean isValid() { - return (isProduct() || isModule()); - } - - public String toString() { - if (null != productDir) { - return "product " + productDir.getName(); - } else if (null != moduleDir) { - return "module " + moduleDir.getName(); - } else { - return ""; - } - } -} - diff --git a/build/src/org/aspectj/internal/tools/build/Builder.java b/build/src/org/aspectj/internal/tools/build/Builder.java deleted file mode 100644 index 72f53e901..000000000 --- a/build/src/org/aspectj/internal/tools/build/Builder.java +++ /dev/null @@ -1,676 +0,0 @@ -/* ******************************************************************* - * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC), - * 2003 Contributors. - * All rights reserved. - * This program and the accompanying materials are made available - * under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * PARC initial implementation - * ******************************************************************/ - -package org.aspectj.internal.tools.build; - -import java.io.File; -import java.io.FileFilter; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Properties; -import java.util.StringTokenizer; - -import org.apache.tools.ant.BuildException; -import org.aspectj.internal.tools.build.Result.Kind; - -/** - * Template class to build (eclipse) modules (and, weakly, products), including - * any required modules. When building modules, this assumes: - *
          - *
        • the name of the module is the base name of the module directory
        • - *
        • all module directories are in the same base (workspace) directory
        • - *
        • the name of the target module jar is {moduleName}.jar
        • - *
        • a module directory contains a .classpath file with - * (currently line-parseable) entries per Eclipse (XML) conventions
        • - *
        • Builder.RESOURCE_PATTERN identifies all resources to copy - * to output.
        • - *
        • This can safely trim test-related code: - *
            - *
          • source directories named "testsrc"
          • - *
          • libraries named "junit.jar"
          • - *
          • required modules whose names start with "testing"
          • - *
          - *
        • A file {moduleDir}/{moduleName}.properties is a property - * file possibly containing entries defining requirements to be merged with the - * output jar (deprecated mechanism - use assembleAll or products)
        • - *
        - * This currently provides no control over the compile or assembly process, but - * clients can harvest {moduleDir}/bin directories to re-use the - * results of eclipse compiles. - *

        - * When building products, this assumes: - *

          - *
        • the installer-resources directory is a peer of the products directory, - * itself the parent of the particular product directory.
        • - *
        • the dist, jar, product, and base (module) directory are set
        • - *
        • the product distribution consists of all (and only) the files in the - * dist sub-directory of the product directory
        • - *
        • files in the dist sub-directory that are empty and end with .jar - * represent modules to build, either as named or through aliases known here.
        • - *
        • When assembling the distribution, all non-binary files are to be - * filtered. - *
        • - *
        • the name of the product installer is - * aspectj-{productName}-{version}.jar, where {productName} is the base name of - * the product directory
        • - *
        - *

        - * When run using main(String[]), all relevant Ant libraries and properties must - * be defined. - *

        - * Written to compile standalone. Refactor if using utils, bridge, etc. - */ -public abstract class Builder { - - /** - * This has only weak forms for build instructions needed: - resource - * pattern - compiler selection and control - * - * Both assumed and generated paths are scattered; see XXXNameLiteral and - * XXXFileLiteral. - * - * Builder is supposed to be thread-safe, but currently caches build - * properties to tunnel for filters. hmm. - */ - - public static final String RESOURCE_PATTERN; - - public static final String BINARY_SOURCE_PATTERN; - - public static final String ALL_PATTERN; - - /** enable copy filter semantics */ - protected static final boolean FILTER_ON = true; - - /** disable copy filter semantics */ - protected static final boolean FILTER_OFF = false; - - /** define libraries to skip as comma-delimited values for this key */ - private static final String SKIP_LIBRARIES_KEY = "skip.libraries"; - - /** List (String) names of libraries to skip during assembly */ - private static final List SKIP_LIBRARIES; - - private static final String ERROR_KEY = "error loading properties"; - - private static final Properties PROPS; - static { - PROPS = new Properties(); - List skips = Collections.emptyList(); - String resourcePattern = "**/*.txt,**/*.rsc,**/*.gif,**/*.properties"; - String allPattern = "**/*"; - String binarySourcePattern = "**/*.rsc,**/*.gif,**/*.jar,**/*.zip"; - String name = Builder.class.getName().replace('.', '/') + ".properties"; - try { - InputStream in = Builder.class.getClassLoader() - .getResourceAsStream(name); - PROPS.load(in); - allPattern = PROPS.getProperty("all.pattern"); - resourcePattern = PROPS.getProperty("resource.pattern"); - binarySourcePattern = PROPS.getProperty("binarySource.pattern"); - skips = commaStrings(PROPS.getProperty(SKIP_LIBRARIES_KEY)); - } catch (Throwable t) { - if (t instanceof ThreadDeath) { - throw (ThreadDeath) t; - } - String m = "error loading " + name + ": " + t.getClass() + " " + t; - PROPS.setProperty(ERROR_KEY, m); - } - SKIP_LIBRARIES = skips; - ALL_PATTERN = allPattern; - BINARY_SOURCE_PATTERN = binarySourcePattern; - RESOURCE_PATTERN = resourcePattern; - } - - /** - * Splits strings into an unmodifable List of String using - * comma as the delimiter and trimming whitespace from the result. - * - * @param text - * String to split. - * @return unmodifiable List (String) of String delimited by comma in text - */ - public static List commaStrings(String text) { - if ((null == text) || (0 == text.length())) { - return Collections.EMPTY_LIST; - } - List strings = new ArrayList(); - StringTokenizer tok = new StringTokenizer(text, ","); - while (tok.hasMoreTokens()) { - String token = tok.nextToken().trim(); - if (0 < token.length()) { - strings.add(token); - } - } - return Collections.unmodifiableList(strings); - } - - /** - * Map delivered-jar name to created-module name - * - * @param jarName - * the String (lowercased) of the jar/zip to map - */ - private String moduleAliasFor(String jarName) { - String result = PROPS.getProperty("alias." + jarName, jarName); - if (verbose && result.equals(jarName)) { - String m = "expected alias for " + jarName; - handler.error(m + PROPS.getProperty(ERROR_KEY, "")); - } - return result; - } - - protected final Messager handler; - - protected boolean buildingEnabled; - - private final File tempDir; - - private final ArrayList tempFiles; - - private final boolean useEclipseCompiles; - - protected boolean verbose; - - protected Builder(File tempDir, boolean useEclipseCompiles, Messager handler) { - Util.iaxIfNull(handler, "handler"); - this.useEclipseCompiles = useEclipseCompiles; - this.handler = handler; - this.tempFiles = new ArrayList(); - if ((null == tempDir) || !tempDir.canWrite() || !tempDir.isDirectory()) { - this.tempDir = Util.makeTempDir("Builder"); - } else { - this.tempDir = tempDir; - } - buildingEnabled = true; - } - - /** tell builder to stop or that it's ok to run */ - public void setBuildingEnabled(boolean enabled) { - buildingEnabled = enabled; - } - - public void setVerbose(boolean verbose) { - this.verbose = verbose; - } - - private void verifyBuildSpec(BuildSpec buildSpec) { - if (null == buildSpec.productDir) { // ensure module properties - // derive moduleDir from baseDir + module - if (null == buildSpec.moduleDir) { - if (null == buildSpec.baseDir) { - throw new BuildException("require baseDir or moduleDir"); - } else if (null == buildSpec.module) { - throw new BuildException("require module with baseDir"); - } else { - if (null == buildSpec.baseDir) { - buildSpec.baseDir = new File("."); // user.home? - } - buildSpec.moduleDir = new File(buildSpec.baseDir, - buildSpec.module); - } - } else if (null == buildSpec.baseDir) { - // derive baseDir from moduleDir parent - buildSpec.baseDir = buildSpec.moduleDir.getParentFile(); - // rule: base is parent - if (null == buildSpec.baseDir) { - buildSpec.baseDir = new File("."); // user.home? - } - handler.log("Builder using derived baseDir: " - + buildSpec.baseDir); - } - Util.iaxIfNotCanReadDir(buildSpec.moduleDir, "moduleDir"); - if (null == buildSpec.module) { - // derive module name from directory - buildSpec.module = buildSpec.moduleDir.getName(); - if (null == buildSpec.module) { - throw new BuildException("no name, even from " - + buildSpec.moduleDir); - } - } - } - } - - /** - * Find the Result (and hence Module and Modules) for this BuildSpec. - */ - protected Result specifyResultFor(BuildSpec buildSpec) { - if (buildSpec.trimTesting - && (-1 != buildSpec.module.indexOf("testing"))) { // XXXNameLiteral - String warning = "Warning - cannot trimTesting for testing modules: "; - handler.log(warning + buildSpec.module); - } - Messager handler = new Messager(); - Modules modules = new Modules(buildSpec.baseDir, buildSpec.jarDir, - handler); - - final Module moduleToBuild = modules.getModule(buildSpec.module); - Kind kind = Result.kind(buildSpec.trimTesting, - buildSpec.assembleAll); - return moduleToBuild.getResult(kind); - } - - public final boolean build(BuildSpec buildSpec) { - if (!buildingEnabled) { - return false; - } - verifyBuildSpec(buildSpec); - - if (null != buildSpec.productDir) { - return buildProduct(buildSpec); - } - Result result = specifyResultFor(buildSpec); - ArrayList errors = new ArrayList(); - try { - return buildAll(result, errors); - } finally { - if (0 < errors.size()) { - String label = "error building " + buildSpec + ": "; - for (Iterator iter = errors.iterator(); iter.hasNext();) { - String m = label + iter.next(); - handler.error(m); - } - } - } - } - - /** - * Clean up any temporary files, etc. after build completes - */ - public boolean cleanup() { - boolean noErr = true; - for (ListIterator iter = tempFiles.listIterator(); iter.hasNext();) { - File file = (File) iter.next(); - if (!Util.deleteContents(file) || !file.delete()) { - if (noErr) { - noErr = false; - } - handler.log("unable to clean up " + file); - } - } - return noErr; - } - - protected final boolean isLogging() { - return (verbose && (null != this.handler)); - } - - protected Result[] skipUptodate(Result[] results) { - if (null == results) { - return new Result[0]; - } - Result[] done = new Result[results.length]; - int to = 0; - for (int i = 0; i < done.length; i++) { - if ((null != results[i]) && results[i].outOfDate()) { - done[to++] = results[i]; - } - } - if (to < results.length) { - Result[] newdone = new Result[to]; - System.arraycopy(done, 0, newdone, 0, newdone.length); - done = newdone; - } - return done; - } - - /** - * Build a result with all antecedants. - * - * @param result - * the Result to build - * @param errors - * the List sink for errors, if any - * @return false after successful build, when module jar should exist - */ - protected final boolean buildAll(Result result, List errors) { - Result[] buildList = skipUptodate(getAntecedantResults(result)); - ArrayList doneList = new ArrayList(); - if ((null != buildList) && (0 < buildList.length)) { - if (isLogging()) { - handler.log("modules to build: " + Arrays.asList(buildList)); - } - for (int i = 0; i < buildList.length; i++) { - Result required = buildList[i]; - if (!buildingEnabled) { - return false; - } - String requiredName = required.getName(); - if (!doneList.contains(requiredName)) { - doneList.add(requiredName); - if (!buildOnly(required, errors)) { - return false; - } - } - } - } - return true; - } - - /** - * Build a module but no antecedants. - * - * @param module - * the Module to build - * @param errors - * the List sink for errors, if any - * @return false after successful build, when module jar should exist - */ - protected final boolean buildOnly(Result result, List errors) { - if (!result.outOfDate()) { - return true; - } - if (isLogging()) { - handler.log("building " + result); - } - if (!buildingEnabled) { - return false; - } - if (result.getKind().assemble) { - return assembleAll(result, handler); - } - Module module = result.getModule(); - final File classesDir; - if (useEclipseCompiles) { - classesDir = new File(module.moduleDir, "bin"); // FileLiteral - } else { - String name = "classes-" + System.currentTimeMillis(); - classesDir = new File(tempDir, name); - } - if (verbose) { - handler.log("buildOnly " + module); - } - try { - return (compile(result, classesDir,useEclipseCompiles, errors)) - && assemble(result, classesDir, errors); - } finally { - if (!useEclipseCompiles && !Util.delete(classesDir)) { - errors.add("buildOnly unable to delete " + classesDir); - } - } - } - - /** - * Register temporary file or directory to be deleted when the build is - * complete, even if an Exception is thrown. - */ - protected void addTempFile(File tempFile) { - if (null != tempFile) { - tempFiles.add(tempFile); - } - } - - /** - * Build product by discovering any modules to build, building those, - * assembling the product distribution, and optionally creating an installer - * for it. - * - * @return true on success - */ - protected final boolean buildProduct(BuildSpec buildSpec) - throws BuildException { - Util.iaxIfNull(buildSpec, "buildSpec"); - - if (!buildSpec.trimTesting) { - buildSpec.trimTesting = true; - handler.log("testing trimmed for " + buildSpec); - } - Util.iaxIfNotCanReadDir(buildSpec.productDir, "productDir"); - Util.iaxIfNotCanReadDir(buildSpec.baseDir, "baseDir"); - Util.iaxIfNotCanWriteDir(buildSpec.distDir, "distDir"); - - // ---- discover modules to build, and build them - Modules modules = new Modules(buildSpec.baseDir, buildSpec.jarDir, - handler); - ProductModule[] productModules = discoverModules(buildSpec.productDir, - modules); - for (int i = 0; i < productModules.length; i++) { - if (buildSpec.verbose) { - handler.log("building product module " + productModules[i]); - } - if (!buildProductModule(productModules[i])) { - return false; - } - } - if (buildSpec.verbose) { - handler.log("assembling product module for " + buildSpec); - } - - // ---- assemble product distribution - final String productName = buildSpec.productDir.getName(); - final File targDir = new File(buildSpec.distDir, productName); - final String targDirPath = targDir.getPath(); - if (targDir.canWrite()) { - Util.deleteContents(targDir); - } - - if (!targDir.canWrite() && !targDir.mkdirs()) { - if (buildSpec.verbose) { - handler.log("buildProduct unable to create " + targDir); - } - return false; - } - - // copy non-binaries (with filter) - File distDir = new File(buildSpec.productDir, "dist"); - if (!copyNonBinaries(buildSpec, distDir, targDir)) { - return false; - } - - // copy binaries (but not module flag files) - String excludes = null; - { - StringBuffer buf = new StringBuffer(); - for (int i = 0; i < productModules.length; i++) { - if (0 < buf.length()) { - buf.append(","); - } - buf.append(productModules[i].relativePath); - } - if (0 < buf.length()) { - excludes = buf.toString(); - } - } - - if (!copyBinaries(buildSpec, distDir, targDir, excludes)) { - return false; - } - - // copy binaries associated with module flag files - for (int i = 0; i < productModules.length; i++) { - final ProductModule product = productModules[i]; - final Kind kind = Result.kind(Result.NORMAL, product.assembleAll); - Result result = product.module.getResult(kind); - String targPath = Util.path(targDirPath, product.relativePath); - File jarFile = result.getOutputFile(); - copyFile(jarFile, new File(targPath), FILTER_OFF); - } - handler.log("created product in " + targDir); - - // ---- create installer - if (buildSpec.createInstaller) { - return buildInstaller(buildSpec, targDirPath); - } else { - return true; - } - } - - protected boolean copyBinaries(BuildSpec buildSpec, File distDir, - File targDir, String excludes) { - String includes = Builder.BINARY_SOURCE_PATTERN; - return copyFiles(distDir, targDir, includes, excludes, FILTER_OFF); - } - - /** - * filter-copy everything but the binaries - */ - protected boolean copyNonBinaries(BuildSpec buildSpec, File distDir, - File targDir) { - String excludes = Builder.BINARY_SOURCE_PATTERN; - String includes = Builder.ALL_PATTERN; - return copyFiles(distDir, targDir, includes, excludes, FILTER_ON); - } - - protected final boolean buildProductModule(ProductModule module) { - ArrayList errors = new ArrayList(); - try { - Kind productKind = Result.kind(Result.NORMAL, Result.ASSEMBLE); - Result result = module.module.getResult(productKind); - return buildAll(result, errors); - } finally { - for (Iterator iter = errors.iterator(); iter.hasNext();) { - handler.error("error building " + module + ": " + iter.next()); - } - } - } - - /** - * Discover any modules that might need to be built in order to assemble the - * product distribution. This interprets empty .jar files as module - * deliverables. - */ - protected ProductModule[] discoverModules(File productDir, Modules modules) { - final ArrayList found = new ArrayList(); - FileFilter filter = new FileFilter() {// empty jar files - public boolean accept(File file) { - if ((null != file) && file.canRead() - && file.getPath().endsWith(".jar") // XXXFileLiteral - && (0l == file.length())) { - found.add(file); - } - return true; - } - }; - Util.visitFiles(productDir, filter); - ArrayList results = new ArrayList(); - for (File file: found) { - String jarName = moduleAliasFor(file.getName().toLowerCase()); - if (jarName.endsWith(".jar") || jarName.endsWith(".zip")) { // XXXFileLiteral - jarName = jarName.substring(0, jarName.length() - 4); - } else { - handler.log("can only replace .[jar|zip]: " + file); - // XXX error? - } - boolean assembleAll = jarName.endsWith("-all"); - // XXXFileLiteral - String name = (!assembleAll ? jarName : jarName.substring(0, - jarName.length() - 4)); - Module module = modules.getModule(name); - if (null == module) { - handler.log("unable to find module for " + file); - } else { - results.add(new ProductModule(productDir, file, module, - assembleAll)); - } - } - return (ProductModule[]) results.toArray(new ProductModule[0]); - } - - /** - * Subclasses should query whether to include library files in the assembly. - * - * @param module - * the Module being built - * @param libraries - * the List of File path to the jar to consider assembling - * @return true if the jar should be included, false otherwise. - */ - protected void removeLibraryFilesToSkip(Module module, List libraries) { - for (ListIterator liter = libraries.listIterator(); liter.hasNext();) { - File library = (File) liter.next(); - final String fname = library.getName(); - if (null != fname) { - for (Iterator iter = SKIP_LIBRARIES.iterator(); iter.hasNext();) { - String name = (String) iter.next(); - if (fname.equals(name)) { - liter.remove(); - break; - } - } - } - } - } - - /** - * @return String[] names of results to build for this module - */ - abstract protected Result[] getAntecedantResults(Result toBuild); - - /** - * Compile module classes to classesDir, saving String errors. - * - * @param module - * the Module to compile - * @param classesDir - * the File directory to compile to - * @param useExistingClasses - * if true, don't recompile and ensure classes are available - * @param errors - * the List to add error messages to - */ - abstract protected boolean compile(Result result, File classesDir, - boolean useExistingClasses, List errors); - - /** - * Assemble the module distribution from the classesDir, saving String - * errors. - * - * @see #removeLibraryFilesToSkip(Module, File) - */ - abstract protected boolean assemble(Result result, File classesDir, - List errors); - - /** - * Assemble the module distribution from the classesDir and all - * antecendants, saving String errors. - * - * @see #removeLibraryFilesToSkip(Module, File) - */ - abstract protected boolean assembleAll(Result result, Messager handler); - - /** - * Generate the installer for this product to targDirPath - */ - abstract protected boolean buildInstaller(BuildSpec buildSpec, - String targDirPath); - - /** - * Copy fromFile to toFile, optionally filtering contents - */ - abstract protected boolean copyFile(File fromFile, File toFile, - boolean filter); - - /** - * Copy toDir any fromDir included files without any exluded files, - * optionally filtering contents. - * - * @param fromDir - * File dir to read from - error if not readable - * @param toDir - * File dir to write to - error if not writable - * @param included - * String Ant pattern of included files (if null, include all) - * @param excluded - * String Ant pattern of excluded files (if null, exclude none) - * @param filter - * if FILTER_ON, then filter file contents using global - * token/value pairs - */ - abstract protected boolean copyFiles(File fromDir, File toDir, - String included, String excluded, boolean filter); -} diff --git a/build/src/org/aspectj/internal/tools/build/Builder.properties b/build/src/org/aspectj/internal/tools/build/Builder.properties deleted file mode 100644 index 3838514f4..000000000 --- a/build/src/org/aspectj/internal/tools/build/Builder.properties +++ /dev/null @@ -1,20 +0,0 @@ -# documented in build/readme-build-module.html - -# alias product/dist/lib/{name} to project jar -# used by Builder.moduleAliasFor(String) -alias.aspectjtools.jar=ajbrowser-all.jar -alias.aspectjrt.jar=aspectj5rt-all.jar -alias.aspectjweaver.jar=loadtime5-all.jar -# alias.aspectjlib.jar=org.aspectj.lib.jar -alias.org.aspectj.matcher.jar=org.aspectj.matcher-all.jar - -# libraries to avoid bundling (IBM JRE different, etc.) -# see build/readme-build-module.html, Builder.SKIP_LIBRARIES -skip.libraries=asm-3.1.jar,core.jar,graphics.jar,ant.jar,tools.jar,bcel-verifier.jar,asm-3.1.jar,junit.jar,xml-apis.jar,xercesImpl.jar,commons.jar,jrockit.jar - -# Ant patterns to gather and omit resources -# files copied during module jar assembly -resource.pattern=**/*.txt,**/*.rsc,**/*.gif,**/*.properties,**/*.xml,**/*.dtd -# files not filtered when copied during product assembly -binarySource.pattern=**/*.rsc,**/*.gif,**/*.jar,**/*.zip -all.pattern=**/* diff --git a/build/src/org/aspectj/internal/tools/build/Messager.java b/build/src/org/aspectj/internal/tools/build/Messager.java deleted file mode 100644 index 4752fd645..000000000 --- a/build/src/org/aspectj/internal/tools/build/Messager.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ******************************************************************* - * Copyright (c) 1999-2001 Xerox Corporation, - * 2002 Palo Alto Research Center, Incorporated (PARC). - * All rights reserved. - * This program and the accompanying materials are made available - * under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Xerox/PARC initial implementation - * ******************************************************************/ - - -package org.aspectj.internal.tools.build; - -/** logging stub XXX replace */ -public class Messager { - public Messager() { - } - public boolean log(String s) { - System.out.println(s); - return true; - } - - public boolean error(String s) { - System.out.println(s); - return true; - } - - public boolean logException(String context, Throwable thrown) { - System.err.println(context); - thrown.printStackTrace(System.err); - return true; - } -} - - - - - - - diff --git a/build/src/org/aspectj/internal/tools/build/Module.java b/build/src/org/aspectj/internal/tools/build/Module.java deleted file mode 100644 index 3f0afbfd9..000000000 --- a/build/src/org/aspectj/internal/tools/build/Module.java +++ /dev/null @@ -1,754 +0,0 @@ -/* ******************************************************************* - * Copyright (c) 1999-2001 Xerox Corporation, - * 2002 Palo Alto Research Center, Incorporated (PARC). - * All rights reserved. - * This program and the accompanying materials are made available - * under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Xerox/PARC initial implementation - * ******************************************************************/ - -package org.aspectj.internal.tools.build; - -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Properties; -import java.util.StringTokenizer; - -import org.aspectj.internal.tools.build.Result.Kind; -import org.aspectj.internal.tools.build.Util.OSGIBundle; -import org.aspectj.internal.tools.build.Util.OSGIBundle.RequiredBundle; - - -/** - * This represents an (eclipse) build module/unit used by a Builder to compile - * classes and/or assemble zip file of classes, optionally with all antecedants. - * This implementation infers attributes from two files in the module directory: - *

          - *
        • an Eclipse project .classpath file containing required - * libraries and modules (collectively, "antecedants")
        • - *
        • a file {moduleName}.mf.txt is taken as the manifest of - * any .jar file produced, after filtering.
        • - *
        - * - * @see Builder - * @see Modules#getModule(String) - */ -public class Module { - private static final String[] ATTS = new String[] { "exported", "kind", - "path", "sourcepath" }; - -// private static final int getATTSIndex(String key) { -// for (int i = 0; i < ATTS.length; i++) { -// if (ATTS[i].equals(key)) -// return i; -// } -// return -1; -// } - - /** - * @return true if file is null or cannot be read or was last modified after - * time - */ - private static boolean outOfDate(long time, File file) { - return ((null == file) || !file.canRead() || (file.lastModified() > time)); - } - - /** @return all source files under srcDir */ - private static Iterator sourceFiles(File srcDir) { - ArrayList result = new ArrayList(); - sourceFiles(srcDir, result); - return result.iterator(); - } - - private static void sourceFiles(File srcDir, List result) { - if ((null == srcDir) || !srcDir.canRead() || !srcDir.isDirectory()) { - return; - } - File[] files = srcDir.listFiles(); - for (int i = 0; i < files.length; i++) { - if (files[i].isDirectory()) { - sourceFiles(files[i], result); - } else if (isSourceFile(files[i])) { - result.add(files[i]); - } - } - } - - private static void addIfNew(List source, List sink) { - for (File item: source) { - if (!sink.contains(item)) { - sink.add(item); - } - } - } - - /** - * Recursively find antecedant jars. - * - * @see findKnownJarAntecedants() - */ - static void doFindJarRequirements(Result result, List known) { - Util.iaxIfNull(result, "result"); - Util.iaxIfNull(known, "known"); - addIfNew(result.getLibJars(), known); - addIfNew(result.getExportedLibJars(), known); - Result[] reqs = result.getRequired(); - for (int i = 0; i < reqs.length; i++) { - Result requiredResult = reqs[i]; - File requiredJar = requiredResult.getOutputFile(); - if (!known.contains(requiredJar)) { - known.add(requiredJar); - doFindJarRequirements(requiredResult, known); - } - } - } - - /** @return true if this is a source file */ - private static boolean isSourceFile(File file) { - String path = file.getPath(); - return (path.endsWith(".java") || path.endsWith(".aj")); // XXXFileLiteral - } - -// /** @return List of File of any module or library jar ending with suffix */ -// private static ArrayList findJarsBySuffix(String suffix, Kind kind, -// List libJars, List required) { -// ArrayList result = new ArrayList(); -// if (null != suffix) { -// // library jars -// for (Iterator iter = libJars.iterator(); iter.hasNext();) { -// File file = (File) iter.next(); -// if (file.getPath().endsWith(suffix)) { -// result.add(file); -// } -// } -// // module jars -// for (Iterator iter = required.iterator(); iter.hasNext();) { -// Module module = (Module) iter.next(); -// Result moduleResult = module.getResult(kind); -// File file = moduleResult.getOutputFile(); -// if (file.getPath().endsWith(suffix)) { -// result.add(file); -// } -// } -// } -// return result; -// } - - public final boolean valid; - - public final File moduleDir; - - public final String name; - - /** reference back to collection for creating required modules */ - private final Modules modules; - - private final Result release; - - private final Result test; - - private final Result testAll; - - private final Result releaseAll; - - /** path to output jar - may not exist */ - private final File moduleJar; - - /** File list of library jars */ - private final List libJars; - - /** List of classpath variables */ - private final List classpathVariables; - - /** - * List of library jars exported to clients (duplicates some libJars - * entries) - */ - private final List exportedLibJars; - - /** File list of source directories */ - private final List srcDirs; - - /** properties from the modules {name}.properties file */ - private final Properties properties; - - /** List of required modules */ - private final List requiredModules; - - /** logger */ - private final Messager messager; - - Module(File moduleDir, File jarDir, String name, Modules modules, - Messager messager) { - Util.iaxIfNotCanReadDir(moduleDir, "moduleDir"); - Util.iaxIfNotCanReadDir(jarDir, "jarDir"); - Util.iaxIfNull(name, "name"); - Util.iaxIfNull(modules, "modules"); - this.moduleDir = moduleDir; - this.libJars = new ArrayList(); - this.exportedLibJars = new ArrayList(); - this.requiredModules = new ArrayList(); - this.srcDirs = new ArrayList(); - this.classpathVariables = new ArrayList(); - this.properties = new Properties(); - this.name = name; - this.modules = modules; - this.messager = messager; - this.moduleJar = new File(jarDir, name + ".jar"); - this.release = new Result(Result.RELEASE, this, jarDir); - this.releaseAll = new Result(Result.RELEASE_ALL, this, jarDir); - this.test = new Result(Result.TEST, this, jarDir); - this.testAll = new Result(Result.TEST_ALL, this, jarDir); - valid = init(); - } - - - /** @return Modules registry of known modules, including this one */ - public Modules getModules() { - return modules; - } - - /** - * @param kind - * the Kind of the result to recalculate - * @param recalculate - * if true, then force recalculation - * @return true if the target jar for this module is older than any source - * files in a source directory or any required modules or any - * libraries or if any libraries or required modules are missing - */ - public static boolean outOfDate(Result result) { - File outputFile = result.getOutputFile(); - if (!(outputFile.exists() && outputFile.canRead())) { - return true; - } - final long time = outputFile.lastModified(); - File file; - for (Iterator iter = result.getSrcDirs().iterator(); iter.hasNext();) { - File srcDir = iter.next(); - for (Iterator srcFiles = sourceFiles(srcDir); srcFiles.hasNext();) { - file = srcFiles.next(); - if (outOfDate(time, file)) { - return true; - } - } - } - // required modules - Result[] reqs = result.getRequired(); - for (int i = 0; i < reqs.length; i++) { - Result requiredResult = reqs[i]; - file = requiredResult.getOutputFile(); - if (outOfDate(time, file)) { - return true; - } - } - // libraries - for (Iterator iter = result.getLibJars().iterator(); iter.hasNext();) { - file = (File) iter.next(); - if (outOfDate(time, file)) { - return true; - } - } - return false; - } - - - - public String toString() { - return name; - } - - public String toLongString() { - return "Module [name=" + name + ", srcDirs=" + srcDirs + ", required=" - + requiredModules + ", moduleJar=" + moduleJar + ", libJars=" - + libJars + "]"; - } - - public Result getResult(Kind kind) { - return kind.assemble ? (kind.normal ? releaseAll : testAll) - : (kind.normal ? release : test); - } - - List srcDirs(Result result) { - myResult(result); - return srcDirs; - } - - List libJars(Result result) { - myResult(result); - return libJars; - } - - List classpathVariables(Result result) { - myResult(result); - return classpathVariables; - } - - List exportedLibJars(Result result) { - myResult(result); - return exportedLibJars; - } - - List requiredModules(Result result) { - myResult(result); - return requiredModules; - } - - private void myResult(Result result) { - if ((null == result) || this != result.getModule()) { - throw new IllegalArgumentException("not my result: " + result + ": " + this); - } - } - - private boolean init() { - boolean cp = initClasspath(); - boolean mf = initManifest(); - if (!cp && !mf) { - return false; - } - return initProperties() && reviewInit() && initResults(); - } - - /** read OSGI manifest.mf file XXX hacked */ - private boolean initManifest() { - File metaInf = new File(moduleDir, "META-INF"); - if (!metaInf.canRead() || !metaInf.isDirectory()) { - return false; - } - File file = new File(metaInf, "MANIFEST.MF"); // XXXFileLiteral - if (!file.exists()) { - return false; // ok, not OSGI - } - InputStream fin = null; - OSGIBundle bundle = null; - try { - fin = new FileInputStream(file); - bundle = new OSGIBundle(fin); - } catch (IOException e) { - messager.logException("IOException reading " + file, e); - return false; - } finally { - Util.closeSilently(fin); - } - RequiredBundle[] bundles = bundle.getRequiredBundles(); - for (int i = 0; i < bundles.length; i++) { - RequiredBundle required = bundles[i]; - update("src", "/" + required.name, required.text, false); - } - String[] libs = bundle.getClasspath(); - for (int i = 0; i < libs.length; i++) { - update("lib", libs[i], libs[i], false); - } - - return true; - } - - /** read eclipse .classpath file XXX line-oriented hack */ - private boolean initClasspath() { - // meaning testsrc directory, junit library, etc. - File file = new File(moduleDir, ".classpath"); // XXXFileLiteral - if (!file.exists()) { - return false; // OSGI??? - } - FileReader fin = null; - try { - fin = new FileReader(file); - BufferedReader reader = new BufferedReader(fin); - String line; - XMLItem item = new XMLItem("classpathentry", new ICB()); - while (null != (line = reader.readLine())) { - line = line.trim(); - // dumb - only handle comment-only lines - if (!line.startsWith("\"="; - StringTokenizer st = new StringTokenizer(line, DELIM, true); - ArrayList result = new ArrayList(); - StringBuffer quote = new StringBuffer(); - boolean inQuote = false; - while (st.hasMoreTokens()) { - String s = st.nextToken(); - if ((1 == s.length()) && (-1 != DELIM.indexOf(s))) { - if ("\"".equals(s)) { // end quote (or escaped) - if (inQuote) { - inQuote = false; - quote.append("\""); - result.add(quote.toString()); - quote.setLength(0); - } else { - quote.append("\""); - inQuote = true; - } - } else { - result.add(s); - } - } else { // not a delimiter - if (inQuote) { - quote.append(s); - } else { - result.add(s); - } - } - } - return (String[]) result.toArray(new String[0]); - } - - public void acceptLine(String line) { - String[] tokens = tokenize(line); - for (int i = 0; i < tokens.length; i++) { - next(tokens[i]); - } - } - - private Properties attributesToProperties() { - Properties result = new Properties(); - for (int i = 0; i < attributes.length; i++) { - String a = attributes[i]; - if (null != a) { - result.setProperty(ATTS[i], a); - } - } - return result; - } - - void errorIfNotNull(String name, String value) { - if (null != value) { - error("Did not expect " + name + ": " + value); - } - } - - void errorIfNull(String name, String value) { - if (null == value) { - error("expected value for " + name); - } - } - - boolean activeEntity() { - return targetEntity.equals(entityName); - } - - /** - * Assumes that comments and "".equals(s)) { - errorIfNull("entityName", entityName); - if ("/".equals(attributeName)) { - attributeName = null; - } else { - errorIfNotNull("attributeName", attributeName); - } - if (activeEntity()) { - callback.end(attributesToProperties()); - } - entityName = null; - } else if ("=".equals(s)) { - errorIfNull("entityName", entityName); - errorIfNull("attributeName", attributeName); - } else if (s.startsWith("\"")) { - errorIfNull("entityName", entityName); - errorIfNull("attributeName", attributeName); - writeAttribute(attributeName, s); - attributeName = null; - } else { - if (null == entityName) { - reset(); - entityName = s; - } else if (null == attributeName) { - attributeName = s; - } else { - System.out - .println("unknown state - not value, attribute, or entity: " - + s); - } - } - } - - void readAttribute(String s) { - for (int i = 0; i < ATTS.length; i++) { - if (s.equals(ATTS[i])) { - attributes[i] = ATT_STARTED; - break; - } - } - } - - void writeAttribute(String name, String value) { - for (int i = 0; i < ATTS.length; i++) { - if (name.equals(ATTS[i])) { - if (!value.startsWith("\"") || !value.endsWith("\"")) { - error("bad attribute value: " + value); - } - value = value.substring(1, value.length() - 1); - attributes[i] = value; - return; - } - } - } - - void error(String s) { - throw new Error(s + " at input " + input); - } - } -} diff --git a/build/src/org/aspectj/internal/tools/build/Modules.java b/build/src/org/aspectj/internal/tools/build/Modules.java deleted file mode 100644 index 83686820e..000000000 --- a/build/src/org/aspectj/internal/tools/build/Modules.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ******************************************************************* - * Copyright (c) 1999-2001 Xerox Corporation, - * 2002 Palo Alto Research Center, Incorporated (PARC). - * All rights reserved. - * This program and the accompanying materials are made available - * under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Xerox/PARC initial implementation - * ******************************************************************/ - - -package org.aspectj.internal.tools.build; - -import java.io.File; -import java.util.Hashtable; - -/** - * Registration and factory for modules - * @see Module - * @see Builder - */ -public class Modules { - - private final Hashtable modules = new Hashtable(); - public final File baseDir; - public final File jarDir; - private final Messager handler; - - public Modules(File baseDir, File jarDir, Messager handler) { - this.baseDir = baseDir; - this.jarDir = jarDir; - this.handler = handler; - Util.iaxIfNotCanReadDir(baseDir, "baseDir"); - Util.iaxIfNotCanReadDir(jarDir, "jarDir"); - Util.iaxIfNull(handler, "handler"); - } - - - /** - * Get module associated with name. - * @return fail if unable to find or create module {name}. - */ - public Module getModule(String name) { - if (null == name) { - return null; - } - Module result = (Module) modules.get(name); - if (null == result) { - File moduleDir = new File(baseDir, name); - if (!Util.canReadDir(moduleDir)) { - handler.error("not a module: " + name); - } else { - result = new Module(moduleDir, jarDir, name, this, handler); - if (result.valid) { - modules.put(name, result); - } else { - handler.error("invalid module: " + result.toLongString()); - } - } - } - return result; - } -} \ No newline at end of file diff --git a/build/src/org/aspectj/internal/tools/build/ProductModule.java b/build/src/org/aspectj/internal/tools/build/ProductModule.java deleted file mode 100644 index c695a4f8e..000000000 --- a/build/src/org/aspectj/internal/tools/build/ProductModule.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ******************************************************************* - * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). - * All rights reserved. - * This program and the accompanying materials are made available - * under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Xerox/PARC initial implementation - * ******************************************************************/ -package org.aspectj.internal.tools.build; - -import java.io.File; - -/** - * Struct associating module with target product distribution jar - * and assembly instructions. - * When building product distributions, a zero-length jar file - * in the dist directory may signify a module to be built, - * renamed, and included in the distribution. - */ -public class ProductModule { - /** name of distribution directory in product directory */ - private static final String DIST = "dist"; - - /** top-level product directory being produced */ - public final File productDir; - - /** path to file in distribution template dir for this module jar */ - public final File replaceFile; - - /** relative path within distribution of this product module jar */ - public final String relativePath; - - /** the module jar is the file to replace */ - public final Module module; - - /** if true, assemble all when building module */ - public final boolean assembleAll; - - public ProductModule(File productDir, File replaceFile, Module module, boolean assembleAll) { - this.replaceFile = replaceFile; - this.module = module; - this.productDir = productDir; - this.assembleAll = assembleAll; - Util.iaxIfNull(module, "module"); - Util.iaxIfNotCanReadDir(productDir, "productDir"); - Util.iaxIfNotCanReadFile(replaceFile, "replaceFile"); - String productDirPath = productDir.getAbsolutePath(); - String replaceFilePath = replaceFile.getAbsolutePath(); - if (!replaceFilePath.startsWith(productDirPath)) { - String m = "\"" + replaceFilePath - + "\" does not start with \"" - + productDirPath - + "\""; - throw new IllegalArgumentException(m); - } - replaceFilePath = replaceFilePath.substring(1+productDirPath.length()); - if (!replaceFilePath.startsWith(DIST)) { - String m = "\"" + replaceFilePath - + "\" does not start with \"" + DIST + "\""; - throw new IllegalArgumentException(m); - } - relativePath = replaceFilePath.substring(1 + DIST.length()); - } - public String toString() { - return "" + module + " for " + productDir; - } -} diff --git a/build/src/org/aspectj/internal/tools/build/Result.java b/build/src/org/aspectj/internal/tools/build/Result.java deleted file mode 100644 index e12ba4e29..000000000 --- a/build/src/org/aspectj/internal/tools/build/Result.java +++ /dev/null @@ -1,387 +0,0 @@ -/* ******************************************************************* - * Copyright (c) 2005 Contributors. - * All rights reserved. - * This program and the accompanying materials are made available - * under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution and is available at - * http://eclipse.org/legal/epl-v10.html - * - * Contributors: - * Wes Isberg initial implementation - * ******************************************************************/ - -package org.aspectj.internal.tools.build; - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -/** - * Represents a prospective build result and any requirements for it. Used for - * [testing|normal][jar|assembled-jar|classesDir?]. - */ -public class Result { - public static final boolean NORMAL = true; - - public static final boolean ASSEMBLE = true; - - static final Kind RELEASE = new Kind("RELEASE", NORMAL, !ASSEMBLE); - - static final Kind RELEASE_ALL = new Kind("RELEASE_ALL", NORMAL, ASSEMBLE); - - static final Kind TEST = new Kind("TEST", !NORMAL, !ASSEMBLE); - - static final Kind TEST_ALL = new Kind("TEST_ALL", !NORMAL, ASSEMBLE); - - private static final Kind[] KINDS = { RELEASE, TEST, RELEASE_ALL, TEST_ALL }; - - private static final HashMap nameToResult = new HashMap(); - - public static boolean isTestingJar(String name) { - name = name.toLowerCase(); - return "junit.jar".equals(name); - } - - public static boolean isTestingDir(String name) { - name = name.toLowerCase(); - return (Util.Constants.TESTSRC.equals(name) || Util.Constants.JAVA5_TESTSRC - .equals(name)); - } - - public static boolean isTestingModule(Module module) { - String name = module.name.toLowerCase(); - return name.startsWith("testing") || "tests".equals(name); - } - - public static synchronized Result getResult(String name) { - if (null == name) { - throw new IllegalArgumentException("null name"); - } - return (Result) nameToResult.get(name); - } - - public static Result[] getResults(String[] names) { - if (null == names) { - return new Result[0]; - } - Result[] results = new Result[names.length]; - - for (int i = 0; i < results.length; i++) { - String name = names[i]; - if (null == name) { - String m = "no name at " + i + ": " + Arrays.asList(names); - throw new IllegalArgumentException(m); - } - Result r = Result.getResult(name); - if (null == r) { - String m = "no result [" + i + "]: " + name + ": " - + Arrays.asList(names); - throw new IllegalArgumentException(m); - } - results[i] = r; - } - return results; - - } - - public static Kind[] KINDS() { - Kind[] result = new Kind[KINDS.length]; - System.arraycopy(KINDS, 0, result, 0, result.length); - return result; - } - - public static void iaxUnlessNormal(Result result) { - if ((null == result) || !result.getKind().normal) { - throw new IllegalArgumentException("not normal: " + result); - } - } - - public static void iaxUnlessAssembly(Result result) { - if ((null == result) || !result.getKind().assemble) { - throw new IllegalArgumentException("not assembly: " + result); - } - } - - public static Kind kind(boolean normal, boolean assemble) { - return (normal == NORMAL ? (assemble == ASSEMBLE ? RELEASE_ALL - : RELEASE) : (assemble == ASSEMBLE ? TEST_ALL : TEST)); - } - - public static class Kind { - final String name; - - final boolean normal; - - final boolean assemble; - - private Kind(String name, boolean normal, boolean assemble) { - this.name = name; - this.normal = normal; - this.assemble = assemble; - } - - public final boolean isAssembly() { - return assemble; - } - - public final boolean isNormal() { - return normal; - } - - public final String toString() { - return name; - } - } - - /** path to output jar - may not exist */ - private final File outputFile; - - /** List of required Result */ - private final List requiredResults; - - /** List of library jars */ - private final List libJars; - - /** List of classpath variables */ - private final List classpathVariables; - - transient String toLongString; - - /** - * List of library jars exported to clients (duplicates some libJars - * entries) - */ - private final List exportedLibJars; - - /** List of source directories */ - private final List srcDirs; - - /** true if this has calculated List fields. */ - private boolean requiredDone; - - /** true if this has been found to be out of date */ - private boolean outOfDate; - - /** true if we have calculated whether this is out of date */ - private boolean outOfDateSet; - - private final Kind kind; - - private final Module module; - - private final String name; - - Result(Kind kind, Module module, File jarDir) { - this.kind = kind; - this.module = module; - this.libJars = new ArrayList(); - this.exportedLibJars = new ArrayList(); - this.srcDirs = new ArrayList(); - this.classpathVariables = new ArrayList(); - this.requiredResults = new ArrayList(); - String name = module.name; - if (!kind.normal) { - name += "-test"; - } - if (kind.assemble) { - name += "-all"; - } - this.name = name; - this.outputFile = new File(jarDir, name + ".jar"); - nameToResult.put(name, this); - } - - public String getName() { - return name; - } - - public File getOutputFile() { - return outputFile; - } - - public void clearOutOfDate() { - outOfDateSet = false; - outOfDate = false; - } - - public boolean outOfDate() { - if (!outOfDateSet) { - outOfDate = Module.outOfDate(this); - outOfDateSet = true; - } - return outOfDate; - } - - /** @return List (File) of jar's required */ - public List findJarRequirements() { - ArrayList result = new ArrayList(); - Module.doFindJarRequirements(this, result); - return result; - } - - /** @return unmodifiable List of String classpath variables */ - public List getClasspathVariables() { - return safeList(classpathVariables); - } - - // - /** @return unmodifiable List of required modules String names */ - public Result[] getRequired() { - return safeResults(requiredResults); - } - - /** - * @return unmodifiable list of exported library files, guaranteed readable - */ - public List getExportedLibJars() { - return safeList(exportedLibJars); - } - - /** - * @return unmodifiable list of required library files, guaranteed readable - */ - public List getLibJars() { - requiredDone(); - return safeList(libJars); - } - - /** - * @return unmodifiable list of required library files, guaranteed readable - */ - // public List getMerges() { - // requiredDone(); - // return safeList(merges); - // } - /** @return unmodifiable list of source directories, guaranteed readable */ - public List getSrcDirs() { - return safeList(srcDirs); - } - - public Module getModule() { - return module; - } - - public Kind getKind() { - return kind; - } - - public String toLongString() { - if (null == toLongString) { - toLongString = name + "[outputFile=" + outputFile - + ", requiredResults=" + requiredResults + ", srcDirs=" - + srcDirs + ", libJars=" + libJars + "]"; - } - return toLongString; - } - - public String toString() { - return name; - } - - private List safeList(List l) { - requiredDone(); - return Collections.unmodifiableList(l); - } - - private Result[] safeResults(List list) { - requiredDone(); - if (null == list) { - return new Result[0]; - } - return (Result[]) list.toArray(new Result[0]); - } - - private void initSrcDirs() { - srcDirs.addAll(getModule().srcDirs(this)); - if (getKind().normal) { - // trim testing source directories - for (ListIterator iter = srcDirs.listIterator(); iter.hasNext();) { - File srcDir = iter.next(); - if (isTestingDir(srcDir.getName())) { - iter.remove(); - } - } - } - } - - private void initLibJars() { - libJars.addAll(getModule().libJars(this)); - if (getKind().normal && !isTestingModule(getModule())) { - // trim testing libraries - for (ListIterator iter = libJars.listIterator(); iter.hasNext();) { - File libJar = iter.next(); - if (isTestingJar(libJar.getName())) { - iter.remove(); - } - } - } - } - - private void assertKind(Kind kind) { - if (kind != getKind()) { - throw new IllegalArgumentException("expected " + getKind() - + " got " + kind); - } - } - - private void initRequiredResults() { - final Module module = getModule(); - final Kind kind = getKind(); - if (kind.assemble) { - if (kind.normal) { - assertKind(RELEASE_ALL); - requiredResults.add(module.getResult(RELEASE)); - } else { - assertKind(TEST_ALL); - requiredResults.add(module.getResult(TEST)); - requiredResults.add(module.getResult(RELEASE)); - } - } else if (!kind.normal) { - assertKind(TEST); - requiredResults.add(module.getResult(RELEASE)); - } else { - assertKind(RELEASE); - } - // externally-required: - List modules = module.requiredModules(this); - final boolean adoptTests = !kind.normal || isTestingModule(module); - for (Module required: modules) { - if (adoptTests) { - // testing builds can rely on other release and test results - requiredResults.add(required.getResult(TEST)); - requiredResults.add(required.getResult(RELEASE)); - } else if (!isTestingModule(required)){ - // release builds can only rely on non-testing results - // from non-testing modules - requiredResults.add(required.getResult(RELEASE)); - } // else skip release dependencies on testing-* (testing-util) - } - } - - private void initClasspathVariables() { - // no difference - classpathVariables.addAll(getModule().classpathVariables(this)); - } - - private void initExportedLibJars() { - // no difference - exportedLibJars.addAll(getModule().exportedLibJars(this)); - } - - private synchronized void requiredDone() { - if (!requiredDone) { - initSrcDirs(); - initLibJars(); - initRequiredResults(); - initClasspathVariables(); - initExportedLibJars(); - requiredDone = true; - } - } - -} diff --git a/build/src/org/aspectj/internal/tools/build/SampleGatherer.java b/build/src/org/aspectj/internal/tools/build/SampleGatherer.java deleted file mode 100644 index 0b023e6c5..000000000 --- a/build/src/org/aspectj/internal/tools/build/SampleGatherer.java +++ /dev/null @@ -1,1049 +0,0 @@ -/* ******************************************************************* - * Copyright (c) 2003 Contributors. - * All rights reserved. - * This program and the accompanying materials are made available - * under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Wes Isberg initial implementation - * ******************************************************************/ - -/* - * A quickie hack to extract sample code from testable sources. - * This could reuse a lot of code from elsewhere, - * but currently doesn't, - * to keep it in the build module which avoids dependencies. - * (Too bad we can't use scripting languages...) - */ -package org.aspectj.internal.tools.build; - -import java.io.*; -import java.text.DateFormat; -import java.util.*; - -/** - * This gathers sample code delimited with [START..END]-SAMPLE - * from source files under a base directory, - * along with any @author info. - *
        // START-SAMPLE {anchorName} {anchorText}
        - *    ... sample code ...
        - *   // END-SAMPLE {anchorName}
        - *   
        - * where {anchorName} need not be unique and might be - * hierarchical wrt "-", e.g., "genus-species-individual". - */ -public class SampleGatherer { - - /** EOL String for gathered lines */ - public static final String EOL = "\n"; // XXX - - static final String START = "START-SAMPLE"; - static final String END = "END-SAMPLE"; - static final String AUTHOR = "@author"; - static final String FLAG = "XXX"; - -// private static void test(String[] args){ -// String[] from = new String[] { "
        ", "
        " }; -// String[] to = new String[] { "<pre>", "</pre>" }; -// String source = "in this
         day and 
        age of
        ";
        -//        System.err.println("from " + source);
        -//        System.err.println("  to " + SampleUtil.replace(source, from, to));
        -//        source = "
         day and 
        "; -// System.err.println("from " + source); -// System.err.println(" to " + SampleUtil.replace(source, from, to)); -// source = "
         0) && (start < line.length())) {
        -            line = line.substring(start);
        -        }
        -        line = line.trim();
        -        if (line.endsWith("*/")) {
        -            line = line.substring(0, line.length()-2).trim();
        -        } else if (line.endsWith("-->")) {
        -            line = line.substring(0, line.length()-3).trim();
        -        }
        -        return line;
        -    }
        -        
        -    private static void doGather(File source, Samples sink) 
        -            throws IOException {
        -        if (source.isFile()) {
        -            if (isSource(source)) {
        -                gatherFromFile(source, sink);
        -            }
        -        } else if (source.isDirectory() && source.canRead()) {
        -            File[] files = source.listFiles();
        -            for (int i = 0; i < files.length; i++) {
        -                doGather(files[i], sink);
        -            }
        -        }
        -    }
        -
        -    private static boolean isSource(File file) {
        -        if ((null == file) || !file.isFile() || !file.canRead()) {
        -            return false;
        -        }
        -        String path = file.getName().toLowerCase();
        -        String[] suffixes = Sample.Kind.SOURCE_SUFFIXES;
        -        for (int i = 0; i < suffixes.length; i++) {
        -            if (path.endsWith(suffixes[i])) {
        -                return true;
        -            }
        -        }
        -        return false;
        -    }
        -    
        -    private static void gatherFromFile(final File source, final Samples sink) 
        -            throws IOException {
        -        Reader reader = null;
        -        try {
        -            String author = null;
        -            StringBuffer sampleCode = new StringBuffer();
        -            String anchorName = null;
        -            String anchorTitle = null;
        -            ArrayList flags = new ArrayList();
        -            int startLine = -1; // seeking
        -            int endLine = Integer.MAX_VALUE; // not seeking
        -            reader = new FileReader(source);
        -            LineNumberReader lineReader = new LineNumberReader(reader);
        -            String line;
        -
        -            while (null != (line = lineReader.readLine())) { // XXX naive
        -                // found start?
        -                int loc = line.indexOf(START);
        -                if (-1 != loc) {
        -                    int lineNumber = lineReader.getLineNumber();
        -                    if (-1 != startLine) {
        -                        abort("unexpected " + START, source, line, lineNumber);
        -                    }
        -                    startLine = lineNumber;
        -                    endLine = -1;
        -                    anchorName = trimCommentEnd(line, loc + START.length());
        -                    loc = anchorName.indexOf(" ");
        -                    if (-1 == loc) {
        -                        anchorTitle = null;
        -                    } else {
        -                        anchorTitle = anchorName.substring(1+loc).trim();
        -                        anchorName = anchorName.substring(0, loc);
        -                    }
        -                    continue;
        -                } 
        -
        -                // found end?
        -                loc = line.indexOf(END);
        -                if (-1 != loc) {
        -                    int lineNumber = lineReader.getLineNumber();
        -                    if (Integer.MAX_VALUE == endLine) {
        -                        abort("unexpected " + END, source, line, lineNumber);
        -                    }
        -                    String newtag = trimCommentEnd(line, loc + END.length());
        -                    if ((newtag.length() > 0) && !newtag.equals(anchorName)) {
        -                        String m = "expected " + anchorName
        -                            + " got " + newtag;
        -                        abort(m, source, line, lineNumber);
        -                    }
        -                    endLine = lineNumber;
        -                    Sample sample = new Sample(anchorName,
        -                            anchorTitle,
        -                            author, 
        -                            sampleCode.toString(), 
        -                            source, 
        -                            startLine, 
        -                            endLine,
        -                            (String[]) flags.toArray(new String[flags.size()]));
        -                    sink.addSample(sample);
        -
        -                    // back to seeking start
        -                    sampleCode.setLength(0);
        -                    startLine = -1;
        -                    endLine = Integer.MAX_VALUE;
        -                    continue;
        -                } 
        -
        -                // found author?
        -                loc = line.indexOf(AUTHOR);
        -                if (-1 != loc) {
        -                    author = trimCommentEnd(line, loc + AUTHOR.length());
        -                }
        -                // found flag comment?
        -                loc = line.indexOf(FLAG);
        -                if (-1 != loc) {
        -                    flags.add(trimCommentEnd(line, loc + FLAG.length()));
        -                }
        -                
        -                // reading?
        -                if ((-1 != startLine) && (-1 == endLine)) {
        -                    sampleCode.append(line);
        -                    sampleCode.append(EOL);
        -                }
        -            }
        -            if (-1 == endLine) {
        -                abort("incomplete sample", source, "", lineReader.getLineNumber());
        -            }
        -        } finally {
        -            if (null != reader) {
        -                reader.close();
        -            }
        -        }
        -    }
        -    private static void abort(String why, File file, String line, int lineNumber)
        -            throws Abort {
        -        throw new Abort(why + " at " + file + ":" + lineNumber + ": " + line);
        -    }
        -//    private static void delay(Object toDelay) {
        -//        synchronized (toDelay) { // XXX sleep instead?
        -//            toDelay.notifyAll();
        -//        }
        -//    }
        -    static class Abort extends IOException {
        -        private static final long serialVersionUID = -1l;
        -        Abort(String s) {
        -            super(s);
        -        }
        -    }
        -}
        -
        -/**
        - * Data associated with sample code - struct class.
        - */
        -class Sample {
        -    public static final String ASPECTJ_TEAM = "The AspectJ Team";
        -
        -    /** sort by anchorName, file path, and start/end location */
        -    static Comparator NAME_SOURCE_COMPARER = new Comparator() {
        -        public int compare(Sample left, Sample right) {
        -            if (null == left) {
        -                return (null == right ? 0 : -1);
        -            } 
        -            if (null == right) {
        -                return 1;
        -            } 
        -            int result = left.anchorName.compareTo(right.anchorName);
        -            if (0 != result) {
        -                return result;                
        -            }
        -            result = left.sourcePath.compareTo(right.sourcePath);
        -            if (0 != result) {
        -                return result;                
        -            }
        -            result = right.startLine - left.startLine;
        -            if (0 != result) {
        -                return result;                
        -            }
        -            return right.endLine - left.endLine;
        -        }
        -    };
        -
        -    /** sort by author, then NAME_SOURCE_COMPARER */
        -    static Comparator AUTHOR_NAME_SOURCE_COMPARER = new Comparator() {
        -        public int compare(Sample left, Sample right) {
        -            if (null == left) {
        -                return (null == right ? 0 : -1);
        -            } 
        -            if (null == right) {
        -                return 1;
        -            } 
        -            int result = left.author.compareTo(right.author);
        -            if (0 != result) {
        -                return result;                
        -            }
        -            return NAME_SOURCE_COMPARER.compare(left,right);
        -        }
        -    };
        -    
        -    final String anchorName;
        -    final String anchorTitle;
        -    final String author;
        -    final String sampleCode;
        -    final File sourcePath;
        -    final int startLine;
        -    final int endLine;
        -    final Kind kind;
        -    /** List of String flags found in the sample */
        -    final List flags;
        -    public Sample(
        -        String anchorName,
        -        String anchorTitle,
        -        String author,
        -        String sampleCode,
        -        File sourcePath,
        -        int startLine,
        -        int endLine,
        -        String[] flags) {
        -        this.anchorName = anchorName;
        -        this.anchorTitle = anchorTitle;
        -        this.author = (null != author ? author : ASPECTJ_TEAM);
        -        this.sampleCode = sampleCode;
        -        this.sourcePath = sourcePath;
        -        this.startLine = startLine;
        -        this.endLine = endLine;
        -        this.kind = Kind.getKind(sourcePath);
        -//        List theFlags;
        -        if ((null == flags) || (0 == flags.length)) {
        -            this.flags = Collections.EMPTY_LIST;
        -        } else {
        -            this.flags = Collections.unmodifiableList(Arrays.asList(flags));
        -        }
        -    }
        -
        -    public String toString() {
        -        return sampleCode;
        -    }
        -
        -    public static class Kind {
        -        
        -        /** lowercase source suffixes identify files to gather samples from */
        -        public static final String[] SOURCE_SUFFIXES = new String[]
        -        { ".java", ".aj", ".sh", ".ksh", 
        -        ".txt", ".text", ".html", ".htm", ".xml" };
        -        static final Kind XML = new Kind();
        -        static final Kind HTML = new Kind();
        -        static final Kind PROGRAM = new Kind();
        -        static final Kind SCRIPT = new Kind();
        -        static final Kind TEXT = new Kind();
        -        static final Kind OTHER = new Kind();
        -        public static Kind getKind(File file) {
        -            if (null == file) {
        -                return OTHER;
        -            }
        -            String name = file.getName().toLowerCase();
        -            if ((name.endsWith(".java") || name.endsWith(".aj"))) {
        -                return PROGRAM;
        -            }
        -            if ((name.endsWith(".html") || name.endsWith(".htm"))) {
        -                return HTML;
        -            }
        -            if ((name.endsWith(".sh") || name.endsWith(".ksh"))) {
        -                return SCRIPT;
        -            }
        -            if ((name.endsWith(".txt") || name.endsWith(".text"))) {
        -                return TEXT;
        -            }
        -            if (name.endsWith(".xml")) {
        -                return XML;
        -            }
        -            return OTHER;
        -        }
        -        private Kind() {
        -        }
        -    }
        -}
        -
        -/**
        - * type-safe Collection of samples.
        - */
        -class Samples {
        -    private ArrayList samples = new ArrayList();
        -    int size() {
        -        return samples.size();
        -    }
        -    void addSample(Sample sample) {
        -        samples.add(sample);
        -    }
        -    /**
        -     * @return List copy, sorted by Sample.NAME_SOURCE_COMPARER
        -     */
        -    List getSortedSamples() {
        -        return getSortedSamples(Sample.NAME_SOURCE_COMPARER);
        -    }
        -    
        -    List getSortedSamples(Comparator comparer) {
        -        ArrayList result = new ArrayList();
        -        result.addAll(samples);
        -        Collections.sort(result, comparer);
        -        return result;
        -    }
        -}
        -
        -
        -/**
        - * Render samples by using method visitors.
        - */
        -class SamplesRenderer {
        -    public static SamplesRenderer ME = new SamplesRenderer();
        -    protected SamplesRenderer() {        
        -    }
        -    public static final String EOL = "\n"; // XXX
        -    public static final String INFO = 
        -      "

        This contains contributions from the AspectJ community of " - + "

        • sample code for AspectJ programs,
        • " - + "
        • sample code for extensions to AspectJ tools using the public API's,
        • " - + "
        • sample scripts for invoking AspectJ tools, and
        • " - + "
        • documentation trails showing how to do given tasks" - + " using AspectJ, AJDT, or various IDE or deployment" - + " environments.

        " - + "

        Find complete source files in the AspectJ CVS repository at " - + "org.aspectj/modules/docs/sandbox. " - + "For instructions on downloading code from the CVS repository, " - + "see the FAQ entry " - + "\"buildingsource\".

        "; - - public static final String COPYRIGHT = - "

        Copyright 2003 Contributors. All Rights Reserved. " - + "This sample code is made available under the Common Public " + "License version 1.0 available at " - + "" - + "http://www.eclipse.org/legal/epl-v10.html." - + "Contributors are listed in this document as authors. " - + "Permission to republish portions of this sample code " - + "is hereby granted if the publication acknowledges " - + "the author by name and " - + "the source by reference to the AspectJ project home page " - + " at http://eclipse.org/aspectj.

        " - + EOL; - - /** template algorithm to render */ - public final StringBuffer render(Samples samples, StringBuffer sink) { - if (null == sink) { - sink = new StringBuffer(); - } - if ((null == samples) || (0 == samples.size())) { - return sink; - } - startList(samples, sink); - List list = samples.getSortedSamples(); - String anchorName = null; - for (ListIterator iter = list.listIterator(); - iter.hasNext();) { - Sample sample = (Sample) iter.next(); - String newAnchorName = sample.anchorName; - if ((null == anchorName) - || (!anchorName.equals(newAnchorName))) { - endAnchorName(anchorName, sink); - startAnchorName(newAnchorName, sample.anchorTitle, sink); - anchorName = newAnchorName; - } - render(sample, sink); - } - endAnchorName(anchorName, sink); - endList(samples, sink); - return sink; - } - protected void startList(Samples samples, StringBuffer sink) { - sink.append("Printing " + samples.size() + " samples"); - sink.append(EOL); - } - - protected void startAnchorName(String name, String title, StringBuffer sink) { - sink.append("anchor " + name); - sink.append(EOL); - } - - protected void render(Sample sample, StringBuffer sink) { - SampleUtil.render(sample, "=", ", ",sink); - sink.setLength(sink.length()-2); - sink.append(EOL); - } - - /** - * @param name the String name being ended - ignore if null - * @param sink - */ - protected void endAnchorName(String name, StringBuffer sink) { - if (null == name) { - return; - } - } - - protected void endList(Samples samples, StringBuffer sink) { - sink.append("Printed " + samples.size() + " samples"); - sink.append(EOL); - } - -} - -// XXX need DocBookSamplesRenderer - -/** - * Output the samples as a single HTML file, with a table of contents - * and sorting the samples by their anchor tags. - */ -class HTMLSamplesRenderer extends SamplesRenderer { - public static SamplesRenderer ME = new HTMLSamplesRenderer(); - // XXX move these - public static boolean doHierarchical = true; - public static boolean doFlags = false; - - - final StringBuffer tableOfContents; - final StringBuffer sampleSection; - String[] lastAnchor = new String[0]; - String currentAnchor; - String currentAuthor; - - protected HTMLSamplesRenderer() { - sampleSection = new StringBuffer(); - tableOfContents = new StringBuffer(); - } - - protected void startAnchorName(String name, String title, StringBuffer sink) { - if (doHierarchical) { - doContentTree(name); - } - // ---- now do anchor - tableOfContents.append("
      5. " + title + "
      6. "); - tableOfContents.append(EOL); - currentAnchor = name; - } - - protected void startList(Samples samples, StringBuffer sink) { - } - - protected void render(Sample sample, StringBuffer sink) { - if (null != currentAnchor) { - if (!currentAnchor.equals(sample.anchorName)) { - String m = "expected " + currentAnchor - + " got " + sample.anchorName; - throw new Error(m); - } - currentAnchor = null; - } - - // do heading then code - renderHeading(sample.anchorName, sample.anchorTitle, sampleSection); - if (sample.kind == Sample.Kind.HTML) { - renderHTML(sample); - } else if (sample.kind == Sample.Kind.XML) { - renderXML(sample); - } else { - renderPre(sample); - } - } - - protected boolean doRenderAuthor(Sample sample) { - return (null != sample.author); - // && !sample.author.equals(currentAuthor) - } - - protected void renderStandardHeader(Sample sample) { - // XXX starting same as pre - if (doRenderAuthor(sample)) { - currentAuthor = sample.author; - sampleSection.append("

        |   " + currentAuthor); - sampleSection.append(EOL); - } - sampleSection.append("  |  "); - sampleSection.append(SampleUtil.renderCodePath(sample.sourcePath)); - sampleSection.append(":" + sample.startLine); - sampleSection.append("  |"); - sampleSection.append(EOL); - sampleSection.append("

        "); - sampleSection.append(EOL); - if (doFlags) { - boolean flagHeaderDone = false; - for (Iterator iter = sample.flags.iterator(); iter.hasNext();) { - String flag = (String) iter.next(); - if (!flagHeaderDone) { - sampleSection.append("

        Comments flagged:

          "); - sampleSection.append(EOL); - flagHeaderDone = true; - } - sampleSection.append("
        • "); - sampleSection.append(flag); - sampleSection.append("
        • "); - } - if (flagHeaderDone) { - sampleSection.append("
        "); - sampleSection.append(EOL); - } - } - } - - protected void renderXML(Sample sample) { - renderStandardHeader(sample); - sampleSection.append("
        ");
        -        sampleSection.append(EOL);
        -        sampleSection.append(prepareXMLSample(sample.sampleCode));
        -        sampleSection.append(EOL);
        -        sampleSection.append("    
        "); - sampleSection.append(EOL); - } - - protected void renderHTML(Sample sample) { - renderStandardHeader(sample); - sampleSection.append(EOL); - sampleSection.append(prepareHTMLSample(sample.sampleCode)); - sampleSection.append(EOL); - } - - protected void renderPre(Sample sample) { - renderStandardHeader(sample); - sampleSection.append("
        ");
        -        sampleSection.append(EOL);
        -        sampleSection.append(prepareCodeSample(sample.sampleCode));
        -        sampleSection.append("    
        "); - sampleSection.append(EOL); - } - - protected void endAnchorName(String name, StringBuffer sink) { - if (null == name) { - return; - } - currentAnchor = null; - currentAuthor = null; // authors don't span anchors - } - - protected void endList(Samples samples, StringBuffer sink) { - sink.append(""); - sink.append(EOL); - sink.append("AspectJ sample code"); - sink.append(EOL); - sink.append(""); - sink.append(EOL); - sink.append(" "); - sink.append(EOL); - sink.append("

        AspectJ sample code

        "); - sink.append(INFO); - sink.append(EOL); - sink.append(COPYRIGHT); - sink.append(EOL); - sink.append("

        Generated on "); - sink.append(DateFormat.getDateInstance().format(new Date())); - sink.append(" by SamplesGatherer"); - sink.append(EOL); - sink.append("

        Contents

        "); - sink.append(EOL); - sink.append("
          "); - sink.append(EOL); - sink.append(tableOfContents.toString()); - // unwind to common prefix, if necessary - for (int i = 0; i < lastAnchor.length ; i++) { - sink.append("
        "); - } - - sink.append("
      7. Author Index
      8. "); - sink.append("
    "); - sink.append("

    Listings

    "); - sink.append(EOL); - sink.append(sampleSection.toString()); - renderAuthorIndex(samples, sink); - sink.append(""); - sink.append(EOL); - } - - protected String prepareXMLSample(String sampleCode) { - String[] from = new String[] {"\t", "<"}; - String[] to = new String[] {" ", "<"}; - return (SampleUtil.replace(sampleCode, from, to)); - } - - protected String prepareHTMLSample(String sampleCode) { - String[] from = new String[20]; - String[] to = new String[20]; - for (int i = 0; i < to.length; i++) { - String h = "h" + i + ">"; - from[i] = "<" + h; - to[i] = "

    "; - from[++i] = "

    "; - } - return (SampleUtil.replace(sampleCode, from, to)); - } - - protected String prepareCodeSample(String sampleCode) { - String[] from = new String[] { "

    ", "
    " }; - String[] to = new String[] { "<pre>", "</pre>" }; - return (SampleUtil.replace(sampleCode, from, to)); - } - - protected void renderHeading(String anchor, String title, StringBuffer sink) { - sink.append(" "); - sink.append(EOL); - if ((null == title) || (0 == title.length())) { - title = anchor; - } - sink.append("

    " + title + "

    "); - sink.append(EOL); - sink.append("back to top"); - sink.append(EOL); - } - - /** - * Manage headings in both table of contents and listings. - * @param name the String anchor - */ - protected void doContentTree(String name) { - if (name.equals(lastAnchor)) { - return; - } - // ---- handle trees - String[] parts = SampleUtil.splitAnchorName(name); - //String[] lastAnchor = (String[]) lastAnchors.peek(); - int firstDiff = SampleUtil.commonPrefix(parts, lastAnchor); - // unwind to common prefix, if necessary - if (firstDiff+1 < lastAnchor.length) { - for (int i = 1; i < lastAnchor.length-firstDiff ; i++) { - tableOfContents.append(" "); - tableOfContents.append(EOL); - } - } - // build up prefix - StringBuffer branchAnchor = new StringBuffer(); - for (int i = 0; i < firstDiff;) { - branchAnchor.append(parts[i]); - i++; - branchAnchor.append("-"); - } - // emit leading headers, but not anchor itself - for (int i = firstDiff; i < (parts.length-1); i++) { - branchAnchor.append(parts[i]); - String prefixName = branchAnchor.toString(); - branchAnchor.append("-"); - tableOfContents.append("
  12. " + prefixName + "
  13. "); - tableOfContents.append(EOL); - tableOfContents.append("
      "); - tableOfContents.append(EOL); - - renderHeading(prefixName, prefixName, sampleSection); - } - lastAnchor = parts; - } - - protected void renderAuthorIndex(Samples samples, StringBuffer sink) { - sink.append("

      Author Index

      "); - List list = samples.getSortedSamples(Sample.AUTHOR_NAME_SOURCE_COMPARER); - String lastAuthor = null; - for (ListIterator iter = list.listIterator(); iter.hasNext();) { - Sample sample = (Sample)iter.next(); - String author = sample.author; - if (!author.equals(lastAuthor)) { - if (null != lastAuthor) { - sink.append("
    "); - } - sink.append("
  14. "); - sink.append(author); - sink.append(EOL); - sink.append("
      "); - sink.append(EOL); - lastAuthor = author; - } - sink.append("
    • "); - if (null == sample.anchorTitle) { - sink.append(sample.anchorName); - } else { - sink.append(sample.anchorTitle); - } - sink.append("
    • "); - } - } -} - -class SampleUtil { - public static final String SAMPLE_BASE_DIR_NAME = "sandbox"; - - public static void simpleRender(Samples result, StringBuffer sink) { - List sortedSamples = result.getSortedSamples(); - int i = 0; - for (ListIterator iter = sortedSamples.listIterator(); - iter.hasNext();) { - Sample sample = (Sample) iter.next(); - sink.append(i++ + ": " + sample); - } - } - - /** result struct for getPackagePath */ - static class JavaFile { - /** input File possibly signifying a java file */ - final File path; - - /** String java path suffix in form "com/company/Bar.java" - * null if this is not a java file - */ - final String javaPath; - - /** any prefix before java path suffix in the original path */ - final String prefix; - - /** error handling */ - final Throwable thrown; - JavaFile(File path, String javaPath, String prefix, Throwable thrown) { - this.path = path; - this.javaPath = javaPath; - this.prefix = prefix; - this.thrown = thrown; - } - } - - /** - * Read any package statement in the file to determine - * the package path of the file - * @param path the File to seek the package in - * @return the JavaFile with the components of the path - */ - public static JavaFile getJavaFile(File path) { - if (null == path) { - throw new IllegalArgumentException("null path"); - } - String result = path.getPath().replace('\\', '/'); - String packag = ""; - String javaPath = null; - String prefix = null; - Throwable thrown = null; - if (result.endsWith(".java") || result.endsWith(".aj")) { - FileReader reader = null; - try { - reader = new FileReader(path); - BufferedReader br = new BufferedReader(reader); - String line; - while (null != (line = br.readLine())) { - int loc = line.indexOf("package"); - if (-1 != loc) { - int end = line.indexOf(";"); - if (-1 == loc) { - String m = "unterminated package statement \""; - throw new Error(m + line + "\" in " + path); - } - packag = (line.substring(loc + 7, end) + ".") - .trim() - .replace('.', '/'); - break; - } - loc = line.indexOf("import"); - if (-1 != loc) { - break; - } - } - } catch (IOException e) { - thrown = e; - } finally { - if (null != reader) { - try { - reader.close(); - } catch (IOException e1) { - // ignore - } - } - } - if (null == thrown) { - javaPath = packag + path.getName(); - int loc = result.indexOf(javaPath); - if (-1 == loc) { - String m = "expected suffix " + javaPath + " in "; - throw new Error(m + result); - } - prefix = result.substring(0, loc); - } - } - return new JavaFile(path, javaPath, prefix, thrown); - } - - /** - * Extract file path relative to base of package directory - * and directory in SAMPLE_BASE_DIR_NAME for this file. - * @param path the File to render from SAMPLE_BASE_DIR_NAME - * @return String "baseDir {path}" - */ - public static String renderCodePath(File path) { - JavaFile javaFile = getJavaFile(path); - if (javaFile.thrown != null) { - throw new Error(javaFile.thrown.getClass() - + ": " + javaFile.thrown.getMessage()); - } - - String file = javaFile.javaPath; // can be null... - String prefix = javaFile.prefix; - if (prefix == null) { - prefix = path.getPath().replace('\\', '/'); - } - int loc = prefix.lastIndexOf(SAMPLE_BASE_DIR_NAME); - if (-1 == loc) { - String m = "not after " + SAMPLE_BASE_DIR_NAME; - throw new IllegalArgumentException(m + "?: " + path); - } - prefix = prefix.substring(loc + 1 + SAMPLE_BASE_DIR_NAME.length()); - - if (file == null) { - int slash = prefix.lastIndexOf('/'); - if (-1 == slash) { - file = prefix; - prefix = ""; - } else { - file = prefix.substring(slash+1); - prefix = prefix.substring(0, slash); - } - } - if (prefix.endsWith("/")) { - prefix = prefix.substring(0, prefix.length()-1); - } - return (prefix + " " + file).trim(); - } - - public static int commonPrefix(String[] lhs, String[] rhs) { - final int max = smallerSize(lhs, rhs); - int firstDiff = 0; - while (firstDiff < max) { - if (!lhs[firstDiff].equals(rhs[firstDiff])) { - break; - } - firstDiff++; - } - return firstDiff; - } - - private static int smallerSize(Object[] one, Object[] two) { - if ((null == one) || (null == two)) { - return 0; - } - return (one.length > two.length ? two.length : one.length); - } - - public static String[] splitAnchorName(Sample sample) { - return splitAnchorName(sample.anchorName); - } - - public static String[] splitAnchorName(String anchorName) { - ArrayList result = new ArrayList(); - int start = 0; - int loc = anchorName.indexOf("-", start); - String next; - while (loc != -1) { - next = anchorName.substring(start, loc); - result.add(next); - start = loc+1; - loc = anchorName.indexOf("-", start); - } - next = anchorName.substring(start); - result.add(next); - return (String[]) result.toArray(new String[result.size()]); - } - /** - * Replace literals with literals in source string - * @param source the String to modify - * @param from the String[] of literals to replace - * @param to the String[] of literals to use when replacing - * @return the String source as modified by the replaces - */ - public static String replace(String source, String[] from, String[] to) { - if ((null == source) || (0 == source.length())) { - return source; - } - if (from.length != to.length) { - throw new IllegalArgumentException("unmatched from/to"); - } - StringBuffer result = new StringBuffer(); - int LEN = source.length(); - int start = 0; - for (int i = 0; i < LEN; i++) { - String suffix = source.substring(i); - for (int j = 0; j < from.length; j++) { - if (suffix.startsWith(from[j])) { - result.append(source.substring(start, i)); - result.append(to[j]); - start = i + from[j].length(); - i = start-1; - break; - } - } - } - if (start < source.length()) { - result.append(source.substring(start)); - } - return result.toString(); - } - - public static void render( - Sample sample, - String fieldDelim, - String valueDelim, - StringBuffer sink) { - if ((null == sink) || (null == sample)) { - return; - } - if (null == fieldDelim) { - fieldDelim = ""; - } - if (null == valueDelim) { - valueDelim = ""; - } - sink.append("anchorName"); - sink.append(valueDelim); - sink.append(sample.anchorName); - sink.append(fieldDelim); - sink.append("author"); - sink.append(valueDelim); - sink.append(sample.author); - sink.append(fieldDelim); - sink.append("sourcePath"); - sink.append(valueDelim); - sink.append(sample.sourcePath.toString()); - sink.append(fieldDelim); - sink.append("startLine"); - sink.append(valueDelim); - sink.append(sample.startLine); - sink.append(fieldDelim); - sink.append("endLine"); - sink.append(valueDelim); - sink.append(sample.endLine); - sink.append(fieldDelim); - sink.append("sampleCode"); - sink.append(valueDelim); - sink.append(sample.sampleCode.toString()); - sink.append(fieldDelim); - } - private SampleUtil(){} -} diff --git a/build/src/org/aspectj/internal/tools/build/Util.java b/build/src/org/aspectj/internal/tools/build/Util.java deleted file mode 100644 index 2fc2dcb72..000000000 --- a/build/src/org/aspectj/internal/tools/build/Util.java +++ /dev/null @@ -1,483 +0,0 @@ -/* ******************************************************************* - * Copyright (c) 1999-2001 Xerox Corporation, - * 2002 Palo Alto Research Center, Incorporated (PARC). - * All rights reserved. - * This program and the accompanying materials are made available - * under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Xerox/PARC initial implementation - * ******************************************************************/ - - -package org.aspectj.internal.tools.build; - -import java.io.*; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.StringTokenizer; -import java.util.jar.Attributes; -import java.util.jar.Manifest; -import java.util.jar.Attributes.Name; - -/** - * Build-only utilities. - * Many mirror utils module APIs. - */ -public class Util { - public static class Constants { - public static final String TESTSRC = "testsrc"; - public static final String JAVA5_SRC = "java5-src"; - public static final String JAVA5_TESTSRC = "java5-testsrc"; - } - // XXX quick hack for Java 5 support - public static final boolean JAVA5_VM; - static { - boolean java5VM = false; - try { - java5VM = (null != Class.forName("java.lang.annotation.Annotation")); - } catch (Throwable t) { - // ignore - } - JAVA5_VM = java5VM; - } - - /** - * Map version in long form to short, - * e.g., replacing "alpha" with "a" - */ - public static String shortVersion(String version) { - version = Util.replace(version, "alpha", "a"); - version = Util.replace(version, "beta", "b"); - version = Util.replace(version, "candidate", "rc"); - version = Util.replace(version, "development", "d"); - version = Util.replace(version, "dev", "d"); - return version; - } - - /** - * Replace any instances of {replace} in {input} with {with}. - * @param input the String to search/replace - * @param replace the String to search for in input - * @param with the String to replace with in input - * @return input if it has no replace, otherwise a new String - */ - public static String replace(String input, String replace, String with) { - int loc = input.indexOf(replace); - if (-1 != loc) { - String result = input.substring(0, loc); - result += with; - int start = loc + replace.length(); - if (start < input.length()) { - result += input.substring(start); - } - input = result; - } - return input; - } - - /** @return false if filter returned false for any file in baseDir subtree */ - public static boolean visitFiles(File baseDir, FileFilter filter) { - Util.iaxIfNotCanReadDir(baseDir, "baseDir"); - Util.iaxIfNull(filter, "filter"); - File[] files = baseDir.listFiles(); - boolean passed = true; - for (int i = 0; passed && (i < files.length); i++) { - passed = files[i].isDirectory() - ? visitFiles(files[i], filter) - : filter.accept(files[i]); - } - return passed; - } - - /** @throws IllegalArgumentException if cannot read dir */ - public static void iaxIfNotCanReadDir(File dir, String name) { - if (!canReadDir(dir)) { - throw new IllegalArgumentException(name + " dir not readable: " + dir); - } - } - - /** @throws IllegalArgumentException if cannot read file */ - public static void iaxIfNotCanReadFile(File file, String name) { - if (!canReadFile(file)) { - throw new IllegalArgumentException(name + " file not readable: " + file); - } - } - - /** @throws IllegalArgumentException if cannot write dir */ - public static void iaxIfNotCanWriteDir(File dir, String name) { - if (!canWriteDir(dir)) { - throw new IllegalArgumentException(name + " dir not writeable: " + dir); - } - } - - /** @throws IllegalArgumentException if input is null */ - public static void iaxIfNull(Object input, String name) { - if (null == input) { - throw new IllegalArgumentException("null " + name); - } - } - - /** render exception to String */ - public static String renderException(Throwable thrown) { - if (null == thrown) { - return "(Throwable) null"; - } - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw, true); - pw.println(thrown.getMessage()); - thrown.printStackTrace(pw); - pw.flush(); - return sw.getBuffer().toString(); - } - - /** @return true if dir is a writable directory */ - public static boolean canWriteDir(File dir) { - return (null != dir) && dir.canWrite() && dir.isDirectory(); - } - - public static String path(String first, String second) { - return first + File.separator + second; - } - - public static String path(String[] segments) { - StringBuffer sb = new StringBuffer(); - if ((null != segments)) { - for (int i = 0; i < segments.length; i++) { - if (0 < i) { - sb.append(File.separator); - } - sb.append(segments[i]); - } - } - return sb.toString(); - } - - /** @return true if dir is a readable directory */ - public static boolean canReadDir(File dir) { - return (null != dir) && dir.canRead() && dir.isDirectory(); - } - - /** @return true if dir is a readable file */ - public static boolean canReadFile(File file) { - return (null != file) && file.canRead() && file.isFile(); - } - - /** - * Delete file or directory. - * @param dir the File file or directory to delete. - * @return true if all contents of dir were deleted - */ - public static boolean delete(File dir) { - return deleteContents(dir) && dir.delete(); - } - - /** - * Delete contents of directory. - * The directory itself is not deleted. - * @param dir the File directory whose contents should be deleted. - * @return true if all contents of dir were deleted - */ - public static boolean deleteContents(File dir) { - if ((null == dir) || !dir.canWrite()) { - return false; - } else if (dir.isDirectory()) { - File[] files = dir.listFiles(); - for (int i = 0; i < files.length; i++) { - if (!deleteContents(files[i]) || !files[i].delete()) { - return false; - } - } - } - return true; - } - - /** @return File temporary directory with the given prefix */ - public static File makeTempDir(String prefix) { - if (null == prefix) { - prefix = "tempDir"; - } - File tempFile = null; - for (int i = 0; i < 10; i++) { - try { - tempFile = File.createTempFile(prefix,"tmp"); - tempFile.delete(); - if (tempFile.mkdirs()) { - break; - } - tempFile = null; - } catch (IOException e) { - } - } - return tempFile; - } - /** - * Close stream with the usual checks. - * @param stream the InputStream to close - ignored if null - * @return null if closed without IOException, message otherwise - */ - public static String close(Writer stream) { - String result = null; - if (null != stream) { - try { - stream.close(); - } catch(IOException e) { - result = e.getMessage(); - } - } - return result; - } - - /** - * @param list the Object[] to test - * @return true if list is null or empty - */ - public static boolean isEmpty(Object[] list) { - return ((null == list) || (0 == list.length)); - } - - public static void closeSilently(InputStream in) { - if (null != in) { - try { - in.close(); - } catch (IOException e) { - // do nothing - } - } - } - - public static void closeSilently(Reader in) { - if (null != in) { - try { - in.close(); - } catch (IOException e) { - // do nothing - } - } - } - - /** - * Report whether actual has different members than expected - * @param expected the String[] of expected members (none null) - * @param actual the String[] of actual members - * @param sb StringBuffer sink for any differences in membership - * @return true if any diffs found and sink updated - */ - public static final boolean reportMemberDiffs(String[] expected, String[] actual, StringBuffer sb) { - expected = copy(expected); - actual = copy(actual); - int hits = 0; - for (int i = 0; i < expected.length; i++) { - int curHit = hits; - for (int j = 0; (curHit == hits) && (j < actual.length); j++) { - if (null == expected[i]) { - throw new IllegalArgumentException("null at " + i); - } - if (expected[i].equals(actual[j])) { - expected[i] = null; - actual[j] = null; - hits++; - } - } - } - if ((hits != expected.length) || (hits != actual.length)) { - sb.append("unexpected ["); - String prefix = ""; - for (int i = 0; i < actual.length; i++) { - if (null != actual[i]) { - sb.append(prefix); - prefix = ", "; - sb.append("\""); - sb.append(actual[i]); - sb.append("\""); - } - } - sb.append("] missing ["); - prefix = ""; - for (int i = 0; i < expected.length; i++) { - if (null != expected[i]) { - sb.append(prefix); - prefix = ", "; - sb.append("\""); - sb.append(expected[i]); - sb.append("\""); - } - } - sb.append("]"); - return true; - } - return false; - } - - private static final String[] copy(String[] ra) { - if (null == ra) { - return new String[0]; - } - String[] result = new String[ra.length]; - System.arraycopy(ra, 0, result, 0, ra.length); - return result; - } - - /** - * Support for OSGI bundles read from manifest files. - * Currently very limited, and will only support the subset of - * features that we use. - * sources: - * http://www-128.ibm.com/developerworks/library/os-ecl-osgi/index.html - * http://help.eclipse.org/help30/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/osgi/org/osgi/framework/Constants.html - */ - public static class OSGIBundle { - public static final Name BUNDLE_NAME = new Name("Bundle-Name"); - - public static final Name BUNDLE_SYMBOLIC_NAME = new Name( - "Bundle-SymbolicName"); - - public static final Name BUNDLE_VERSION = new Name("Bundle-Version"); - - public static final Name BUNDLE_ACTIVATOR = new Name("Bundle-Activator"); - - public static final Name BUNDLE_VENDOR = new Name("Bundle-Vendor"); - - public static final Name REQUIRE_BUNDLE = new Name("Require-Bundle"); - - public static final Name IMPORT_PACKAGE = new Name("Import-Package"); - - public static final Name BUNDLE_CLASSPATH = new Name("Bundle-ClassPath"); - - /** unmodifiable list of all valid OSGIBundle Name's */ - public static final List NAMES; - static { - ArrayList names = new ArrayList(); - names.add(BUNDLE_NAME); - names.add(BUNDLE_SYMBOLIC_NAME); - names.add(BUNDLE_VERSION); - names.add(BUNDLE_ACTIVATOR); - names.add(BUNDLE_VENDOR); - names.add(REQUIRE_BUNDLE); - names.add(IMPORT_PACKAGE); - names.add(BUNDLE_CLASSPATH); - NAMES = Collections.unmodifiableList(names); - } - - private final Manifest manifest; - - private final Attributes attributes; - - /** - * - * @param manifestInputStream - * the InputStream of the manifest.mf - will be closed. - * @throws IOException - * if unable to read or close the manifest input stream. - */ - public OSGIBundle(InputStream manifestInputStream) throws IOException { - manifest = new Manifest(); - manifest.read(manifestInputStream); - manifestInputStream.close(); - attributes = manifest.getMainAttributes(); - } - - public String getAttribute(Name attributeName) { - return attributes.getValue(attributeName); - } - - public String[] getClasspath() { - String cp = getAttribute(OSGIBundle.BUNDLE_CLASSPATH); - if (null == cp) { - return new String[0]; - } - StringTokenizer st = new StringTokenizer(cp, " ,"); - String[] result = new String[st.countTokens()]; - int i = 0; - while (st.hasMoreTokens()) { - result[i++] = st.nextToken(); - } - return result; - } - - /** - * XXX ugly/weak hack only handles a single version comma - * {name};bundle-version="[1.5.0,1.5.5]";resolution:=optional - * @return - */ - public RequiredBundle[] getRequiredBundles() { - String value = getAttribute(OSGIBundle.REQUIRE_BUNDLE); - if (null == value) { - return new RequiredBundle[0]; - } - StringTokenizer st = new StringTokenizer(value, " ,"); - RequiredBundle[] result = new RequiredBundle[st.countTokens()]; - int i = 0; - int skips = 0; - while (st.hasMoreTokens()) { - String token = st.nextToken(); - int first = token.indexOf("\""); - if (-1 != first) { - if (!st.hasMoreTokens()) { - throw new IllegalArgumentException(token); - } - // just assume only one quoted "," for version? - token += "," + st.nextToken(); - skips++; - } - result[i++] = new RequiredBundle(token); - } - if (skips > 0) { - RequiredBundle[] patch = new RequiredBundle[result.length-skips]; - System.arraycopy(result, 0, patch, 0, patch.length); - result = patch; - } - return result; - } - - /** - * Wrap each dependency on another bundle - */ - public static class RequiredBundle { - - /** unparsed entry text, for debugging */ - final String text; - - /** Symbolic name of the required bundle */ - final String name; - - /** if not null, then start/end versions of required bundle - * in the format of the corresponding manifest entry - */ - final String versions; - - /** if true, then required bundle is optional */ - final boolean optional; - - private RequiredBundle(String entry) { - text = entry; - StringTokenizer st = new StringTokenizer(entry, ";"); - name = st.nextToken(); - String vers = null; - String opt = null; - // bundle-version="[1.5.0,1.5.5]";resolution:=optiona - final String RESOLUTION = "resolution:="; - final String VERSION = "bundle-version=\""; - while (st.hasMoreTokens()) { - String token = st.nextToken(); - if (token.startsWith(VERSION)) { - int start = VERSION.length(); - int end = token.lastIndexOf("\""); - vers = token.substring(start, end); - // e.g., [1.5.0,1.5.5) - } else if (token.startsWith(RESOLUTION)) { - int start = RESOLUTION.length(); - int end = token.length(); - opt = token.substring(start, end); - } - } - versions = vers; - optional = "optional".equals(opt); - } - } - } -} - diff --git a/build/src/org/aspectj/internal/tools/build/package.html b/build/src/org/aspectj/internal/tools/build/package.html deleted file mode 100644 index 3fa443812..000000000 --- a/build/src/org/aspectj/internal/tools/build/package.html +++ /dev/null @@ -1,12 +0,0 @@ - - - -The build taskdef relies on the classes in this package for -behavior independent of Ant. - - diff --git a/build/src/test/java/org/aspectj/build/BuildModuleTests.java b/build/src/test/java/org/aspectj/build/BuildModuleTests.java new file mode 100644 index 000000000..52510c75f --- /dev/null +++ b/build/src/test/java/org/aspectj/build/BuildModuleTests.java @@ -0,0 +1,304 @@ +package org.aspectj.build; +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + + +// default package + +import org.aspectj.internal.tools.ant.taskdefs.Checklics; +import org.aspectj.internal.tools.build.Builder; +import org.aspectj.internal.tools.build.Util; +import org.aspectj.internal.tools.build.UtilsTest; +import org.aspectj.internal.build.BuildModuleTest; +import org.aspectj.internal.build.ModulesTest; + +import java.io.File; +import java.io.FileFilter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.StringTokenizer; + +import junit.framework.*; + +/** + * Master suite for build module + * and test of all source directories for correct licenses and known file types. + */ +public class BuildModuleTests extends TestCase { + + /** if true, then replace old headers with new first */ + private static final boolean replacing = false; // XXX never to enable again... + + /** replace commented out below - if any replace failed, halt all */ + private static boolean replaceFailed = false; + + private static final String BASE_DIR = ".." + File.separator; + private static final String[] JDT_SOURCE_DIRS = new String[] {}; + + public static Test suite() { + TestSuite suite = new TestSuite("Build module tests"); + suite.addTestSuite(BuildModuleTests.class); + suite.addTestSuite(BuildModuleTest.class); + suite.addTestSuite(ModulesTest.class); + suite.addTestSuite(UtilsTest.class); + return suite; + } + + /** @return String tag of license if not default */ + public static String getLicense(String module) { + return null; // use permissive default + } + + final static List SOURCE_NAMES = Collections.unmodifiableList( + Arrays.asList(new String[]{"src", "testsrc", "java5-src", "java5-testsrc", "aspectj-src"})); + + /** + * @param moduleDir + * @return + */ + private static File[] findSourceRoots(File moduleDir) { + ArrayList result = new ArrayList(); + for (String name: SOURCE_NAMES) { + File srcDir = new File(moduleDir, name); + if (srcDir.canRead() && srcDir.isDirectory()) { + result.add(srcDir); + } + } + return (File[]) result.toArray(new File[0]); + } + + public BuildModuleTests(String name) { super(name); } + + public void testSuffixList() { + if (!UnknownFileCheck.STATIC_ERRORS.isEmpty()) { + fail("" + UnknownFileCheck.STATIC_ERRORS); + } + } + public void testLicense_ajbrowser() { + checkLicense("ajbrowser"); + } + public void testLicense_ajde() { + checkLicense("ajde"); + } + public void testLicense_aspectj5rt() { + checkLicense("aspectj5rt"); + } + public void testLicense_asm() { + checkLicense("asm"); + } + + public void testLicense_bridge() { + checkLicense("bridge"); + } + public void testLicense_build() { + checkLicense("build"); + } + public void testLicense_org_aspectj_ajdt_core() { + checkLicense("org.aspectj.ajdt.core"); + } + public void testLicense_org_aspectj_lib() { + checkLicense("org.aspectj.lib"); + } + public void testLicense_org_eclipse_jdt_core() { + final String mod = "org.eclipse.jdt.core"; + final String pre = BASE_DIR + mod + File.separator; + for (int i = 0; i < JDT_SOURCE_DIRS.length; i++) { + checkSourceDirectory(new File(pre + JDT_SOURCE_DIRS[i]), mod); + } + } + + public void testLicense_runtime() { + checkLicense("runtime"); + } + public void testLicense_taskdefs() { + checkLicense("taskdefs"); + } + public void testLicense_testing() { + checkLicense("testing"); + } + public void testLicense_testing_client() { + checkLicense("testing-client"); + } + public void testLicense_testing_drivers() { + checkLicense("testing-drivers"); + } + public void testLicense_testing_util() { + checkLicense("testing-util"); + } + public void testLicense_util() { + checkLicense("util"); + } + public void testLicense_weaver() { + String module = "weaver"; + // skip (testdata) packages fluffy, reflect + checkSourceDirectory(new File(Util.path(new String[] {"..", module, "src"})), module); + checkSourceDirectory(new File(Util.path(new String[] {"..", module, "testsrc", "org"})), module); + } + + public void testLicense_ajdoc() { + checkLicense("ajdoc"); + } + + public void testLicense_loadtime() { + checkLicense("loadtime"); + } + + public void testLicense_loadtime5() { + checkLicense("loadtime5"); + } + + public void testLicense_weaver5() { + checkLicense("weaver5"); + } + + void checkLicense(String module) { + File moduleDir = new File(Util.path("..", module)); + File[] srcDirs = findSourceRoots(moduleDir); + for (int i = 0; i < srcDirs.length; i++) { + checkSourceDirectory(srcDirs[i], module); + } + } + + void checkSourceDirectory(File srcDir, String module) { + final String label = "source dir " + srcDir + " (module " + module + ")"; + assertTrue(label, (srcDir.exists() && srcDir.isDirectory())); + String license = getLicense(module); +// if (replacing) { +// if (replacing && true) { +// throw new Error("replacing done - code left for other replaces"); +// } +// assertTrue("aborting - replace failed", !replaceFailed); +// // do the replace +// int fails = Checklics.runDirect(moduleDir.getPath(), "replace-headers"); +// replaceFailed = (0 != fails); +// assertTrue(!replaceFailed); +// license = Checklics.CPL_IBM_PARC_XEROX_TAG; +// } + int fails = Checklics.runDirect(srcDir.getPath(), license, true); + if (0 != fails) { + if (replacing) { + BuildModuleTests.replaceFailed = true; + } + assertTrue(label + " fails", !BuildModuleTests.replaceFailed); + } + + // separate check to verify all file types (suffixes) are known + if (!"testsrc".equals(srcDir.getName())) { + ArrayList unknownFiles = new ArrayList(); + UnknownFileCheck.SINGLETON.unknownFiles(srcDir, unknownFiles); + if (!unknownFiles.isEmpty()) { + String s = "unknown files (see readme-build-module.html to " + + "update Builder.properties resource patterns): "; + fail(s + unknownFiles); + } + } + } + /** + * Check tree for files not managed by the build system + * (either source files or managed as resources). + * This should pick up situations where new kinds of resources are added + * to the tree without updating the build script patterns to pick them + * up. + * @see Builder#BINARY_SOURCE_PATTERN + * @see Builder#RESOURCE_PATTERN + * @see org.aspectj.util.FileUtil#SOURCE_SUFFIXES + */ + static class UnknownFileCheck implements FileFilter { + private static final UnknownFileCheck SINGLETON = new UnknownFileCheck(); + private static final ArrayList STATIC_ERRORS = new ArrayList(); + // Builder.BINARY_SOURCE_PATTERN and Builder.RESOURCE_PATTERN + public static final List KNOWN_SUFFIXES; + + static { + List suffixes = new ArrayList(); + // sources from org.aspectj.util.FileUtil.SOURCE_SUFFIXES + suffixes.add(".aj"); + suffixes.add(".java"); + + // just because we know... + suffixes.add(".html"); + + // others from Builder + final String input = Builder.BINARY_SOURCE_PATTERN + + "," + Builder.RESOURCE_PATTERN; + StringTokenizer st = new StringTokenizer(input, ","); + while (st.hasMoreTokens()) { + String token = st.nextToken().trim(); + if (0 == token.length()) { + continue; + } + if (token.startsWith("**/*.")) { + token = token.substring(4); + } else if (token.startsWith("*.")) { + token = token.substring(1); + } else { + String s = input + " at \"" + token + "\""; + STATIC_ERRORS.add("unable to read pattern: " + s); + } + suffixes.add(token); + } + KNOWN_SUFFIXES = Collections.unmodifiableList(suffixes); + } + + private UnknownFileCheck() { + + } + /** + * Return true if input File file is a valid path to a directory + * or to a file + * which is not hidden (starts with .) + * and does not have a known suffix. + * Caller is responsible for pruning CVS directories + * @return true iff unknown or a directory + */ + public boolean accept(File file) { + if (null == file) { + return false; + } + if (file.isDirectory()) { + return file.canRead(); + } + + String name = file.getName(); + if ("CVS".equals(name) || name.startsWith(".")) { + return false; + } + // to do not accepting uppercase suffixes... + for (String suffix: KNOWN_SUFFIXES) { + if (name.endsWith(suffix)) { + return false; + } + } + return true; + + } + void unknownFiles(File dir, ArrayList results) { + File[] files = dir.listFiles(this); + for (int j = 0; j < files.length; j++) { + File file = files[j]; + if (file.isDirectory()) { + String name = file.getName(); + if (!("CVS".equals(name))) { + unknownFiles(file, results); + } + } else { + results.add(file); + } + } + } + + } +} + diff --git a/build/src/test/java/org/aspectj/internal/build/BuildClasspathTest.java b/build/src/test/java/org/aspectj/internal/build/BuildClasspathTest.java new file mode 100644 index 000000000..b8cb4b896 --- /dev/null +++ b/build/src/test/java/org/aspectj/internal/build/BuildClasspathTest.java @@ -0,0 +1,67 @@ +/* ******************************************************************* + * Copyright (c) 2005 Contributors. + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://eclipse.org/legal/epl-v10.html + * + * Contributors: + * Wes Isberg initial implementation + * ******************************************************************/ + + +package org.aspectj.internal.build; + +import java.io.File; + +import junit.framework.TestCase; + +import org.aspectj.internal.tools.build.Messager; +import org.aspectj.internal.tools.build.Module; +import org.aspectj.internal.tools.build.Modules; +import org.aspectj.internal.tools.build.Result; +import org.aspectj.internal.tools.build.Result.Kind; + +public class BuildClasspathTest extends TestCase { + + public void testKindsGet() { + Kind kind = Result.kind(Result.NORMAL, Result.ASSEMBLE); + same(kind, "RELEASE_ALL"); + kind = Result.kind(Result.NORMAL, !Result.ASSEMBLE); + same(kind, "RELEASE"); + kind = Result.kind(!Result.NORMAL, Result.ASSEMBLE); + same(kind, "TEST_ALL"); + kind = Result.kind(!Result.NORMAL, !Result.ASSEMBLE); + same(kind, "TEST"); + } + private void same(Kind kind, String name) { + if (!name.equals(kind.toString())) { + fail("expected \"" + name + "\" got \"" + kind + "\""); + } + } + public void testClasspath() { + Messager handler = new Messager(); + File baseDir = new File(".."); + File jarDir = new File("../aj-build/jars"); + Modules modules = new Modules(baseDir, jarDir, handler); + Module module = modules.getModule("ajbrowser"); + Kind kind = Result.kind(Result.NORMAL, !Result.ASSEMBLE); + Result result = module.getResult(kind); + print(result); + } + public void testBuildClasspath() { + Messager handler = new Messager(); + File baseDir = new File(".."); + File jarDir = new File("../aj-build/jars"); + Modules modules = new Modules(baseDir, jarDir, handler); + Module module = modules.getModule("build"); + Kind kind = Result.kind(Result.NORMAL, !Result.ASSEMBLE); + Result result = module.getResult(kind); + print(result); + } + private void print(Result result) { + System.out.println(result + " libjars" + result.getLibJars()); + System.out.println(result + " required" + result.getRequired()); + } +} diff --git a/build/src/test/java/org/aspectj/internal/build/BuildModuleTest.java b/build/src/test/java/org/aspectj/internal/build/BuildModuleTest.java new file mode 100644 index 000000000..bc96bef6a --- /dev/null +++ b/build/src/test/java/org/aspectj/internal/build/BuildModuleTest.java @@ -0,0 +1,468 @@ +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC), + * 2005-2006 Contributors. + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + +package org.aspectj.internal.build; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.zip.ZipEntry; +import java.util.zip.ZipException; +import java.util.zip.ZipFile; + +import junit.framework.TestCase; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.taskdefs.Java; +import org.apache.tools.ant.types.Path; +import org.apache.tools.ant.types.Commandline.Argument; +import org.aspectj.internal.tools.ant.taskdefs.BuildModule; +import org.aspectj.internal.tools.ant.taskdefs.Checklics; +import org.aspectj.internal.tools.build.Util; + +/** + * Test our integrated taskdef build. + * This responds to two environment variables: + * (1) run.build.tests must be defined before + * tests that build the tree (and hence take minutes) + * will run; + * (2) build.config takes the same form as it does for the + * builder task, e.g., "useEclipseCompiles" will avoid + * recompiling with Javac and adopt classes in the + * {module}/bin directories. + */ +public class BuildModuleTest extends TestCase { + + private static boolean printInfoMessages = false; + private static boolean printedMessage; + private static final boolean REMOVE_JARS_AFTER_DEBUGGING = true; + // to just build one module verbosely + private static final String[] DEBUGS + = {}; + + // skip those requiring ajdoc, which requires tools.jar + // also skip those requiring java5 unless manually set up + // also skip big ones to avoid slowing the build too much + private static final String[] SKIPS + //= {}; + = {"aspectjtools", "ajdoc", "aspectj5rt", "run-all-junit-tests", + "ajbrowser", "testing", "testing-drivers", "org.aspectj.ajdt.core", "weaver"}; + + private static final String SKIP_MESSAGE = + "BuildModuleTest: Define \"run.build.tests\" as a system " + + "property to run tests to build "; + private static final String BUILD_CONFIG; + static { + String config = null; + try { + config = System.getProperty("build.config"); + } catch (Throwable t) { + // ignore + } + BUILD_CONFIG = config; + if (printInfoMessages) { + System.out.println("BuildModuleTest build.config: " + config); + } + } + + ArrayList tempFiles = new ArrayList(); + private File jarDir; + private boolean deleteJars; + boolean building; // must be enabled for tests to run + + public BuildModuleTest(String name) { + super(name); + building = Boolean.getBoolean("run.build.tests"); + } + protected void setUp() { + // change to view whether prior output is used + deleteJars = true; // todo + } + + protected void tearDown() throws Exception { + super.tearDown(); + if (debugging() && !REMOVE_JARS_AFTER_DEBUGGING) { + if (0 < tempFiles.size()) { + System.err.println("debugging files left: " + tempFiles); + } + return; + } + deleteTempFiles(); + } + + protected void deleteTempFiles() { + for (Iterator iter = tempFiles.iterator(); iter.hasNext();) { + File file = (File) iter.next(); + if (!Util.delete(file)) { + File[] list = file.listFiles(); + if (!Util.isEmpty(list)) { + StringBuffer sb = new StringBuffer(); + sb.append("warning: BuildModuleTest unable to delete "); + sb.append(file.toString()); + sb.append("\n"); // XXX platform + for (int i = 0; i < list.length; i++) { + sb.append(" "); + sb.append(list[i].toString()); + sb.append("\n"); // XXX platform + } + System.err.println(sb.toString()); + } + } + } + } + + public void testAllJunitTests() { + checkBuild("run-all-junit-tests"); + } + + public void testBuild() { + checkBuild("build", + Checklics.class.getName(), + new String[0], // help message + true); // ant needed + } + + public void testUtil() { + checkBuild("util"); + } + + public void testAsm() { + checkBuild("asm"); + } + + public void testRuntime() { + checkBuild("runtime"); + } + + public void testAspectj5rt() { + checkBuild("aspectj5rt"); + } + +// public void testLocalOutOfDate() { +// Messager handler = new Messager(); +// File jarDir = new File("c:/home/ws/head/aj-build/jars"); +// File baseDir = new File("c:/home/ws/head"); +// Modules mods = new Modules(baseDir, jarDir, handler); +// Module module = mods.getModule("ajbrowser"); +// Result r = module.getResult(Result.kind(true, true)); +// r.outOfDate(); +// } +// public void testAspectj5rtRequired() { +// File baseDir = new File(".."); +// Modules modules = new Modules(baseDir, getJarDir(), new Messager()); +// Module module = modules.getModule("aspectj5rt"); +// Result result = module.getResult(Result.kind(true, true)); +// Result[] results = result.getRequired(); +// System.out.println(result.toLongString()); +// System.out.println("results: " + Arrays.asList(results)); +// deleteTempFiles(); +// } + public void testNoDuplicates() { + File weaverAllJar = null; + try { + weaverAllJar = doTask("weaver",true, true, true); + } catch (Throwable t) { + System.err.println(getClass() + ".testNoDuplicates() incomplete"); + t.printStackTrace(System.err); + return; + } + String dupError = duplicateEntryError(weaverAllJar); + weaverAllJar.delete(); + if (null != dupError) { + fail(dupError); + } + } + public void testAjbrowser() { + checkBuild("ajbrowser", + "org.aspectj.tools.ajbrowser.Main", + new String[] {"-noExit", "-version"}); // compiler version + } + public void testTestingUtils() { + checkBuild("testing-util"); + } + + public void testAjdt() { + checkBuild("org.aspectj.ajdt.core", + "org.aspectj.tools.ajc.Main", + new String[] { "-noExit", "-version" }); + }// + public void testTesting() { + checkBuild("testing", + "org.aspectj.testing.util.LangUtilTest", + new String[] {"ignored"}); + } + public void testTestingDrivers() { + checkBuild("testing-drivers", + "org.aspectj.testing.drivers.Harness", + new String[] {"-help"}); + } + public void testWeaver() { + checkBuild("weaver"); + } + + // ajdoc relies on tools.jar + public void testAspectjtools() { + if (!shouldBuild("aspectjtools")) { + return; + } + File baseDir = new File(".."); + File tempBuildDir = new File(baseDir, "aj-build"); + File distDir = new File(tempBuildDir, "dist"); + File jarDir = new File(tempBuildDir, "jars"); + assertTrue(distDir.canWrite() || distDir.mkdirs()); + File productDir = new File(baseDir.getPath() + "/build/products/tools"); + assertTrue(""+productDir, productDir.canRead()); + checkBuildProduct(productDir, baseDir, distDir, jarDir); + } + + void checkBuildProduct(File productDir, File baseDir, File distDir, File jarDir) { + if (!shouldBuild(productDir.getPath())) { + return; + } + assertTrue(null != productDir); + assertTrue(productDir.canRead()); + + checkJavac(); + + BuildModule task = new BuildModule(); + Project project = new Project(); + task.setProject(project); + assertTrue(jarDir.canWrite() || jarDir.mkdirs()); + tempFiles.add(jarDir); + task.setJardir(new Path(project, jarDir.getAbsolutePath())); + task.setProductdir(new Path(project, productDir.getAbsolutePath())); + task.setBasedir(new Path(project, baseDir.getAbsolutePath())); + task.setDistdir(new Path(project, distDir.getAbsolutePath())); + task.setFailonerror(true); + if (null != BUILD_CONFIG) { + task.setBuildConfig(BUILD_CONFIG); + } + //task.setVerbose(true); + task.setCreateinstaller(true); + task.execute(); + // now run installer and do product tests? + } + + File getAntJar() { + return new File("../lib/ant/lib/ant.jar"); + } + File getJUnitJar() { + return new File("../lib/junit/junit.jar"); + } + + File getJarDir() { + if (null == jarDir) { + File baseDir = new File("../aj-build/"); + if (!baseDir.canWrite()) { + baseDir = new File("."); + } + jarDir = new File(baseDir, "BuildModuleTest-jars"); + tempFiles.add(jarDir); + } + if (!jarDir.exists()) { + assertTrue(jarDir.mkdirs()); + } + return jarDir; + } + + BuildModule getTask(String module) { + BuildModule task = new BuildModule(); + Project project = new Project(); + task.setProject(project); + File jarDir = getJarDir(); + assertTrue(jarDir.canWrite() || jarDir.mkdirs()); + tempFiles.add(jarDir); + File moduleDir = new File(Util.path("..", module)); + assertTrue(moduleDir.canRead()); + task.setModuledir(new Path(project, moduleDir.getAbsolutePath())); + task.setJardir(new Path(project, jarDir.getAbsolutePath())); + task.setFailonerror(true); + if (null != BUILD_CONFIG) { + task.setBuildConfig(BUILD_CONFIG); + } + return task; + } + + void checkBuild(String module) { + checkBuild(module, null, null, false); + } + + void checkBuild(String module, + String classname, + String[] args) { + checkBuild(module, classname, args, true); + } + + boolean shouldBuild(String target) { + if (null == target) { + return false; + } + if (!building && !printedMessage) { + System.err.println(SKIP_MESSAGE + target + " (this is the only warning)"); + printedMessage = true; + } + if (debugging()) { + for (int i = 0; i < DEBUGS.length; i++) { + if (target.equals(DEBUGS[i])) { + return true; + } + } + return false; + } else { + for (int i = 0; i < SKIPS.length; i++) { + if (SKIPS[i].equals(target)) { + if (printInfoMessages) { + System.err.println(target + " skipped build test [" + getClass().getName() + ".shouldBuild(..)]"); + } + return false; + } + } + } + return building; + } + private static boolean debugging() { + return ((null != DEBUGS) && (0 < DEBUGS.length)); + } + private static String duplicateEntryError(File weaverAllJar) { + ZipFile zipFile = null; + try { + zipFile = new ZipFile(weaverAllJar); + Enumeration e = zipFile.entries(); + ArrayList entryNames = new ArrayList(); + while (e.hasMoreElements()) { + ZipEntry entry = (ZipEntry) e.nextElement(); + String name = entry.getName(); + if (entryNames.contains(name)) { + return "duplicate entry: " + name; + } + entryNames.add(name); + } + } catch (ZipException e) { + return "ZipException " + e; + } catch (IOException e) { + return "IOException " + e; + } finally { + if (null != zipFile) { + try { + zipFile.close(); + } catch (IOException e) { + return "IOException closing " + zipFile + ": " + e; + } + } + } + return null; + } + + private static String name(String module, boolean trimTesting, boolean assemble) { + return module + (trimTesting?"":"-test") + (assemble?"-all":""); + } + private void deleteJar(File jar) { + if (!deleteJars) { + return ; + } + if (jar.exists()) { + jar.delete(); + } + if (jar.exists()) { + try { + Thread.sleep(5000); + } catch (Throwable t) { + } + } + if (jar.exists()) { + assertTrue("cannot delete " + jar, jar.delete()); + } + } + void checkBuild(String module, + String classname, + String[] args, + boolean addAnt) { + if (!shouldBuild(module)) { + return; + } + assertTrue(null != module); + checkJavac(); + doTask(module, true, false); + doTask(module, true, true); + doTask(module, false, false); + File jar = doTask(module, false, true, true); + + // verify if possible + if (null != classname) { + Java java = new Java(); + Project project = new Project(); + java.setProject(project); + java.setFailonerror(true); + Path cp = new Path(project); + assertTrue(jar.canRead()); + cp.append(new Path(project, jar.getAbsolutePath())); + if (addAnt) { + cp.append(new Path(project, getAntJar().getAbsolutePath())); + cp.append(new Path(project, getJUnitJar().getAbsolutePath())); + } + java.setClasspath(cp); + java.setClassname(classname); + if (null != args) { + for (int i = 0; i < args.length; i++) { + Argument arg = java.createArg(); + arg.setValue(args[i]); + } + } + try { + java.execute(); + } catch (BuildException e) { + e.printStackTrace(System.err); + assertTrue("BuildException running " + classname, false); + } + } + deleteJar(jar); + } + void doTask(String module, boolean trimTesting, boolean assembleAll) { + doTask(module, trimTesting, assembleAll, false); + } + + File doTask(String module, boolean trimTesting, boolean assembleAll, boolean keepJars) { + BuildModule task = getTask(module); + String name = name(module, trimTesting, assembleAll); + File jar = new File(getJarDir(), name+ ".jar"); + task.setAssembleall(assembleAll); + task.setTrimtesting(trimTesting); + task.execute(); + if (!jar.canRead()) { + File[] files = getJarDir().listFiles(); + fail("cannot read " + jar + " in " + Arrays.asList(files)); + } + if (!keepJars && deleteJars) { + deleteTempFiles(); + } + return jar; + } + + void checkJavac() { + boolean result = false; + try { + result = (null != Class.forName("sun.tools.javac.Main")); + } catch (Throwable t) { + // ignore + } + if (! result) { + assertTrue("add tools.jar to the classpath for Ant's use of javac", false); + } + } + +} diff --git a/build/src/test/java/org/aspectj/internal/build/ModulesTest.java b/build/src/test/java/org/aspectj/internal/build/ModulesTest.java new file mode 100644 index 000000000..16786404c --- /dev/null +++ b/build/src/test/java/org/aspectj/internal/build/ModulesTest.java @@ -0,0 +1,304 @@ +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC), + * 2005-2006 Contributors. + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * Wes Isberg build tests + * ******************************************************************/ + +package org.aspectj.internal.build; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +import junit.framework.TestCase; + +import org.apache.tools.ant.BuildEvent; +import org.apache.tools.ant.BuildListener; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.Task; +import org.apache.tools.ant.types.Path; +import org.aspectj.internal.tools.ant.taskdefs.AntBuilder; +import org.aspectj.internal.tools.ant.taskdefs.BuildModule; +import org.aspectj.internal.tools.build.Messager; +import org.aspectj.internal.tools.build.Module; +import org.aspectj.internal.tools.build.Modules; +import org.aspectj.internal.tools.build.Result; +import org.aspectj.internal.tools.build.Util; +import org.aspectj.internal.tools.build.Result.Kind; +/** + * + */ +public class ModulesTest extends TestCase { + public static final List MODULE_NAMES; + private static final File BASE_DIR = new File(".."); + static { + String[] names = { + "ajbrowser", "ajde", "ajdoc", "asm", "aspectj5rt", + "bridge", "loadtime", "loadtime5", "org.aspectj.ajdt.core", + "runtime", "taskdefs", "testing-client", "testing-util", + "tests", "util", "weaver"}; + List list = Arrays.asList(names); + MODULE_NAMES = Collections.unmodifiableList(list); + } + + private static boolean delete(File file) { // XXX Util + if ((null == file) || !file.exists()) { + return true; + } + if (file.isFile()) { + return file.delete(); + } else { + File[] files = file.listFiles(); + boolean result = true; + for (int i = 0; i < files.length; i++) { + if (!ModulesTest.delete(files[i]) + && result) { + result = false; + } + } + return (file.delete() && result); + } + } + + ArrayList tempFiles = new ArrayList(); + + public ModulesTest(String name) { + super(name); + } + + protected void tearDown() throws Exception { + super.tearDown(); + for (Iterator iter = tempFiles.iterator(); iter.hasNext();) { + File file = (File) iter.next(); + if (!ModulesTest.delete(file)) { + System.err.println("warning: ModulesTest unable to delete " + file); + } + } + } + Modules getModules(Messager handler) { + File jarDir = new File("../aj-build-test-jars"); + if (!jarDir.exists()) { + assertTrue(jarDir.mkdirs()); + tempFiles.add(jarDir); + } + File baseDir = new File(".."); + if (null == handler) { + handler = new Messager(); + } + return new Modules(baseDir, jarDir, handler); + } + + public void testAllModulesCreation() { + ArrayList badModules = new ArrayList(); + for (String name: MODULE_NAMES) { + File dir = new File(BASE_DIR, name); + if (dir.isDirectory()) { + File classpath = new File(dir, ".classpath"); + if (classpath.exists()) { + Modules modules = getModules(null); + Module module = modules.getModule(name); + if (!module.valid) { + badModules.add(module); + } + } + } + } + if (!badModules.isEmpty()) { + StringBuffer sb = new StringBuffer(); + for (Module module: badModules) { + System.err.println(module.toLongString()); + sb.append("\n"); + sb.append(module); + } + fail(sb.toString()); + } + } + + void checkModule(String s) { + if ("docs".equals(s) || "lib".equals(s)) { + return; + } + Modules modules = getModules(null); + Module module = modules.getModule(s); + if (!module.valid) { + assertTrue(module.toLongString(), false); + } + } + + public void testClasspathCreation() { + Modules modules = getModules(null); + Module ajdt = modules.getModule("org.aspectj.ajdt.core"); + assertTrue(ajdt.valid); + + Project project = new Project(); + AntBuilder builder = getBuilder(project); + Path classpath = new Path(project); + Kind kind = Result.kind(Result.NORMAL, !Result.ASSEMBLE); + Result result = ajdt.getResult(kind); + boolean hasLibraries = builder.setupClasspath(result, classpath); + assertTrue(hasLibraries); + if ((null == classpath) || (2 > classpath.size())) { + assertTrue(classpath.toString(), false); + } + } + + /** + * This test requires two OSGI modules: + * org.aspectj.util, which optionally depends on tempaspectjrt. + * Currently, the Ant builder does not handle linked source folders, + * and the OSGI support does not work around optional plugins. + */ + public void skip_testOSGIModuleCreation() { + final String MODULE = "org.aspectj.util"; + final String USES_MODULE = "tempaspectjrt"; + + Modules modules = getModules(null); + Module newutil = modules.getModule(MODULE); + assertTrue(newutil.valid); + + Project project = new Project(); + AntBuilder builder = getBuilder(project); + Path classpath = new Path(project); + Kind kind = Result.kind(Result.NORMAL, !Result.ASSEMBLE); + Result result = newutil.getResult(kind); + builder.setupClasspath(result, classpath); + System.out.println(newutil + " classpath: " + classpath); + if ((1 != classpath.size())) { + assertTrue(classpath.toString(), false); + } + String cpEntry = classpath.list()[0]; + if (!cpEntry.endsWith(USES_MODULE + ".jar")) { + fail("expected " + classpath + " to end with " + USES_MODULE + ".jar"); + } + } + + private AntBuilder getBuilder(Project project) { + project.setBaseDir(new File(".")); + project.setName("testOSGIModuleCreation"); + File tempDir = new File("."); + return (AntBuilder) AntBuilder.getBuilder("", project, tempDir); + } + + + /********************************************************************* + * The following tests/code enable you to run the entire build in JUnit + * to debug directly from Eclipse. To compile using Javac, you will + * need to add tools.jar to the run classpath. + */ + public void skip_testBuildingAspectJModule() { + final String moduleName = "org.aspectj.lib"; + + File modulesDir = new File("..").getAbsoluteFile(); + File buildDir = new File(modulesDir, "aj-build"); + File distDir = new File(buildDir, "dist"); + File jarDir = new File(buildDir, "jars"); + File moduleDir = new File(modulesDir, moduleName); + File jar = new File(jarDir, "org.aspectj.lib.jar"); + jarDir.mkdirs(); + distDir.mkdirs(); + if (jar.canRead()) { + assertTrue(jar.delete()); + } + Project project = new Project(); + project.setBaseDir(modulesDir); + project.setName("testAspectjbuild"); + + BuildModule bm = new BuildModule(); + bm.setProject(project); + bm.setAssembleall(true); + bm.setBuildConfig(""); + bm.setModule(moduleName); + bm.setBasedir(new Path(project, modulesDir.getPath())); + bm.setDistdir(new Path(project, buildDir.getPath())); + bm.setJardir(new Path(project, jarDir.getPath())); + bm.setModuledir(new Path(project, moduleDir.getPath())); + bm.setTrimtesting(true); + bm.setBuildConfig(""); + bm.setVersion("1.2"); + bm.setVerbose(true); + bm.setFailonerror(true); + + bm.execute(); + + assertTrue(jar.canRead()); + } + + public void skip_testBuildingProduct() { + final String productName = "tools"; + File modulesDir = new File("..").getAbsoluteFile(); + File buildDir = new File(modulesDir, "aj-build"); + File distDir = new File(buildDir, "dist"); + File jarDir = new File(buildDir, "jars"); + File productDir = new File(modulesDir, + Util.path(new String[] {"build", "products", productName})); + + jarDir.mkdirs(); + distDir.mkdirs(); + + Project project = new Project(); + project.setBaseDir(modulesDir); + project.setName("testAspectjToolsbuild"); + project.addBuildListener(new EventBuildListener(Project.MSG_WARN)); + + BuildModule bm = new BuildModule(); + bm.setProject(project); + bm.setAssembleall(true); + bm.setBuildConfig(""); + bm.setProductdir(new Path(project, productDir.getPath())); + bm.setBasedir(new Path(project, modulesDir.getPath())); + bm.setDistdir(new Path(project, distDir.getPath())); + bm.setJardir(new Path(project, jarDir.getPath())); + bm.setTrimtesting(true); + bm.setBuildConfig(""); + bm.setVersion("1.2"); + bm.setFailonerror(true); + bm.execute(); + + File libDir = new File(distDir, "tools/lib"); + String[] jars = { "tools", "rt", "weaver", "lib"}; + for (int i = 0; i < jars.length; i++) { + File jar = new File(libDir, "aspectj" + jars[i] + ".jar"); + assertTrue(jar.getPath(), jar.canRead()); + if (10 > jar.length()) { + assertTrue(jar + " too small", false); + } + } + } + /** + * Show messages from the task. + * (normally shown by Ant's default listener) + */ + static class EventBuildListener implements BuildListener { + final int min; + EventBuildListener(int min) { + this.min = min; + } + public void buildFinished(BuildEvent event) {} + public void buildStarted(BuildEvent event) { } + public void messageLogged(BuildEvent event) { + if (min <= event.getPriority()) { + Task t = event.getTask(); + String src = (null == t ? "project" : t.getTaskName()); + System.out.println(src + ": " + event.getMessage()); + } + } + public void targetFinished(BuildEvent event) { } + public void targetStarted(BuildEvent event) { } + public void taskFinished(BuildEvent event) { } + public void taskStarted(BuildEvent event) { } + + } + +} diff --git a/build/src/test/java/org/aspectj/internal/tools/build/UtilsTest.01.MF b/build/src/test/java/org/aspectj/internal/tools/build/UtilsTest.01.MF new file mode 100644 index 000000000..e3ba88396 --- /dev/null +++ b/build/src/test/java/org/aspectj/internal/tools/build/UtilsTest.01.MF @@ -0,0 +1,8 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Client Plug-in +Bundle-SymbolicName: org.aspectj.testing.client +Bundle-Version: 1.0.0 +Bundle-Localization: plugin +Bundle-ClassPath: lib/commons/commons.jar + diff --git a/build/src/test/java/org/aspectj/internal/tools/build/UtilsTest.02.MF b/build/src/test/java/org/aspectj/internal/tools/build/UtilsTest.02.MF new file mode 100644 index 000000000..5888ab3c0 --- /dev/null +++ b/build/src/test/java/org/aspectj/internal/tools/build/UtilsTest.02.MF @@ -0,0 +1,9 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Client Plug-in +Bundle-SymbolicName: org.aspectj.testing.client +Bundle-Version: 1.0.0 +Bundle-Localization: plugin +Bundle-ClassPath: lib/commons/commons.jar, lib/ant/lib/ant.jar +Require-Bundle: util, org.aspectj.runtime + diff --git a/build/src/test/java/org/aspectj/internal/tools/build/UtilsTest.03.MF b/build/src/test/java/org/aspectj/internal/tools/build/UtilsTest.03.MF new file mode 100644 index 000000000..b9717c5f2 --- /dev/null +++ b/build/src/test/java/org/aspectj/internal/tools/build/UtilsTest.03.MF @@ -0,0 +1,9 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Client Plug-in +Bundle-SymbolicName: org.aspectj.testing.client +Bundle-Version: 1.0.0 +Bundle-Localization: plugin +Bundle-ClassPath: lib/commons/commons.jar, lib/ant/lib/ant.jar +Require-Bundle: util, aspectjrt;bundle-version="[1.5.0,1.5.5]";resolution:=optional + diff --git a/build/src/test/java/org/aspectj/internal/tools/build/UtilsTest.java b/build/src/test/java/org/aspectj/internal/tools/build/UtilsTest.java new file mode 100644 index 000000000..4926d42e8 --- /dev/null +++ b/build/src/test/java/org/aspectj/internal/tools/build/UtilsTest.java @@ -0,0 +1,200 @@ +/* ******************************************************************* + * Copyright (c) 2006 Contributors. + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://eclipse.org/legal/epl-v10.html + * + * Contributors: + * Wes Isberg initial implementation + * ******************************************************************/ + +package org.aspectj.internal.tools.build; + +import java.io.IOException; +import java.util.jar.Attributes.Name; + +import junit.framework.TestCase; + +import org.aspectj.internal.tools.build.Util.OSGIBundle; +import org.aspectj.internal.tools.build.Util.OSGIBundle.RequiredBundle; + +public class UtilsTest extends TestCase { + private static final String PREFIX = UtilsTest.class.getName().replace('.', + '/'); + + private static final ClassLoader LOADER = UtilsTest.class.getClassLoader(); + + private static final ManifestTest[] TESTS = { + new ManifestTest("01", + new Name[] { OSGIBundle.BUNDLE_CLASSPATH, + OSGIBundle.BUNDLE_SYMBOLIC_NAME, + OSGIBundle.BUNDLE_VERSION }, new String[] { + "lib/commons/commons.jar", + "org.aspectj.testing.client", "1.0.0" }), + new ManifestTest("02", + new Name[] { OSGIBundle.BUNDLE_SYMBOLIC_NAME, + OSGIBundle.BUNDLE_VERSION }, new String[] { + "org.aspectj.testing.client", "1.0.0" }, + new String[] { "lib/commons/commons.jar", + "lib/ant/lib/ant.jar" }, new String[] { "util", + "org.aspectj.runtime" }), + new ManifestTest("03", + new Name[] { OSGIBundle.BUNDLE_SYMBOLIC_NAME, + OSGIBundle.BUNDLE_VERSION }, new String[] { + "org.aspectj.testing.client", "1.0.0" }, + new String[] { "lib/commons/commons.jar", + "lib/ant/lib/ant.jar" }, new String[] { "util", + "aspectjrt" }) { + void checkOthers(OSGIBundle osgiBundle, StringBuffer sb) { + RequiredBundle[] bundles = osgiBundle.getRequiredBundles(); + for (int i = 0; i < bundles.length; i++) { + RequiredBundle bundle = bundles[i]; + if ("aspectjrt".equals(bundle.name)) { + if (!bundle.optional) { + sb + .append("expected required bundle aspectjrt to be optional"); + } + String version = "[1.5.0,1.5.5]"; + if (!(version.equals(bundle.versions))) { + sb.append("expected version " + version + + " got " + bundle.versions + + " for required bundle aspectjrt"); + } + } + } + + } + } }; + + private static class ManifestTest { + final String name; + + final Name[] expectedNames; + + final String[] expectedValues; + + final String[] classpathEntries; + + final String[] requiredBundleNames; + + ManifestTest(String name, Name[] expectedNames, String[] expectedValues) { + this(name, expectedNames, expectedValues, null, null); + } + + ManifestTest(String name, Name[] expectedNames, + String[] expectedValues, String[] classpathEntries, + String[] requiredBundleNames) { + this.name = name; + this.expectedNames = expectedNames; + this.expectedValues = expectedValues; + this.classpathEntries = classpathEntries; + this.requiredBundleNames = requiredBundleNames; + } + + void run(StringBuffer sb) throws IOException { + String path = PREFIX + "." + name + ".MF"; + OSGIBundle bundle = new OSGIBundle(LOADER.getResourceAsStream(path)); + int len = sb.length(); + checkNamesAndValues(bundle, sb); + checkOthers(bundle, sb); + if (sb.length() != len) { + sb.append("failure was in test " + name); + } + } + + void checkOthers(OSGIBundle bundle, StringBuffer sb) { + } + + void checkNamesAndValues(OSGIBundle bundle, StringBuffer sb) { + for (int i = 0; i < expectedNames.length; i++) { + Name name = expectedNames[i]; + String expected = expectedValues[i]; + String actual = bundle.getAttribute(expectedNames[i]); + if (!((expected == actual) || expected.equals(actual))) { + sb.append(name); + sb.append(" "); + sb.append("expected "); + sb.append(expected); + sb.append("actual "); + sb.append(actual); + sb.append("\n"); + } + } + if (null != classpathEntries) { + String[] cp = bundle.getClasspath(); + Util.reportMemberDiffs(classpathEntries, cp, sb); + } + if (null != requiredBundleNames) { + RequiredBundle[] bundles = bundle.getRequiredBundles(); + String[] names = new String[bundles.length]; + for (int i = 0; i < names.length; i++) { + names[i] = bundles[i].name; + } + Util.reportMemberDiffs(requiredBundleNames, names, sb); + } + } + } + + /** disabled pending research */ + public void skip_testOSGIManifests() throws Exception { + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < TESTS.length; i++) { + TESTS[i].run(sb); + } + if (0 < sb.length()) { + fail(sb.toString()); + } + } + + public void testReportMemberDiffs() { + StringBuffer sb = new StringBuffer(); + String[] exp = null; + String[] act = null; + assertFalse(Util.reportMemberDiffs(exp, act, sb)); + assertEquals("", sb.toString()); + + sb.setLength(0); + exp = new String[] { "" }; + act = null; + assertTrue(Util.reportMemberDiffs(exp, act, sb)); + assertEquals("unexpected [] missing [\"\"]", sb.toString()); + + sb.setLength(0); + exp = null; + act = new String[] { "" }; + assertTrue(Util.reportMemberDiffs(exp, act, sb)); + assertEquals("unexpected [\"\"] missing []", sb.toString()); + + sb.setLength(0); + exp = new String[] { "1", "2", "3" }; + act = new String[] { "2", "4" }; + assertTrue(Util.reportMemberDiffs(exp, act, sb)); + assertEquals("unexpected [\"4\"] missing [\"1\", \"3\"]", sb.toString()); + + } + // public void testResourceStream() throws Exception { + // String path = PREFIX + ".one.mf"; + // System.out.println(path); + // InputStream in = LOADER.getResourceAsStream(path); + // int i; + // while (-1 != (i = in.read())) { + // System.out.print((char) i); + // } + // System.out.println(); + // } + // Map map = bundle.manifest.getEntries(); + // for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) { + // MapEntry entry = (MapEntry) iter.next(); + // System.out.println("entry: " + entry); + // } + // System.out.println("main attributes"); + // Attributes attributes = bundle.manifest.getMainAttributes(); + // Set keys = attributes.keySet(); + // for (Iterator iter = keys.iterator(); iter.hasNext();) { + // Object key = iter.next(); + // System.out.println(" key " + key); + // System.out.println(" value " + attributes.getValue(key.toString())); + // } +} diff --git a/build/testsrc/org/aspectj/build/BuildModuleTests.java b/build/testsrc/org/aspectj/build/BuildModuleTests.java deleted file mode 100644 index 52510c75f..000000000 --- a/build/testsrc/org/aspectj/build/BuildModuleTests.java +++ /dev/null @@ -1,304 +0,0 @@ -package org.aspectj.build; -/* ******************************************************************* - * Copyright (c) 1999-2001 Xerox Corporation, - * 2002 Palo Alto Research Center, Incorporated (PARC). - * All rights reserved. - * This program and the accompanying materials are made available - * under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Xerox/PARC initial implementation - * ******************************************************************/ - - -// default package - -import org.aspectj.internal.tools.ant.taskdefs.Checklics; -import org.aspectj.internal.tools.build.Builder; -import org.aspectj.internal.tools.build.Util; -import org.aspectj.internal.tools.build.UtilsTest; -import org.aspectj.internal.build.BuildModuleTest; -import org.aspectj.internal.build.ModulesTest; - -import java.io.File; -import java.io.FileFilter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.StringTokenizer; - -import junit.framework.*; - -/** - * Master suite for build module - * and test of all source directories for correct licenses and known file types. - */ -public class BuildModuleTests extends TestCase { - - /** if true, then replace old headers with new first */ - private static final boolean replacing = false; // XXX never to enable again... - - /** replace commented out below - if any replace failed, halt all */ - private static boolean replaceFailed = false; - - private static final String BASE_DIR = ".." + File.separator; - private static final String[] JDT_SOURCE_DIRS = new String[] {}; - - public static Test suite() { - TestSuite suite = new TestSuite("Build module tests"); - suite.addTestSuite(BuildModuleTests.class); - suite.addTestSuite(BuildModuleTest.class); - suite.addTestSuite(ModulesTest.class); - suite.addTestSuite(UtilsTest.class); - return suite; - } - - /** @return String tag of license if not default */ - public static String getLicense(String module) { - return null; // use permissive default - } - - final static List SOURCE_NAMES = Collections.unmodifiableList( - Arrays.asList(new String[]{"src", "testsrc", "java5-src", "java5-testsrc", "aspectj-src"})); - - /** - * @param moduleDir - * @return - */ - private static File[] findSourceRoots(File moduleDir) { - ArrayList result = new ArrayList(); - for (String name: SOURCE_NAMES) { - File srcDir = new File(moduleDir, name); - if (srcDir.canRead() && srcDir.isDirectory()) { - result.add(srcDir); - } - } - return (File[]) result.toArray(new File[0]); - } - - public BuildModuleTests(String name) { super(name); } - - public void testSuffixList() { - if (!UnknownFileCheck.STATIC_ERRORS.isEmpty()) { - fail("" + UnknownFileCheck.STATIC_ERRORS); - } - } - public void testLicense_ajbrowser() { - checkLicense("ajbrowser"); - } - public void testLicense_ajde() { - checkLicense("ajde"); - } - public void testLicense_aspectj5rt() { - checkLicense("aspectj5rt"); - } - public void testLicense_asm() { - checkLicense("asm"); - } - - public void testLicense_bridge() { - checkLicense("bridge"); - } - public void testLicense_build() { - checkLicense("build"); - } - public void testLicense_org_aspectj_ajdt_core() { - checkLicense("org.aspectj.ajdt.core"); - } - public void testLicense_org_aspectj_lib() { - checkLicense("org.aspectj.lib"); - } - public void testLicense_org_eclipse_jdt_core() { - final String mod = "org.eclipse.jdt.core"; - final String pre = BASE_DIR + mod + File.separator; - for (int i = 0; i < JDT_SOURCE_DIRS.length; i++) { - checkSourceDirectory(new File(pre + JDT_SOURCE_DIRS[i]), mod); - } - } - - public void testLicense_runtime() { - checkLicense("runtime"); - } - public void testLicense_taskdefs() { - checkLicense("taskdefs"); - } - public void testLicense_testing() { - checkLicense("testing"); - } - public void testLicense_testing_client() { - checkLicense("testing-client"); - } - public void testLicense_testing_drivers() { - checkLicense("testing-drivers"); - } - public void testLicense_testing_util() { - checkLicense("testing-util"); - } - public void testLicense_util() { - checkLicense("util"); - } - public void testLicense_weaver() { - String module = "weaver"; - // skip (testdata) packages fluffy, reflect - checkSourceDirectory(new File(Util.path(new String[] {"..", module, "src"})), module); - checkSourceDirectory(new File(Util.path(new String[] {"..", module, "testsrc", "org"})), module); - } - - public void testLicense_ajdoc() { - checkLicense("ajdoc"); - } - - public void testLicense_loadtime() { - checkLicense("loadtime"); - } - - public void testLicense_loadtime5() { - checkLicense("loadtime5"); - } - - public void testLicense_weaver5() { - checkLicense("weaver5"); - } - - void checkLicense(String module) { - File moduleDir = new File(Util.path("..", module)); - File[] srcDirs = findSourceRoots(moduleDir); - for (int i = 0; i < srcDirs.length; i++) { - checkSourceDirectory(srcDirs[i], module); - } - } - - void checkSourceDirectory(File srcDir, String module) { - final String label = "source dir " + srcDir + " (module " + module + ")"; - assertTrue(label, (srcDir.exists() && srcDir.isDirectory())); - String license = getLicense(module); -// if (replacing) { -// if (replacing && true) { -// throw new Error("replacing done - code left for other replaces"); -// } -// assertTrue("aborting - replace failed", !replaceFailed); -// // do the replace -// int fails = Checklics.runDirect(moduleDir.getPath(), "replace-headers"); -// replaceFailed = (0 != fails); -// assertTrue(!replaceFailed); -// license = Checklics.CPL_IBM_PARC_XEROX_TAG; -// } - int fails = Checklics.runDirect(srcDir.getPath(), license, true); - if (0 != fails) { - if (replacing) { - BuildModuleTests.replaceFailed = true; - } - assertTrue(label + " fails", !BuildModuleTests.replaceFailed); - } - - // separate check to verify all file types (suffixes) are known - if (!"testsrc".equals(srcDir.getName())) { - ArrayList unknownFiles = new ArrayList(); - UnknownFileCheck.SINGLETON.unknownFiles(srcDir, unknownFiles); - if (!unknownFiles.isEmpty()) { - String s = "unknown files (see readme-build-module.html to " - + "update Builder.properties resource patterns): "; - fail(s + unknownFiles); - } - } - } - /** - * Check tree for files not managed by the build system - * (either source files or managed as resources). - * This should pick up situations where new kinds of resources are added - * to the tree without updating the build script patterns to pick them - * up. - * @see Builder#BINARY_SOURCE_PATTERN - * @see Builder#RESOURCE_PATTERN - * @see org.aspectj.util.FileUtil#SOURCE_SUFFIXES - */ - static class UnknownFileCheck implements FileFilter { - private static final UnknownFileCheck SINGLETON = new UnknownFileCheck(); - private static final ArrayList STATIC_ERRORS = new ArrayList(); - // Builder.BINARY_SOURCE_PATTERN and Builder.RESOURCE_PATTERN - public static final List KNOWN_SUFFIXES; - - static { - List suffixes = new ArrayList(); - // sources from org.aspectj.util.FileUtil.SOURCE_SUFFIXES - suffixes.add(".aj"); - suffixes.add(".java"); - - // just because we know... - suffixes.add(".html"); - - // others from Builder - final String input = Builder.BINARY_SOURCE_PATTERN - + "," + Builder.RESOURCE_PATTERN; - StringTokenizer st = new StringTokenizer(input, ","); - while (st.hasMoreTokens()) { - String token = st.nextToken().trim(); - if (0 == token.length()) { - continue; - } - if (token.startsWith("**/*.")) { - token = token.substring(4); - } else if (token.startsWith("*.")) { - token = token.substring(1); - } else { - String s = input + " at \"" + token + "\""; - STATIC_ERRORS.add("unable to read pattern: " + s); - } - suffixes.add(token); - } - KNOWN_SUFFIXES = Collections.unmodifiableList(suffixes); - } - - private UnknownFileCheck() { - - } - /** - * Return true if input File file is a valid path to a directory - * or to a file - * which is not hidden (starts with .) - * and does not have a known suffix. - * Caller is responsible for pruning CVS directories - * @return true iff unknown or a directory - */ - public boolean accept(File file) { - if (null == file) { - return false; - } - if (file.isDirectory()) { - return file.canRead(); - } - - String name = file.getName(); - if ("CVS".equals(name) || name.startsWith(".")) { - return false; - } - // to do not accepting uppercase suffixes... - for (String suffix: KNOWN_SUFFIXES) { - if (name.endsWith(suffix)) { - return false; - } - } - return true; - - } - void unknownFiles(File dir, ArrayList results) { - File[] files = dir.listFiles(this); - for (int j = 0; j < files.length; j++) { - File file = files[j]; - if (file.isDirectory()) { - String name = file.getName(); - if (!("CVS".equals(name))) { - unknownFiles(file, results); - } - } else { - results.add(file); - } - } - } - - } -} - diff --git a/build/testsrc/org/aspectj/internal/build/BuildClasspathTest.java b/build/testsrc/org/aspectj/internal/build/BuildClasspathTest.java deleted file mode 100644 index b8cb4b896..000000000 --- a/build/testsrc/org/aspectj/internal/build/BuildClasspathTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ******************************************************************* - * Copyright (c) 2005 Contributors. - * All rights reserved. - * This program and the accompanying materials are made available - * under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution and is available at - * http://eclipse.org/legal/epl-v10.html - * - * Contributors: - * Wes Isberg initial implementation - * ******************************************************************/ - - -package org.aspectj.internal.build; - -import java.io.File; - -import junit.framework.TestCase; - -import org.aspectj.internal.tools.build.Messager; -import org.aspectj.internal.tools.build.Module; -import org.aspectj.internal.tools.build.Modules; -import org.aspectj.internal.tools.build.Result; -import org.aspectj.internal.tools.build.Result.Kind; - -public class BuildClasspathTest extends TestCase { - - public void testKindsGet() { - Kind kind = Result.kind(Result.NORMAL, Result.ASSEMBLE); - same(kind, "RELEASE_ALL"); - kind = Result.kind(Result.NORMAL, !Result.ASSEMBLE); - same(kind, "RELEASE"); - kind = Result.kind(!Result.NORMAL, Result.ASSEMBLE); - same(kind, "TEST_ALL"); - kind = Result.kind(!Result.NORMAL, !Result.ASSEMBLE); - same(kind, "TEST"); - } - private void same(Kind kind, String name) { - if (!name.equals(kind.toString())) { - fail("expected \"" + name + "\" got \"" + kind + "\""); - } - } - public void testClasspath() { - Messager handler = new Messager(); - File baseDir = new File(".."); - File jarDir = new File("../aj-build/jars"); - Modules modules = new Modules(baseDir, jarDir, handler); - Module module = modules.getModule("ajbrowser"); - Kind kind = Result.kind(Result.NORMAL, !Result.ASSEMBLE); - Result result = module.getResult(kind); - print(result); - } - public void testBuildClasspath() { - Messager handler = new Messager(); - File baseDir = new File(".."); - File jarDir = new File("../aj-build/jars"); - Modules modules = new Modules(baseDir, jarDir, handler); - Module module = modules.getModule("build"); - Kind kind = Result.kind(Result.NORMAL, !Result.ASSEMBLE); - Result result = module.getResult(kind); - print(result); - } - private void print(Result result) { - System.out.println(result + " libjars" + result.getLibJars()); - System.out.println(result + " required" + result.getRequired()); - } -} diff --git a/build/testsrc/org/aspectj/internal/build/BuildModuleTest.java b/build/testsrc/org/aspectj/internal/build/BuildModuleTest.java deleted file mode 100644 index bc96bef6a..000000000 --- a/build/testsrc/org/aspectj/internal/build/BuildModuleTest.java +++ /dev/null @@ -1,468 +0,0 @@ -/* ******************************************************************* - * Copyright (c) 1999-2001 Xerox Corporation, - * 2002 Palo Alto Research Center, Incorporated (PARC), - * 2005-2006 Contributors. - * All rights reserved. - * This program and the accompanying materials are made available - * under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Xerox/PARC initial implementation - * ******************************************************************/ - -package org.aspectj.internal.build; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.zip.ZipEntry; -import java.util.zip.ZipException; -import java.util.zip.ZipFile; - -import junit.framework.TestCase; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Project; -import org.apache.tools.ant.taskdefs.Java; -import org.apache.tools.ant.types.Path; -import org.apache.tools.ant.types.Commandline.Argument; -import org.aspectj.internal.tools.ant.taskdefs.BuildModule; -import org.aspectj.internal.tools.ant.taskdefs.Checklics; -import org.aspectj.internal.tools.build.Util; - -/** - * Test our integrated taskdef build. - * This responds to two environment variables: - * (1) run.build.tests must be defined before - * tests that build the tree (and hence take minutes) - * will run; - * (2) build.config takes the same form as it does for the - * builder task, e.g., "useEclipseCompiles" will avoid - * recompiling with Javac and adopt classes in the - * {module}/bin directories. - */ -public class BuildModuleTest extends TestCase { - - private static boolean printInfoMessages = false; - private static boolean printedMessage; - private static final boolean REMOVE_JARS_AFTER_DEBUGGING = true; - // to just build one module verbosely - private static final String[] DEBUGS - = {}; - - // skip those requiring ajdoc, which requires tools.jar - // also skip those requiring java5 unless manually set up - // also skip big ones to avoid slowing the build too much - private static final String[] SKIPS - //= {}; - = {"aspectjtools", "ajdoc", "aspectj5rt", "run-all-junit-tests", - "ajbrowser", "testing", "testing-drivers", "org.aspectj.ajdt.core", "weaver"}; - - private static final String SKIP_MESSAGE = - "BuildModuleTest: Define \"run.build.tests\" as a system " - + "property to run tests to build "; - private static final String BUILD_CONFIG; - static { - String config = null; - try { - config = System.getProperty("build.config"); - } catch (Throwable t) { - // ignore - } - BUILD_CONFIG = config; - if (printInfoMessages) { - System.out.println("BuildModuleTest build.config: " + config); - } - } - - ArrayList tempFiles = new ArrayList(); - private File jarDir; - private boolean deleteJars; - boolean building; // must be enabled for tests to run - - public BuildModuleTest(String name) { - super(name); - building = Boolean.getBoolean("run.build.tests"); - } - protected void setUp() { - // change to view whether prior output is used - deleteJars = true; // todo - } - - protected void tearDown() throws Exception { - super.tearDown(); - if (debugging() && !REMOVE_JARS_AFTER_DEBUGGING) { - if (0 < tempFiles.size()) { - System.err.println("debugging files left: " + tempFiles); - } - return; - } - deleteTempFiles(); - } - - protected void deleteTempFiles() { - for (Iterator iter = tempFiles.iterator(); iter.hasNext();) { - File file = (File) iter.next(); - if (!Util.delete(file)) { - File[] list = file.listFiles(); - if (!Util.isEmpty(list)) { - StringBuffer sb = new StringBuffer(); - sb.append("warning: BuildModuleTest unable to delete "); - sb.append(file.toString()); - sb.append("\n"); // XXX platform - for (int i = 0; i < list.length; i++) { - sb.append(" "); - sb.append(list[i].toString()); - sb.append("\n"); // XXX platform - } - System.err.println(sb.toString()); - } - } - } - } - - public void testAllJunitTests() { - checkBuild("run-all-junit-tests"); - } - - public void testBuild() { - checkBuild("build", - Checklics.class.getName(), - new String[0], // help message - true); // ant needed - } - - public void testUtil() { - checkBuild("util"); - } - - public void testAsm() { - checkBuild("asm"); - } - - public void testRuntime() { - checkBuild("runtime"); - } - - public void testAspectj5rt() { - checkBuild("aspectj5rt"); - } - -// public void testLocalOutOfDate() { -// Messager handler = new Messager(); -// File jarDir = new File("c:/home/ws/head/aj-build/jars"); -// File baseDir = new File("c:/home/ws/head"); -// Modules mods = new Modules(baseDir, jarDir, handler); -// Module module = mods.getModule("ajbrowser"); -// Result r = module.getResult(Result.kind(true, true)); -// r.outOfDate(); -// } -// public void testAspectj5rtRequired() { -// File baseDir = new File(".."); -// Modules modules = new Modules(baseDir, getJarDir(), new Messager()); -// Module module = modules.getModule("aspectj5rt"); -// Result result = module.getResult(Result.kind(true, true)); -// Result[] results = result.getRequired(); -// System.out.println(result.toLongString()); -// System.out.println("results: " + Arrays.asList(results)); -// deleteTempFiles(); -// } - public void testNoDuplicates() { - File weaverAllJar = null; - try { - weaverAllJar = doTask("weaver",true, true, true); - } catch (Throwable t) { - System.err.println(getClass() + ".testNoDuplicates() incomplete"); - t.printStackTrace(System.err); - return; - } - String dupError = duplicateEntryError(weaverAllJar); - weaverAllJar.delete(); - if (null != dupError) { - fail(dupError); - } - } - public void testAjbrowser() { - checkBuild("ajbrowser", - "org.aspectj.tools.ajbrowser.Main", - new String[] {"-noExit", "-version"}); // compiler version - } - public void testTestingUtils() { - checkBuild("testing-util"); - } - - public void testAjdt() { - checkBuild("org.aspectj.ajdt.core", - "org.aspectj.tools.ajc.Main", - new String[] { "-noExit", "-version" }); - }// - public void testTesting() { - checkBuild("testing", - "org.aspectj.testing.util.LangUtilTest", - new String[] {"ignored"}); - } - public void testTestingDrivers() { - checkBuild("testing-drivers", - "org.aspectj.testing.drivers.Harness", - new String[] {"-help"}); - } - public void testWeaver() { - checkBuild("weaver"); - } - - // ajdoc relies on tools.jar - public void testAspectjtools() { - if (!shouldBuild("aspectjtools")) { - return; - } - File baseDir = new File(".."); - File tempBuildDir = new File(baseDir, "aj-build"); - File distDir = new File(tempBuildDir, "dist"); - File jarDir = new File(tempBuildDir, "jars"); - assertTrue(distDir.canWrite() || distDir.mkdirs()); - File productDir = new File(baseDir.getPath() + "/build/products/tools"); - assertTrue(""+productDir, productDir.canRead()); - checkBuildProduct(productDir, baseDir, distDir, jarDir); - } - - void checkBuildProduct(File productDir, File baseDir, File distDir, File jarDir) { - if (!shouldBuild(productDir.getPath())) { - return; - } - assertTrue(null != productDir); - assertTrue(productDir.canRead()); - - checkJavac(); - - BuildModule task = new BuildModule(); - Project project = new Project(); - task.setProject(project); - assertTrue(jarDir.canWrite() || jarDir.mkdirs()); - tempFiles.add(jarDir); - task.setJardir(new Path(project, jarDir.getAbsolutePath())); - task.setProductdir(new Path(project, productDir.getAbsolutePath())); - task.setBasedir(new Path(project, baseDir.getAbsolutePath())); - task.setDistdir(new Path(project, distDir.getAbsolutePath())); - task.setFailonerror(true); - if (null != BUILD_CONFIG) { - task.setBuildConfig(BUILD_CONFIG); - } - //task.setVerbose(true); - task.setCreateinstaller(true); - task.execute(); - // now run installer and do product tests? - } - - File getAntJar() { - return new File("../lib/ant/lib/ant.jar"); - } - File getJUnitJar() { - return new File("../lib/junit/junit.jar"); - } - - File getJarDir() { - if (null == jarDir) { - File baseDir = new File("../aj-build/"); - if (!baseDir.canWrite()) { - baseDir = new File("."); - } - jarDir = new File(baseDir, "BuildModuleTest-jars"); - tempFiles.add(jarDir); - } - if (!jarDir.exists()) { - assertTrue(jarDir.mkdirs()); - } - return jarDir; - } - - BuildModule getTask(String module) { - BuildModule task = new BuildModule(); - Project project = new Project(); - task.setProject(project); - File jarDir = getJarDir(); - assertTrue(jarDir.canWrite() || jarDir.mkdirs()); - tempFiles.add(jarDir); - File moduleDir = new File(Util.path("..", module)); - assertTrue(moduleDir.canRead()); - task.setModuledir(new Path(project, moduleDir.getAbsolutePath())); - task.setJardir(new Path(project, jarDir.getAbsolutePath())); - task.setFailonerror(true); - if (null != BUILD_CONFIG) { - task.setBuildConfig(BUILD_CONFIG); - } - return task; - } - - void checkBuild(String module) { - checkBuild(module, null, null, false); - } - - void checkBuild(String module, - String classname, - String[] args) { - checkBuild(module, classname, args, true); - } - - boolean shouldBuild(String target) { - if (null == target) { - return false; - } - if (!building && !printedMessage) { - System.err.println(SKIP_MESSAGE + target + " (this is the only warning)"); - printedMessage = true; - } - if (debugging()) { - for (int i = 0; i < DEBUGS.length; i++) { - if (target.equals(DEBUGS[i])) { - return true; - } - } - return false; - } else { - for (int i = 0; i < SKIPS.length; i++) { - if (SKIPS[i].equals(target)) { - if (printInfoMessages) { - System.err.println(target + " skipped build test [" + getClass().getName() + ".shouldBuild(..)]"); - } - return false; - } - } - } - return building; - } - private static boolean debugging() { - return ((null != DEBUGS) && (0 < DEBUGS.length)); - } - private static String duplicateEntryError(File weaverAllJar) { - ZipFile zipFile = null; - try { - zipFile = new ZipFile(weaverAllJar); - Enumeration e = zipFile.entries(); - ArrayList entryNames = new ArrayList(); - while (e.hasMoreElements()) { - ZipEntry entry = (ZipEntry) e.nextElement(); - String name = entry.getName(); - if (entryNames.contains(name)) { - return "duplicate entry: " + name; - } - entryNames.add(name); - } - } catch (ZipException e) { - return "ZipException " + e; - } catch (IOException e) { - return "IOException " + e; - } finally { - if (null != zipFile) { - try { - zipFile.close(); - } catch (IOException e) { - return "IOException closing " + zipFile + ": " + e; - } - } - } - return null; - } - - private static String name(String module, boolean trimTesting, boolean assemble) { - return module + (trimTesting?"":"-test") + (assemble?"-all":""); - } - private void deleteJar(File jar) { - if (!deleteJars) { - return ; - } - if (jar.exists()) { - jar.delete(); - } - if (jar.exists()) { - try { - Thread.sleep(5000); - } catch (Throwable t) { - } - } - if (jar.exists()) { - assertTrue("cannot delete " + jar, jar.delete()); - } - } - void checkBuild(String module, - String classname, - String[] args, - boolean addAnt) { - if (!shouldBuild(module)) { - return; - } - assertTrue(null != module); - checkJavac(); - doTask(module, true, false); - doTask(module, true, true); - doTask(module, false, false); - File jar = doTask(module, false, true, true); - - // verify if possible - if (null != classname) { - Java java = new Java(); - Project project = new Project(); - java.setProject(project); - java.setFailonerror(true); - Path cp = new Path(project); - assertTrue(jar.canRead()); - cp.append(new Path(project, jar.getAbsolutePath())); - if (addAnt) { - cp.append(new Path(project, getAntJar().getAbsolutePath())); - cp.append(new Path(project, getJUnitJar().getAbsolutePath())); - } - java.setClasspath(cp); - java.setClassname(classname); - if (null != args) { - for (int i = 0; i < args.length; i++) { - Argument arg = java.createArg(); - arg.setValue(args[i]); - } - } - try { - java.execute(); - } catch (BuildException e) { - e.printStackTrace(System.err); - assertTrue("BuildException running " + classname, false); - } - } - deleteJar(jar); - } - void doTask(String module, boolean trimTesting, boolean assembleAll) { - doTask(module, trimTesting, assembleAll, false); - } - - File doTask(String module, boolean trimTesting, boolean assembleAll, boolean keepJars) { - BuildModule task = getTask(module); - String name = name(module, trimTesting, assembleAll); - File jar = new File(getJarDir(), name+ ".jar"); - task.setAssembleall(assembleAll); - task.setTrimtesting(trimTesting); - task.execute(); - if (!jar.canRead()) { - File[] files = getJarDir().listFiles(); - fail("cannot read " + jar + " in " + Arrays.asList(files)); - } - if (!keepJars && deleteJars) { - deleteTempFiles(); - } - return jar; - } - - void checkJavac() { - boolean result = false; - try { - result = (null != Class.forName("sun.tools.javac.Main")); - } catch (Throwable t) { - // ignore - } - if (! result) { - assertTrue("add tools.jar to the classpath for Ant's use of javac", false); - } - } - -} diff --git a/build/testsrc/org/aspectj/internal/build/ModulesTest.java b/build/testsrc/org/aspectj/internal/build/ModulesTest.java deleted file mode 100644 index 16786404c..000000000 --- a/build/testsrc/org/aspectj/internal/build/ModulesTest.java +++ /dev/null @@ -1,304 +0,0 @@ -/* ******************************************************************* - * Copyright (c) 1999-2001 Xerox Corporation, - * 2002 Palo Alto Research Center, Incorporated (PARC), - * 2005-2006 Contributors. - * All rights reserved. - * This program and the accompanying materials are made available - * under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Xerox/PARC initial implementation - * Wes Isberg build tests - * ******************************************************************/ - -package org.aspectj.internal.build; - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.tools.ant.BuildEvent; -import org.apache.tools.ant.BuildListener; -import org.apache.tools.ant.Project; -import org.apache.tools.ant.Task; -import org.apache.tools.ant.types.Path; -import org.aspectj.internal.tools.ant.taskdefs.AntBuilder; -import org.aspectj.internal.tools.ant.taskdefs.BuildModule; -import org.aspectj.internal.tools.build.Messager; -import org.aspectj.internal.tools.build.Module; -import org.aspectj.internal.tools.build.Modules; -import org.aspectj.internal.tools.build.Result; -import org.aspectj.internal.tools.build.Util; -import org.aspectj.internal.tools.build.Result.Kind; -/** - * - */ -public class ModulesTest extends TestCase { - public static final List MODULE_NAMES; - private static final File BASE_DIR = new File(".."); - static { - String[] names = { - "ajbrowser", "ajde", "ajdoc", "asm", "aspectj5rt", - "bridge", "loadtime", "loadtime5", "org.aspectj.ajdt.core", - "runtime", "taskdefs", "testing-client", "testing-util", - "tests", "util", "weaver"}; - List list = Arrays.asList(names); - MODULE_NAMES = Collections.unmodifiableList(list); - } - - private static boolean delete(File file) { // XXX Util - if ((null == file) || !file.exists()) { - return true; - } - if (file.isFile()) { - return file.delete(); - } else { - File[] files = file.listFiles(); - boolean result = true; - for (int i = 0; i < files.length; i++) { - if (!ModulesTest.delete(files[i]) - && result) { - result = false; - } - } - return (file.delete() && result); - } - } - - ArrayList tempFiles = new ArrayList(); - - public ModulesTest(String name) { - super(name); - } - - protected void tearDown() throws Exception { - super.tearDown(); - for (Iterator iter = tempFiles.iterator(); iter.hasNext();) { - File file = (File) iter.next(); - if (!ModulesTest.delete(file)) { - System.err.println("warning: ModulesTest unable to delete " + file); - } - } - } - Modules getModules(Messager handler) { - File jarDir = new File("../aj-build-test-jars"); - if (!jarDir.exists()) { - assertTrue(jarDir.mkdirs()); - tempFiles.add(jarDir); - } - File baseDir = new File(".."); - if (null == handler) { - handler = new Messager(); - } - return new Modules(baseDir, jarDir, handler); - } - - public void testAllModulesCreation() { - ArrayList badModules = new ArrayList(); - for (String name: MODULE_NAMES) { - File dir = new File(BASE_DIR, name); - if (dir.isDirectory()) { - File classpath = new File(dir, ".classpath"); - if (classpath.exists()) { - Modules modules = getModules(null); - Module module = modules.getModule(name); - if (!module.valid) { - badModules.add(module); - } - } - } - } - if (!badModules.isEmpty()) { - StringBuffer sb = new StringBuffer(); - for (Module module: badModules) { - System.err.println(module.toLongString()); - sb.append("\n"); - sb.append(module); - } - fail(sb.toString()); - } - } - - void checkModule(String s) { - if ("docs".equals(s) || "lib".equals(s)) { - return; - } - Modules modules = getModules(null); - Module module = modules.getModule(s); - if (!module.valid) { - assertTrue(module.toLongString(), false); - } - } - - public void testClasspathCreation() { - Modules modules = getModules(null); - Module ajdt = modules.getModule("org.aspectj.ajdt.core"); - assertTrue(ajdt.valid); - - Project project = new Project(); - AntBuilder builder = getBuilder(project); - Path classpath = new Path(project); - Kind kind = Result.kind(Result.NORMAL, !Result.ASSEMBLE); - Result result = ajdt.getResult(kind); - boolean hasLibraries = builder.setupClasspath(result, classpath); - assertTrue(hasLibraries); - if ((null == classpath) || (2 > classpath.size())) { - assertTrue(classpath.toString(), false); - } - } - - /** - * This test requires two OSGI modules: - * org.aspectj.util, which optionally depends on tempaspectjrt. - * Currently, the Ant builder does not handle linked source folders, - * and the OSGI support does not work around optional plugins. - */ - public void skip_testOSGIModuleCreation() { - final String MODULE = "org.aspectj.util"; - final String USES_MODULE = "tempaspectjrt"; - - Modules modules = getModules(null); - Module newutil = modules.getModule(MODULE); - assertTrue(newutil.valid); - - Project project = new Project(); - AntBuilder builder = getBuilder(project); - Path classpath = new Path(project); - Kind kind = Result.kind(Result.NORMAL, !Result.ASSEMBLE); - Result result = newutil.getResult(kind); - builder.setupClasspath(result, classpath); - System.out.println(newutil + " classpath: " + classpath); - if ((1 != classpath.size())) { - assertTrue(classpath.toString(), false); - } - String cpEntry = classpath.list()[0]; - if (!cpEntry.endsWith(USES_MODULE + ".jar")) { - fail("expected " + classpath + " to end with " + USES_MODULE + ".jar"); - } - } - - private AntBuilder getBuilder(Project project) { - project.setBaseDir(new File(".")); - project.setName("testOSGIModuleCreation"); - File tempDir = new File("."); - return (AntBuilder) AntBuilder.getBuilder("", project, tempDir); - } - - - /********************************************************************* - * The following tests/code enable you to run the entire build in JUnit - * to debug directly from Eclipse. To compile using Javac, you will - * need to add tools.jar to the run classpath. - */ - public void skip_testBuildingAspectJModule() { - final String moduleName = "org.aspectj.lib"; - - File modulesDir = new File("..").getAbsoluteFile(); - File buildDir = new File(modulesDir, "aj-build"); - File distDir = new File(buildDir, "dist"); - File jarDir = new File(buildDir, "jars"); - File moduleDir = new File(modulesDir, moduleName); - File jar = new File(jarDir, "org.aspectj.lib.jar"); - jarDir.mkdirs(); - distDir.mkdirs(); - if (jar.canRead()) { - assertTrue(jar.delete()); - } - Project project = new Project(); - project.setBaseDir(modulesDir); - project.setName("testAspectjbuild"); - - BuildModule bm = new BuildModule(); - bm.setProject(project); - bm.setAssembleall(true); - bm.setBuildConfig(""); - bm.setModule(moduleName); - bm.setBasedir(new Path(project, modulesDir.getPath())); - bm.setDistdir(new Path(project, buildDir.getPath())); - bm.setJardir(new Path(project, jarDir.getPath())); - bm.setModuledir(new Path(project, moduleDir.getPath())); - bm.setTrimtesting(true); - bm.setBuildConfig(""); - bm.setVersion("1.2"); - bm.setVerbose(true); - bm.setFailonerror(true); - - bm.execute(); - - assertTrue(jar.canRead()); - } - - public void skip_testBuildingProduct() { - final String productName = "tools"; - File modulesDir = new File("..").getAbsoluteFile(); - File buildDir = new File(modulesDir, "aj-build"); - File distDir = new File(buildDir, "dist"); - File jarDir = new File(buildDir, "jars"); - File productDir = new File(modulesDir, - Util.path(new String[] {"build", "products", productName})); - - jarDir.mkdirs(); - distDir.mkdirs(); - - Project project = new Project(); - project.setBaseDir(modulesDir); - project.setName("testAspectjToolsbuild"); - project.addBuildListener(new EventBuildListener(Project.MSG_WARN)); - - BuildModule bm = new BuildModule(); - bm.setProject(project); - bm.setAssembleall(true); - bm.setBuildConfig(""); - bm.setProductdir(new Path(project, productDir.getPath())); - bm.setBasedir(new Path(project, modulesDir.getPath())); - bm.setDistdir(new Path(project, distDir.getPath())); - bm.setJardir(new Path(project, jarDir.getPath())); - bm.setTrimtesting(true); - bm.setBuildConfig(""); - bm.setVersion("1.2"); - bm.setFailonerror(true); - bm.execute(); - - File libDir = new File(distDir, "tools/lib"); - String[] jars = { "tools", "rt", "weaver", "lib"}; - for (int i = 0; i < jars.length; i++) { - File jar = new File(libDir, "aspectj" + jars[i] + ".jar"); - assertTrue(jar.getPath(), jar.canRead()); - if (10 > jar.length()) { - assertTrue(jar + " too small", false); - } - } - } - /** - * Show messages from the task. - * (normally shown by Ant's default listener) - */ - static class EventBuildListener implements BuildListener { - final int min; - EventBuildListener(int min) { - this.min = min; - } - public void buildFinished(BuildEvent event) {} - public void buildStarted(BuildEvent event) { } - public void messageLogged(BuildEvent event) { - if (min <= event.getPriority()) { - Task t = event.getTask(); - String src = (null == t ? "project" : t.getTaskName()); - System.out.println(src + ": " + event.getMessage()); - } - } - public void targetFinished(BuildEvent event) { } - public void targetStarted(BuildEvent event) { } - public void taskFinished(BuildEvent event) { } - public void taskStarted(BuildEvent event) { } - - } - -} diff --git a/build/testsrc/org/aspectj/internal/tools/build/UtilsTest.01.MF b/build/testsrc/org/aspectj/internal/tools/build/UtilsTest.01.MF deleted file mode 100644 index e3ba88396..000000000 --- a/build/testsrc/org/aspectj/internal/tools/build/UtilsTest.01.MF +++ /dev/null @@ -1,8 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Client Plug-in -Bundle-SymbolicName: org.aspectj.testing.client -Bundle-Version: 1.0.0 -Bundle-Localization: plugin -Bundle-ClassPath: lib/commons/commons.jar - diff --git a/build/testsrc/org/aspectj/internal/tools/build/UtilsTest.02.MF b/build/testsrc/org/aspectj/internal/tools/build/UtilsTest.02.MF deleted file mode 100644 index 5888ab3c0..000000000 --- a/build/testsrc/org/aspectj/internal/tools/build/UtilsTest.02.MF +++ /dev/null @@ -1,9 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Client Plug-in -Bundle-SymbolicName: org.aspectj.testing.client -Bundle-Version: 1.0.0 -Bundle-Localization: plugin -Bundle-ClassPath: lib/commons/commons.jar, lib/ant/lib/ant.jar -Require-Bundle: util, org.aspectj.runtime - diff --git a/build/testsrc/org/aspectj/internal/tools/build/UtilsTest.03.MF b/build/testsrc/org/aspectj/internal/tools/build/UtilsTest.03.MF deleted file mode 100644 index b9717c5f2..000000000 --- a/build/testsrc/org/aspectj/internal/tools/build/UtilsTest.03.MF +++ /dev/null @@ -1,9 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Client Plug-in -Bundle-SymbolicName: org.aspectj.testing.client -Bundle-Version: 1.0.0 -Bundle-Localization: plugin -Bundle-ClassPath: lib/commons/commons.jar, lib/ant/lib/ant.jar -Require-Bundle: util, aspectjrt;bundle-version="[1.5.0,1.5.5]";resolution:=optional - diff --git a/build/testsrc/org/aspectj/internal/tools/build/UtilsTest.java b/build/testsrc/org/aspectj/internal/tools/build/UtilsTest.java deleted file mode 100644 index 4926d42e8..000000000 --- a/build/testsrc/org/aspectj/internal/tools/build/UtilsTest.java +++ /dev/null @@ -1,200 +0,0 @@ -/* ******************************************************************* - * Copyright (c) 2006 Contributors. - * All rights reserved. - * This program and the accompanying materials are made available - * under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution and is available at - * http://eclipse.org/legal/epl-v10.html - * - * Contributors: - * Wes Isberg initial implementation - * ******************************************************************/ - -package org.aspectj.internal.tools.build; - -import java.io.IOException; -import java.util.jar.Attributes.Name; - -import junit.framework.TestCase; - -import org.aspectj.internal.tools.build.Util.OSGIBundle; -import org.aspectj.internal.tools.build.Util.OSGIBundle.RequiredBundle; - -public class UtilsTest extends TestCase { - private static final String PREFIX = UtilsTest.class.getName().replace('.', - '/'); - - private static final ClassLoader LOADER = UtilsTest.class.getClassLoader(); - - private static final ManifestTest[] TESTS = { - new ManifestTest("01", - new Name[] { OSGIBundle.BUNDLE_CLASSPATH, - OSGIBundle.BUNDLE_SYMBOLIC_NAME, - OSGIBundle.BUNDLE_VERSION }, new String[] { - "lib/commons/commons.jar", - "org.aspectj.testing.client", "1.0.0" }), - new ManifestTest("02", - new Name[] { OSGIBundle.BUNDLE_SYMBOLIC_NAME, - OSGIBundle.BUNDLE_VERSION }, new String[] { - "org.aspectj.testing.client", "1.0.0" }, - new String[] { "lib/commons/commons.jar", - "lib/ant/lib/ant.jar" }, new String[] { "util", - "org.aspectj.runtime" }), - new ManifestTest("03", - new Name[] { OSGIBundle.BUNDLE_SYMBOLIC_NAME, - OSGIBundle.BUNDLE_VERSION }, new String[] { - "org.aspectj.testing.client", "1.0.0" }, - new String[] { "lib/commons/commons.jar", - "lib/ant/lib/ant.jar" }, new String[] { "util", - "aspectjrt" }) { - void checkOthers(OSGIBundle osgiBundle, StringBuffer sb) { - RequiredBundle[] bundles = osgiBundle.getRequiredBundles(); - for (int i = 0; i < bundles.length; i++) { - RequiredBundle bundle = bundles[i]; - if ("aspectjrt".equals(bundle.name)) { - if (!bundle.optional) { - sb - .append("expected required bundle aspectjrt to be optional"); - } - String version = "[1.5.0,1.5.5]"; - if (!(version.equals(bundle.versions))) { - sb.append("expected version " + version - + " got " + bundle.versions - + " for required bundle aspectjrt"); - } - } - } - - } - } }; - - private static class ManifestTest { - final String name; - - final Name[] expectedNames; - - final String[] expectedValues; - - final String[] classpathEntries; - - final String[] requiredBundleNames; - - ManifestTest(String name, Name[] expectedNames, String[] expectedValues) { - this(name, expectedNames, expectedValues, null, null); - } - - ManifestTest(String name, Name[] expectedNames, - String[] expectedValues, String[] classpathEntries, - String[] requiredBundleNames) { - this.name = name; - this.expectedNames = expectedNames; - this.expectedValues = expectedValues; - this.classpathEntries = classpathEntries; - this.requiredBundleNames = requiredBundleNames; - } - - void run(StringBuffer sb) throws IOException { - String path = PREFIX + "." + name + ".MF"; - OSGIBundle bundle = new OSGIBundle(LOADER.getResourceAsStream(path)); - int len = sb.length(); - checkNamesAndValues(bundle, sb); - checkOthers(bundle, sb); - if (sb.length() != len) { - sb.append("failure was in test " + name); - } - } - - void checkOthers(OSGIBundle bundle, StringBuffer sb) { - } - - void checkNamesAndValues(OSGIBundle bundle, StringBuffer sb) { - for (int i = 0; i < expectedNames.length; i++) { - Name name = expectedNames[i]; - String expected = expectedValues[i]; - String actual = bundle.getAttribute(expectedNames[i]); - if (!((expected == actual) || expected.equals(actual))) { - sb.append(name); - sb.append(" "); - sb.append("expected "); - sb.append(expected); - sb.append("actual "); - sb.append(actual); - sb.append("\n"); - } - } - if (null != classpathEntries) { - String[] cp = bundle.getClasspath(); - Util.reportMemberDiffs(classpathEntries, cp, sb); - } - if (null != requiredBundleNames) { - RequiredBundle[] bundles = bundle.getRequiredBundles(); - String[] names = new String[bundles.length]; - for (int i = 0; i < names.length; i++) { - names[i] = bundles[i].name; - } - Util.reportMemberDiffs(requiredBundleNames, names, sb); - } - } - } - - /** disabled pending research */ - public void skip_testOSGIManifests() throws Exception { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < TESTS.length; i++) { - TESTS[i].run(sb); - } - if (0 < sb.length()) { - fail(sb.toString()); - } - } - - public void testReportMemberDiffs() { - StringBuffer sb = new StringBuffer(); - String[] exp = null; - String[] act = null; - assertFalse(Util.reportMemberDiffs(exp, act, sb)); - assertEquals("", sb.toString()); - - sb.setLength(0); - exp = new String[] { "" }; - act = null; - assertTrue(Util.reportMemberDiffs(exp, act, sb)); - assertEquals("unexpected [] missing [\"\"]", sb.toString()); - - sb.setLength(0); - exp = null; - act = new String[] { "" }; - assertTrue(Util.reportMemberDiffs(exp, act, sb)); - assertEquals("unexpected [\"\"] missing []", sb.toString()); - - sb.setLength(0); - exp = new String[] { "1", "2", "3" }; - act = new String[] { "2", "4" }; - assertTrue(Util.reportMemberDiffs(exp, act, sb)); - assertEquals("unexpected [\"4\"] missing [\"1\", \"3\"]", sb.toString()); - - } - // public void testResourceStream() throws Exception { - // String path = PREFIX + ".one.mf"; - // System.out.println(path); - // InputStream in = LOADER.getResourceAsStream(path); - // int i; - // while (-1 != (i = in.read())) { - // System.out.print((char) i); - // } - // System.out.println(); - // } - // Map map = bundle.manifest.getEntries(); - // for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) { - // MapEntry entry = (MapEntry) iter.next(); - // System.out.println("entry: " + entry); - // } - // System.out.println("main attributes"); - // Attributes attributes = bundle.manifest.getMainAttributes(); - // Set keys = attributes.keySet(); - // for (Iterator iter = keys.iterator(); iter.hasNext();) { - // Object key = iter.next(); - // System.out.println(" key " + key); - // System.out.println(" value " + attributes.getValue(key.toString())); - // } -} -- cgit v1.2.3