Пример #1
0
 /**
  * Sets an optional super grammar file. Use setGlib(File superGrammar) instead.
  *
  * @param superGrammar the super grammar filename
  * @deprecated since ant 1.6
  */
 public void setGlib(String superGrammar) {
   String sg = null;
   if (Os.isFamily("dos")) {
     sg = superGrammar.replace('\\', '/');
   } else {
     sg = superGrammar;
   }
   setGlib(FILE_UTILS.resolveFile(getProject().getBaseDir(), sg));
 }
Пример #2
0
  /**
   * {@inheritDoc}
   *
   * @see RequirementProvider#getRequirements()
   */
  public Requirement[] getRequirements() {
    if (Os.isFamily("windows")) {
      Requirement[] requirements = new Requirement[1];
      requirements[0] = new EclipseRequirement();
      return requirements;
    }

    InstallContext context = Installer.getContext();
    boolean skipVim = ((Boolean) context.getValue("vim.skip")).booleanValue();

    Requirement[] requirements = new Requirement[skipVim ? 3 : 4];
    requirements[0] = new EclipseRequirement();
    requirements[1] = new WhichRequirement("make");
    requirements[2] = new WhichRequirement("gcc");
    if (!skipVim) {
      requirements[3] = new VimRequirement();
    }
    return requirements;
  }
Пример #3
0
  /**
   * Performs a compile using the Javac externally.
   *
   * @return true if the compilation succeeded
   * @throws BuildException on error
   */
  public boolean execute() throws BuildException {
    attributes.log("Using external javac compiler", Project.MSG_VERBOSE);

    Commandline cmd = new Commandline();
    cmd.setExecutable(getJavac().getJavacExecutable());
    if (!assumeJava11() && !assumeJava12()) {
      setupModernJavacCommandlineSwitches(cmd);
    } else {
      setupJavacCommandlineSwitches(cmd, true);
    }
    int firstFileName = assumeJava11() ? -1 : cmd.size();
    logAndAddFilesToCompile(cmd);
    // On VMS platform, we need to create a special java options file
    // containing the arguments and classpath for the javac command.
    // The special file is supported by the "-V" switch on the VMS JVM.
    if (Os.isFamily("openvms")) {
      return execOnVMS(cmd, firstFileName);
    }
    return executeExternalCompile(cmd.getCommandline(), firstFileName, true) == 0;
  }
/** @author Benjamin Bentmann */
public class AntRepoSys {

  private static boolean OS_WINDOWS = Os.isFamily("windows");

  private static final ModelBuilder modelBuilder = new DefaultModelBuilderFactory().newInstance();

  private static final SettingsBuilder settingsBuilder =
      new DefaultSettingsBuilderFactory().newInstance();

  private static final SettingsDecrypter settingsDecrypter =
      new AntSettingsDecryptorFactory().newInstance();

  private Project project;

  private AntServiceLocator locator;

  private RepositorySystem repoSys;

  private RemoteRepositoryManager remoteRepoMan;

  private File userSettings;

  private File globalSettings;

  private Settings settings;

  private List<Mirror> mirrors = new CopyOnWriteArrayList<Mirror>();

  private List<Proxy> proxies = new CopyOnWriteArrayList<Proxy>();

  private List<Authentication> authentications = new CopyOnWriteArrayList<Authentication>();

  private LocalRepository localRepository;

  private Pom defaultPom;

  private File mavenRepoDirFromProperty;

  private static <T> boolean eq(T o1, T o2) {
    return (o1 == null) ? o2 == null : o1.equals(o2);
  }

  public static synchronized AntRepoSys getInstance(Project project) {
    Object obj = project.getReference(Names.ID);
    if (obj instanceof AntRepoSys) {
      return (AntRepoSys) obj;
    }
    AntRepoSys instance = new AntRepoSys(project);
    project.addReference(Names.ID, instance);
    instance.initDefaults();
    return instance;
  }

  private AntRepoSys(Project project) {
    this.project = project;

    locator = new AntServiceLocator(project);
    locator.setServices(Logger.class, new AntLogger(project));
    locator.setServices(ModelBuilder.class, modelBuilder);
    locator.addService(RepositoryConnectorFactory.class, FileRepositoryConnectorFactory.class);
    locator.addService(RepositoryConnectorFactory.class, AsyncRepositoryConnectorFactory.class);
  }

  private void initDefaults() {
    RemoteRepository repo = new RemoteRepository();
    repo.setProject(project);
    repo.setId("central");
    repo.setUrl("http://repo1.maven.org/maven2/");
    project.addReference(Names.ID_CENTRAL, repo);

    repo = new RemoteRepository();
    repo.setProject(project);
    repo.setRefid(new Reference(project, Names.ID_CENTRAL));
    RemoteRepositories repos = new RemoteRepositories();
    repos.setProject(project);
    repos.addRemoterepo(repo);
    project.addReference(Names.ID_DEFAULT_REPOS, repos);

    // resolve maven.repo.local only once relative to project, as the basedir may change for <ant>
    // tasks
    String localRepoResolved = project.getProperty("maven.repo.local.resolved");
    if (localRepoResolved != null) {
      mavenRepoDirFromProperty = new File(localRepoResolved);
    } else {
      String mavenRepoProperty = project.getProperty("maven.repo.local");
      if (mavenRepoProperty != null) {
        mavenRepoDirFromProperty = project.resolveFile(mavenRepoProperty);
        project.setProperty(
            "maven.repo.local.resolved", mavenRepoDirFromProperty.getAbsolutePath());
      }
    }
  }

  public synchronized RepositorySystem getSystem() {
    if (repoSys == null) {
      repoSys = locator.getService(RepositorySystem.class);
      if (repoSys == null) {
        throw new BuildException("The repository system could not be initialized");
      }
    }
    return repoSys;
  }

  private synchronized RemoteRepositoryManager getRemoteRepoMan() {
    if (remoteRepoMan == null) {
      remoteRepoMan = locator.getService(RemoteRepositoryManager.class);
      if (remoteRepoMan == null) {
        throw new BuildException("The repository system could not be initialized");
      }
    }
    return remoteRepoMan;
  }

  public RepositorySystemSession getSession(Task task, LocalRepository localRepo) {
    DefaultRepositorySystemSession session = new MavenRepositorySystemSession();

    Map<Object, Object> configProps = new LinkedHashMap<Object, Object>();
    configProps.put(ConfigurationProperties.USER_AGENT, getUserAgent());
    configProps.putAll(System.getProperties());
    configProps.putAll((Map<?, ?>) project.getProperties());
    configProps.putAll((Map<?, ?>) project.getUserProperties());
    session.setConfigProps(configProps);

    session.setNotFoundCachingEnabled(false);
    session.setTransferErrorCachingEnabled(false);

    session.setOffline(isOffline());
    session.setUserProps(project.getUserProperties());

    session.setLocalRepositoryManager(getLocalRepoMan(localRepo));

    session.setProxySelector(getProxySelector());
    session.setMirrorSelector(getMirrorSelector());
    session.setAuthenticationSelector(getAuthSelector());

    session.setCache(new DefaultRepositoryCache());

    session.setRepositoryListener(new AntRepositoryListener(task));
    session.setTransferListener(new AntTransferListener(task));

    session.setWorkspaceReader(ProjectWorkspaceReader.getInstance());

    return session;
  }

  private String getUserAgent() {
    StringBuilder buffer = new StringBuilder(128);

    buffer.append("Apache-Ant/").append(project.getProperty("ant.version"));
    buffer.append(" (");
    buffer.append("Java ").append(System.getProperty("java.version"));
    buffer.append("; ");
    buffer
        .append(System.getProperty("os.name"))
        .append(" ")
        .append(System.getProperty("os.version"));
    buffer.append(")");
    buffer.append(" Aether");

    return buffer.toString();
  }

  private boolean isOffline() {
    String prop = project.getProperty(Names.PROPERTY_OFFLINE);
    if (prop != null) {
      return Boolean.parseBoolean(prop);
    }
    return getSettings().isOffline();
  }

  private File getDefaultLocalRepoDir() {
    if (mavenRepoDirFromProperty != null) {
      return mavenRepoDirFromProperty;
    }

    Settings settings = getSettings();
    if (settings.getLocalRepository() != null) {
      return new File(settings.getLocalRepository());
    }

    return new File(new File(project.getProperty("user.home"), ".m2"), "repository");
  }

  private LocalRepositoryManager getLocalRepoMan(LocalRepository localRepo) {
    if (localRepo == null) {
      localRepo = localRepository;
    }

    File repoDir;
    if (localRepo != null && localRepo.getDir() != null) {
      repoDir = localRepo.getDir();
    } else {
      repoDir = getDefaultLocalRepoDir();
    }

    org.sonatype.aether.repository.LocalRepository repo =
        new org.sonatype.aether.repository.LocalRepository(repoDir);

    return getSystem().newLocalRepositoryManager(repo);
  }

  private synchronized Settings getSettings() {
    if (settings == null) {
      DefaultSettingsBuildingRequest request = new DefaultSettingsBuildingRequest();
      request.setUserSettingsFile(getUserSettings());
      request.setGlobalSettingsFile(getGlobalSettings());
      request.setSystemProperties(getSystemProperties());
      request.setUserProperties(getUserProperties());

      try {
        settings = settingsBuilder.build(request).getEffectiveSettings();
      } catch (SettingsBuildingException e) {
        project.log("Could not process settings.xml: " + e.getMessage(), e, Project.MSG_WARN);
      }

      SettingsDecryptionResult result =
          settingsDecrypter.decrypt(new DefaultSettingsDecryptionRequest(settings));
      settings.setServers(result.getServers());
      settings.setProxies(result.getProxies());
    }
    return settings;
  }

  private ProxySelector getProxySelector() {
    DefaultProxySelector selector = new DefaultProxySelector();

    for (Proxy proxy : proxies) {
      selector.add(ConverterUtils.toProxy(proxy), proxy.getNonProxyHosts());
    }

    Settings settings = getSettings();
    for (org.apache.maven.settings.Proxy proxy : settings.getProxies()) {
      org.sonatype.aether.repository.Authentication auth = null;
      if (proxy.getUsername() != null || proxy.getPassword() != null) {
        auth =
            new org.sonatype.aether.repository.Authentication(
                proxy.getUsername(), proxy.getPassword());
      }
      selector.add(
          new org.sonatype.aether.repository.Proxy(
              proxy.getProtocol(), proxy.getHost(), proxy.getPort(), auth),
          proxy.getNonProxyHosts());
    }

    return selector;
  }

  private MirrorSelector getMirrorSelector() {
    DefaultMirrorSelector selector = new DefaultMirrorSelector();

    for (Mirror mirror : mirrors) {
      selector.add(
          mirror.getId(), mirror.getUrl(), mirror.getType(), false, mirror.getMirrorOf(), null);
    }

    Settings settings = getSettings();
    for (org.apache.maven.settings.Mirror mirror : settings.getMirrors()) {
      selector.add(
          String.valueOf(mirror.getId()),
          mirror.getUrl(),
          mirror.getLayout(),
          false,
          mirror.getMirrorOf(),
          mirror.getMirrorOfLayouts());
    }

    return selector;
  }

  private AuthenticationSelector getAuthSelector() {
    DefaultAuthenticationSelector selector = new DefaultAuthenticationSelector();

    Collection<String> ids = new HashSet<String>();
    for (Authentication auth : authentications) {
      List<String> servers = auth.getServers();
      if (!servers.isEmpty()) {
        org.sonatype.aether.repository.Authentication a = ConverterUtils.toAuthentication(auth);
        for (String server : servers) {
          if (ids.add(server)) {
            selector.add(server, a);
          }
        }
      }
    }

    Settings settings = getSettings();
    for (Server server : settings.getServers()) {
      org.sonatype.aether.repository.Authentication auth =
          new org.sonatype.aether.repository.Authentication(
              server.getUsername(), server.getPassword(),
              server.getPrivateKey(), server.getPassphrase());
      selector.add(server.getId(), auth);
    }

    return new ConservativeAuthenticationSelector(selector);
  }

  public synchronized void setUserSettings(File file) {
    if (!eq(this.userSettings, file)) {
      settings = null;
    }
    this.userSettings = file;
  }

  /* UT */ File getUserSettings() {
    if (userSettings == null) {
      userSettings = AetherUtils.findUserSettings(project);
    }
    return userSettings;
  }

  public void setGlobalSettings(File file) {
    if (!eq(this.globalSettings, file)) {
      settings = null;
    }
    this.globalSettings = file;
  }

  /* UT */ File getGlobalSettings() {
    if (globalSettings == null) {
      globalSettings = AetherUtils.findGlobalSettings(project);
    }
    return globalSettings;
  }

  public void addProxy(Proxy proxy) {
    proxies.add(proxy);
  }

  public void addMirror(Mirror mirror) {
    mirrors.add(mirror);
  }

  public void addAuthentication(Authentication authentication) {
    authentications.add(authentication);
  }

  public void setLocalRepository(LocalRepository localRepository) {
    this.localRepository = localRepository;
  }

  public Model loadModel(
      Task task, File pomFile, boolean local, RemoteRepositories remoteRepositories) {
    RepositorySystemSession session = getSession(task, null);

    remoteRepositories =
        remoteRepositories == null
            ? AetherUtils.getDefaultRepositories(project)
            : remoteRepositories;

    List<org.sonatype.aether.repository.RemoteRepository> repositories =
        ConverterUtils.toRepositories(
            task.getProject(), session, remoteRepositories, getRemoteRepoMan());

    ModelResolver modelResolver =
        new AntModelResolver(session, "project", getSystem(), getRemoteRepoMan(), repositories);

    Settings settings = getSettings();

    try {
      DefaultModelBuildingRequest request = new DefaultModelBuildingRequest();
      request.setLocationTracking(true);
      request.setProcessPlugins(false);
      if (local) {
        request.setPomFile(pomFile);
        request.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_STRICT);
      } else {
        request.setModelSource(new FileModelSource(pomFile));
        request.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
      }
      request.setSystemProperties(getSystemProperties());
      request.setUserProperties(getUserProperties());
      request.setProfiles(SettingsUtils.convert(settings.getProfiles()));
      request.setActiveProfileIds(settings.getActiveProfiles());
      request.setModelResolver(modelResolver);
      return modelBuilder.build(request).getEffectiveModel();
    } catch (ModelBuildingException e) {
      throw new BuildException("Could not load POM " + pomFile + ": " + e.getMessage(), e);
    }
  }

  private Properties getSystemProperties() {
    Properties props = new Properties();
    getEnvProperties(props);
    props.putAll(System.getProperties());
    ConverterUtils.addProperties(props, project.getProperties());
    return props;
  }

  private Properties getEnvProperties(Properties props) {
    if (props == null) {
      props = new Properties();
    }
    boolean envCaseInsensitive = OS_WINDOWS;
    for (Map.Entry<String, String> entry : System.getenv().entrySet()) {
      String key = entry.getKey();
      if (envCaseInsensitive) {
        key = key.toUpperCase(Locale.ENGLISH);
      }
      key = "env." + key;
      props.put(key, entry.getValue());
    }
    return props;
  }

  private Properties getUserProperties() {
    return ConverterUtils.addProperties(null, project.getUserProperties());
  }

  /** Sets the default POM. */
  public void setDefaultPom(Pom pom) {
    this.defaultPom = pom;
  }

  /** Returns the current default POM. */
  public Pom getDefaultPom() {
    return defaultPom;
  }

  public CollectResult collectDependencies(
      Task task,
      Dependencies dependencies,
      LocalRepository localRepository,
      RemoteRepositories remoteRepositories) {
    RepositorySystemSession session = getSession(task, localRepository);

    remoteRepositories =
        remoteRepositories == null
            ? AetherUtils.getDefaultRepositories(project)
            : remoteRepositories;

    List<org.sonatype.aether.repository.RemoteRepository> repos =
        ConverterUtils.toRepositories(project, session, remoteRepositories, getRemoteRepoMan());

    CollectRequest collectRequest = new CollectRequest();
    collectRequest.setRequestContext("project");

    for (org.sonatype.aether.repository.RemoteRepository repo : repos) {
      task.getProject().log("Using remote repository " + repo, Project.MSG_VERBOSE);
      collectRequest.addRepository(repo);
    }

    if (dependencies != null) {
      List<Exclusion> globalExclusions = dependencies.getExclusions();
      Collection<String> ids = new HashSet<String>();

      for (Dependency dep : dependencies.getDependencies()) {
        ids.add(dep.getVersionlessKey());
        collectRequest.addDependency(ConverterUtils.toDependency(dep, globalExclusions, session));
      }

      if (dependencies.getPom() != null) {
        Model model = dependencies.getPom().getModel(task);
        for (org.apache.maven.model.Dependency dep : model.getDependencies()) {
          Dependency dependency = new Dependency();
          dependency.setArtifactId(dep.getArtifactId());
          dependency.setClassifier(dep.getClassifier());
          dependency.setGroupId(dep.getGroupId());
          dependency.setScope(dep.getScope());
          dependency.setType(dep.getType());
          dependency.setVersion(dep.getVersion());
          if (ids.contains(dependency.getVersionlessKey())) {
            continue;
          }
          if (dep.getSystemPath() != null && dep.getSystemPath().length() > 0) {
            dependency.setSystemPath(task.getProject().resolveFile(dep.getSystemPath()));
          }
          for (org.apache.maven.model.Exclusion exc : dep.getExclusions()) {
            Exclusion exclusion = new Exclusion();
            exclusion.setGroupId(exc.getGroupId());
            exclusion.setArtifactId(exc.getArtifactId());
            exclusion.setClassifier("*");
            exclusion.setExtension("*");
            dependency.addExclusion(exclusion);
          }
          collectRequest.addDependency(
              ConverterUtils.toDependency(dependency, globalExclusions, session));
        }
      }
    }

    task.getProject().log("Collecting dependencies", Project.MSG_VERBOSE);

    CollectResult result;
    try {
      result = getSystem().collectDependencies(session, collectRequest);
    } catch (DependencyCollectionException e) {
      throw new BuildException("Could not collect dependencies: " + e.getMessage(), e);
    }

    return result;
  }
}
/** JUnit 3 testcases for org.apache.tools.ant.DirectoryScanner */
public class DirectoryScannerTest extends BuildFileTest {

  public DirectoryScannerTest(String name) {
    super(name);
  }

  // keep track of what operating systems are supported here.
  private boolean supportsSymlinks = Os.isFamily("unix");

  public void setUp() {
    configureProject("src/etc/testcases/core/directoryscanner.xml");
    getProject().executeTarget("setup");
  }

  public void tearDown() {
    getProject().executeTarget("cleanup");
  }

  public void test1() {
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
    ds.setIncludes(new String[] {"alpha"});
    ds.scan();
    compareFiles(ds, new String[] {}, new String[] {"alpha"});
  }

  public void test2() {
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
    ds.setIncludes(new String[] {"alpha/"});
    ds.scan();
    compareFiles(
        ds,
        new String[] {"alpha/beta/beta.xml", "alpha/beta/gamma/gamma.xml"},
        new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
  }

  public void test3() {
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
    ds.scan();
    compareFiles(
        ds,
        new String[] {"alpha/beta/beta.xml", "alpha/beta/gamma/gamma.xml"},
        new String[] {"", "alpha", "alpha/beta", "alpha/beta/gamma"});
  }

  public void testFullPathMatchesCaseSensitive() {
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
    ds.setIncludes(new String[] {"alpha/beta/gamma/GAMMA.XML"});
    ds.scan();
    compareFiles(ds, new String[] {}, new String[] {});
  }

  public void testFullPathMatchesCaseInsensitive() {
    DirectoryScanner ds = new DirectoryScanner();
    ds.setCaseSensitive(false);
    ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
    ds.setIncludes(new String[] {"alpha/beta/gamma/GAMMA.XML"});
    ds.scan();
    compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"}, new String[] {});
  }

  public void test2ButCaseInsensitive() {
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
    ds.setIncludes(new String[] {"ALPHA/"});
    ds.setCaseSensitive(false);
    ds.scan();
    compareFiles(
        ds,
        new String[] {"alpha/beta/beta.xml", "alpha/beta/gamma/gamma.xml"},
        new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
  }

  public void testAllowSymlinks() {
    if (!supportsSymlinks) {
      return;
    }

    getProject().executeTarget("symlink-setup");
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
    ds.setIncludes(new String[] {"alpha/beta/gamma/"});
    ds.scan();
    compareFiles(
        ds, new String[] {"alpha/beta/gamma/gamma.xml"}, new String[] {"alpha/beta/gamma"});
  }

  public void testProhibitSymlinks() {
    if (!supportsSymlinks) {
      return;
    }

    getProject().executeTarget("symlink-setup");
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
    ds.setIncludes(new String[] {"alpha/beta/gamma/"});
    ds.setFollowSymlinks(false);
    ds.scan();
    compareFiles(ds, new String[] {}, new String[] {});
  }

  // father and child pattern test
  public void testOrderOfIncludePatternsIrrelevant() {
    String[] expectedFiles = {"alpha/beta/beta.xml", "alpha/beta/gamma/gamma.xml"};
    String[] expectedDirectories = {"alpha/beta", "alpha/beta/gamma"};
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
    ds.setIncludes(new String[] {"alpha/be?a/**", "alpha/beta/gamma/"});
    ds.scan();
    compareFiles(ds, expectedFiles, expectedDirectories);
    // redo the test, but the 2 include patterns are inverted
    ds = new DirectoryScanner();
    ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
    ds.setIncludes(new String[] {"alpha/beta/gamma/", "alpha/be?a/**"});
    ds.scan();
    compareFiles(ds, expectedFiles, expectedDirectories);
  }

  public void testPatternsDifferInCaseScanningSensitive() {
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
    ds.setIncludes(new String[] {"alpha/", "ALPHA/"});
    ds.scan();
    compareFiles(
        ds,
        new String[] {"alpha/beta/beta.xml", "alpha/beta/gamma/gamma.xml"},
        new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
  }

  public void testPatternsDifferInCaseScanningInsensitive() {
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
    ds.setIncludes(new String[] {"alpha/", "ALPHA/"});
    ds.setCaseSensitive(false);
    ds.scan();
    compareFiles(
        ds,
        new String[] {"alpha/beta/beta.xml", "alpha/beta/gamma/gamma.xml"},
        new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
  }

  public void testFullpathDiffersInCaseScanningSensitive() {
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
    ds.setIncludes(new String[] {"alpha/beta/gamma/gamma.xml", "alpha/beta/gamma/GAMMA.XML"});
    ds.scan();
    compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"}, new String[] {});
  }

  public void testFullpathDiffersInCaseScanningInsensitive() {
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
    ds.setIncludes(new String[] {"alpha/beta/gamma/gamma.xml", "alpha/beta/gamma/GAMMA.XML"});
    ds.setCaseSensitive(false);
    ds.scan();
    compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"}, new String[] {});
  }

  public void testParentDiffersInCaseScanningSensitive() {
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
    ds.setIncludes(new String[] {"alpha/", "ALPHA/beta/"});
    ds.scan();
    compareFiles(
        ds,
        new String[] {"alpha/beta/beta.xml", "alpha/beta/gamma/gamma.xml"},
        new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
  }

  public void testParentDiffersInCaseScanningInsensitive() {
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
    ds.setIncludes(new String[] {"alpha/", "ALPHA/beta/"});
    ds.setCaseSensitive(false);
    ds.scan();
    compareFiles(
        ds,
        new String[] {"alpha/beta/beta.xml", "alpha/beta/gamma/gamma.xml"},
        new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
  }

  /**
   * Test case for setFollowLinks() and associated functionality. Only supports test on Linux at the
   * moment because Java has no real notion of symlinks built in, so an os-specfic call to
   * Runtime.exec() must be made to create a link to test against.
   */
  public void testSetFollowLinks() throws IOException {
    if (supportsSymlinks) {
      File linkFile = new File(System.getProperty("root"), "src/main/org/apache/tools/ThisIsALink");
      System.err.println("link exists pre-test? " + linkFile.exists());

      try {
        // add conditions and more commands as soon as the need arises
        String[] command = new String[] {"ln", "-s", "ant", linkFile.getAbsolutePath()};
        try {
          Runtime.getRuntime().exec(command);
          // give ourselves some time for the system call
          // to execute... tweak if you have a really over
          // loaded system.
          Thread.sleep(1000);
        } catch (IOException ioe) {
          fail("IOException making link " + ioe);
        } catch (InterruptedException ie) {
        }

        File dir = new File(System.getProperty("root"), "src/main/org/apache/tools");
        System.err.println("link exists after exec? " + linkFile.exists());
        System.err.println(
            "Ant knows it is a link? "
                + FileUtils.getFileUtils().isSymbolicLink(dir, "ThisIsALink"));

        DirectoryScanner ds = new DirectoryScanner();

        // followLinks should be true by default, but if this ever
        // changes we will need this line.
        ds.setFollowSymlinks(true);

        ds.setBasedir(dir);
        ds.setExcludes(new String[] {"ant/**"});
        ds.scan();

        boolean haveZipPackage = false;
        boolean haveTaskdefsPackage = false;

        String[] included = ds.getIncludedDirectories();
        for (int i = 0; i < included.length; i++) {
          if (included[i].equals("zip")) {
            haveZipPackage = true;
          } else if (included[i].equals("ThisIsALink" + File.separator + "taskdefs")) {
            haveTaskdefsPackage = true;
          }
        }

        // if we followed the symlink we just made we should
        // bypass the excludes.

        assertTrue("(1) zip package included", haveZipPackage);
        assertTrue("(1) taskdefs package included", haveTaskdefsPackage);

        ds = new DirectoryScanner();
        ds.setFollowSymlinks(false);

        ds.setBasedir(dir);
        ds.setExcludes(new String[] {"ant/**"});
        ds.scan();

        haveZipPackage = false;
        haveTaskdefsPackage = false;
        included = ds.getIncludedDirectories();
        for (int i = 0; i < included.length; i++) {
          if (included[i].equals("zip")) {
            haveZipPackage = true;
          } else if (included[i].equals("ThisIsALink" + File.separator + "taskdefs")) {
            haveTaskdefsPackage = true;
          }
        }
        assertTrue("(2) zip package included", haveZipPackage);
        assertTrue("(2) taskdefs package not included", !haveTaskdefsPackage);

      } finally {
        System.err.println("link exists pre-delete? " + linkFile.exists());
        if (!linkFile.delete()) {
          throw new RuntimeException("Failed to delete " + linkFile);
        }
        System.err.println("link exists post-delete? " + linkFile.exists());
      }
    }
  }

  public void testExcludeOneFile() {
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
    ds.setIncludes(new String[] {"**/*.xml"});
    ds.setExcludes(new String[] {"alpha/beta/b*xml"});
    ds.scan();
    compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"}, new String[] {});
  }

  public void testExcludeHasPrecedence() {
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
    ds.setIncludes(new String[] {"alpha/**"});
    ds.setExcludes(new String[] {"alpha/**"});
    ds.scan();
    compareFiles(ds, new String[] {}, new String[] {});
  }

  public void testAlternateIncludeExclude() {
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
    ds.setIncludes(new String[] {"alpha/**", "alpha/beta/gamma/**"});
    ds.setExcludes(new String[] {"alpha/beta/**"});
    ds.scan();
    compareFiles(ds, new String[] {}, new String[] {"alpha"});
  }

  public void testAlternateExcludeInclude() {
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
    ds.setExcludes(new String[] {"alpha/**", "alpha/beta/gamma/**"});
    ds.setIncludes(new String[] {"alpha/beta/**"});
    ds.scan();
    compareFiles(ds, new String[] {}, new String[] {});
  }

  /** Test inspired by Bug#1415. */
  public void testChildrenOfExcludedDirectory() {
    getProject().executeTarget("children-of-excluded-dir-setup");
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
    ds.setExcludes(new String[] {"alpha/**"});
    ds.setFollowSymlinks(false);
    ds.scan();
    compareFiles(ds, new String[] {"delta/delta.xml"}, new String[] {"", "delta"});

    ds = new DirectoryScanner();
    ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
    ds.setExcludes(new String[] {"alpha"});
    ds.setFollowSymlinks(false);
    ds.scan();
    compareFiles(
        ds,
        new String[] {"alpha/beta/beta.xml", "alpha/beta/gamma/gamma.xml", "delta/delta.xml"},
        new String[] {"", "alpha/beta", "alpha/beta/gamma", "delta"});
  }

  public void testIsExcludedDirectoryScanned() {
    getProject().executeTarget("children-of-excluded-dir-setup");
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
    ds.setExcludes(new String[] {"**/gamma/**"});
    ds.setFollowSymlinks(false);
    ds.scan();
    Set set = ds.getScannedDirs();
    assertFalse("empty set", set.isEmpty());
    String s = "alpha/beta/gamma/".replace('/', File.separatorChar);
    assertFalse("scanned " + s, set.contains(s));
  }

  private void compareFiles(
      DirectoryScanner ds, String[] expectedFiles, String[] expectedDirectories) {
    String includedFiles[] = ds.getIncludedFiles();
    String includedDirectories[] = ds.getIncludedDirectories();
    assertEquals("file present: ", expectedFiles.length, includedFiles.length);
    assertEquals("directories present: ", expectedDirectories.length, includedDirectories.length);

    TreeSet files = new TreeSet();
    for (int counter = 0; counter < includedFiles.length; counter++) {
      files.add(includedFiles[counter].replace(File.separatorChar, '/'));
    }
    TreeSet directories = new TreeSet();
    for (int counter = 0; counter < includedDirectories.length; counter++) {
      directories.add(includedDirectories[counter].replace(File.separatorChar, '/'));
    }

    String currentfile;
    Iterator i = files.iterator();
    int counter = 0;
    while (i.hasNext()) {
      currentfile = (String) i.next();
      assertEquals(expectedFiles[counter], currentfile);
      counter++;
    }
    String currentdirectory;
    Iterator dirit = directories.iterator();
    counter = 0;
    while (dirit.hasNext()) {
      currentdirectory = (String) dirit.next();
      assertEquals(expectedDirectories[counter], currentdirectory);
      counter++;
    }
  }
}
Пример #6
0
  /**
   * execute this task.
   *
   * @throws BuildException on error.
   */
  public void execute() throws BuildException {

    checkConfiguration();

    Vector files = getFileList();

    // quick exit if the target is up to date
    if (isUpToDate(files)) {
      return;
    }

    log("Building " + archiveType + ": " + cabFile.getAbsolutePath());

    if (!Os.isFamily("windows")) {
      log("Using listcab/libcabinet", Project.MSG_VERBOSE);

      StringBuffer sb = new StringBuffer();

      Enumeration fileEnum = files.elements();

      while (fileEnum.hasMoreElements()) {
        sb.append(fileEnum.nextElement()).append("\n");
      }
      sb.append("\n").append(cabFile.getAbsolutePath()).append("\n");

      try {
        Process p =
            Execute.launch(
                getProject(),
                new String[] {"listcab"},
                null,
                baseDir != null ? baseDir : getProject().getBaseDir(),
                true);
        OutputStream out = p.getOutputStream();

        // Create the stream pumpers to forward listcab's stdout and stderr to the log
        // note: listcab is an interactive program, and issues prompts for every new line.
        //       Therefore, make it show only with verbose logging turned on.
        LogOutputStream outLog = new LogOutputStream(this, Project.MSG_VERBOSE);
        LogOutputStream errLog = new LogOutputStream(this, Project.MSG_ERR);
        StreamPumper outPump = new StreamPumper(p.getInputStream(), outLog);
        StreamPumper errPump = new StreamPumper(p.getErrorStream(), errLog);

        // Pump streams asynchronously
        (new Thread(outPump)).start();
        (new Thread(errPump)).start();

        out.write(sb.toString().getBytes());
        out.flush();
        out.close();

        // A wild default for when the thread is interrupted
        int result = DEFAULT_RESULT;

        try {
          // Wait for the process to finish
          result = p.waitFor();

          // Wait for the end of output and error streams
          outPump.waitFor();
          outLog.close();
          errPump.waitFor();
          errLog.close();
        } catch (InterruptedException ie) {
          log("Thread interrupted: " + ie);
        }

        // Informative summary message in case of errors
        if (Execute.isFailure(result)) {
          log("Error executing listcab; error code: " + result);
        }
      } catch (IOException ex) {
        String msg = "Problem creating " + cabFile + " " + ex.getMessage();
        throw new BuildException(msg, getLocation());
      }
    } else {
      try {
        File listFile = createListFile(files);
        ExecTask exec = createExec();
        File outFile = null;

        // die if cabarc fails
        exec.setFailonerror(true);
        exec.setDir(baseDir);

        if (!doVerbose) {
          outFile = FILE_UTILS.createTempFile("ant", "", null, true, true);
          exec.setOutput(outFile);
        }

        exec.setExecutable("cabarc");
        exec.createArg().setValue("-r");
        exec.createArg().setValue("-p");

        if (!doCompress) {
          exec.createArg().setValue("-m");
          exec.createArg().setValue("none");
        }

        if (cmdOptions != null) {
          exec.createArg().setLine(cmdOptions);
        }

        exec.createArg().setValue("n");
        exec.createArg().setFile(cabFile);
        exec.createArg().setValue("@" + listFile.getAbsolutePath());

        exec.execute();

        if (outFile != null) {
          outFile.delete();
        }

        listFile.delete();
      } catch (IOException ioe) {
        String msg = "Problem creating " + cabFile + " " + ioe.getMessage();
        throw new BuildException(msg, getLocation());
      }
    }
  }
Пример #7
0
 /**
  * Check if the os is valid. Default is to allow windows
  *
  * @return true if the os is valid.
  */
 protected boolean isValidOs() {
   return getOs() == null && getOsFamily() == null
       ? Os.isFamily(Os.FAMILY_WINDOWS)
       : super.isValidOs();
 }