public PluginsEnvironmentBuilder(File dir) throws Exception {
    DirectoryScanner directoryScanner = new DirectoryScanner();

    directoryScanner.setBasedir(dir);
    directoryScanner.setIncludes(new String[] {"**\\liferay-plugin-package.properties"});

    directoryScanner.scan();

    String dirName = dir.getCanonicalPath();

    for (String fileName : directoryScanner.getIncludedFiles()) {
      setupWarProject(dirName, fileName);
    }

    directoryScanner = new DirectoryScanner();

    directoryScanner.setBasedir(dir);
    directoryScanner.setIncludes(new String[] {"**\\build.xml"});

    directoryScanner.scan();

    for (String fileName : directoryScanner.getIncludedFiles()) {
      String content = _fileUtil.read(dirName + "/" + fileName);

      boolean osgiProject = false;

      if (content.contains("<import file=\"../../build-common-osgi-plugin.xml\" />")
          || content.contains("../tools/sdk/build-common-osgi-plugin.xml\" />")) {

        osgiProject = true;
      }

      boolean sharedProject = false;

      if (content.contains("<import file=\"../build-common-shared.xml\" />")
          || content.contains("../tools/sdk/build-common-shared.xml\" />")) {

        sharedProject = true;
      }

      List<String> dependencyJars = Collections.emptyList();

      if (osgiProject) {
        int x = content.indexOf("osgi.ide.dependencies");

        if (x != -1) {
          x = content.indexOf("value=\"", x);
          x = content.indexOf("\"", x);

          int y = content.indexOf("\"", x + 1);

          dependencyJars = Arrays.asList(StringUtil.split(content.substring(x + 1, y)));
        }
      }

      if (osgiProject || sharedProject) {
        setupJarProject(dirName, fileName, dependencyJars, sharedProject);
      }
    }
  }
 private String[] findJsonFiles(File targetDirectory) {
   DirectoryScanner scanner = new DirectoryScanner();
   scanner.setIncludes(new String[] {"**/*.json"});
   scanner.setBasedir(targetDirectory);
   scanner.scan();
   return scanner.getIncludedFiles();
 }
Beispiel #3
0
  private DirectoryScanner scan(FileSet fileSet) {
    File basedir = new File(fileSet.getDirectory());

    if (!basedir.exists() || !basedir.isDirectory()) {
      return null;
    }

    DirectoryScanner scanner = new DirectoryScanner();

    List<String> includesList = fileSet.getIncludes();
    List<String> excludesList = fileSet.getExcludes();

    if (includesList.size() > 0) {
      scanner.setIncludes(includesList.toArray(new String[0]));
    }

    if (excludesList.size() > 0) {
      scanner.setExcludes(excludesList.toArray(new String[0]));
    }

    if (true) // fileSet.isUseDefaultExcludes() )
    {
      scanner.addDefaultExcludes();
    }

    scanner.setBasedir(basedir);
    scanner.setFollowSymlinks(true); // fileSet.isFollowSymlinks() );

    scanner.scan();

    return scanner;
  }
Beispiel #4
0
 /**
  * Fulfill the ResourceCollection contract.
  *
  * @return number of elements as int.
  */
 public synchronized int size() {
   if (isReference()) {
     return getRef().size();
   }
   ensureDirectoryScannerSetup();
   ds.scan();
   return ds.getIncludedFilesCount() + ds.getIncludedDirsCount();
 }
 /** Converts the file(s) identified by the given pattern. */
 public static void convert(String pattern, boolean compress) throws IOException {
   DirectoryScanner scanner = new DirectoryScanner();
   scanner.setBasedir(".");
   scanner.setIncludes(new String[] {pattern});
   scanner.scan();
   for (String source : scanner.getIncludedFiles()) {
     try {
       convert(source, source, compress);
     } catch (IOException e) {
       log.warning("Error converting file.", "file", source, e);
     }
   }
 }
 private String[] findJsonFiles(
     File targetDirectory, String fileIncludePattern, String fileExcludePattern) {
   DirectoryScanner scanner = new DirectoryScanner();
   if (fileIncludePattern == null || fileIncludePattern.isEmpty()) {
     scanner.setIncludes(new String[] {DEFAULT_FILE_INCLUDE_PATTERN});
   } else {
     scanner.setIncludes(new String[] {fileIncludePattern});
   }
   if (fileExcludePattern != null) {
     scanner.setExcludes(new String[] {fileExcludePattern});
   }
   scanner.setBasedir(targetDirectory);
   scanner.scan();
   return scanner.getIncludedFiles();
 }
Beispiel #7
0
  public void produce(final DataConsumer pReceiver) throws IOException {
    String user = "******";
    int uid = 0;
    String group = "root";
    int gid = 0;
    int filemode = TarEntry.DEFAULT_FILE_MODE;
    int dirmode = TarEntry.DEFAULT_DIR_MODE;
    String prefix = "";

    if (fileset instanceof Tar.TarFileSet) {
      Tar.TarFileSet tarfileset = (Tar.TarFileSet) fileset;
      user = tarfileset.getUserName();
      uid = tarfileset.getUid();
      group = tarfileset.getGroup();
      gid = tarfileset.getGid();
      filemode = tarfileset.getMode();
      dirmode = tarfileset.getDirMode(tarfileset.getProject());
      prefix = tarfileset.getPrefix(tarfileset.getProject());
    }

    final DirectoryScanner scanner = fileset.getDirectoryScanner(fileset.getProject());
    scanner.scan();

    final File basedir = scanner.getBasedir();

    final String[] directories = scanner.getIncludedDirectories();
    for (int i = 0; i < directories.length; i++) {
      final String name = directories[i].replace('\\', '/');

      pReceiver.onEachDir(prefix + "/" + name, null, user, uid, group, gid, dirmode, 0);
    }

    final String[] files = scanner.getIncludedFiles();
    for (int i = 0; i < files.length; i++) {
      final String name = files[i].replace('\\', '/');
      final File file = new File(basedir, name);

      final InputStream inputStream = new FileInputStream(file);
      try {
        pReceiver.onEachFile(
            inputStream, prefix + "/" + name, null, user, uid, group, gid, filemode, file.length());
      } finally {
        inputStream.close();
      }
    }
  }
  public ExtInfoBuilder(String basedir, String outputDir, String servletContextName)
      throws Exception {

    DirectoryScanner ds = new DirectoryScanner();

    ds.setBasedir(basedir);
    ds.setExcludes(
        new String[] {
          ".svn/**",
          "**/.svn/**",
          "ext-impl/ext-impl.jar",
          "ext-impl/src/**",
          "ext-service/ext-service.jar",
          "ext-service/src/**",
          "ext-util-bridges/ext-util-bridges.jar",
          "ext-util-bridges/src/**",
          "ext-util-java/ext-util-java.jar",
          "ext-util-java/src/**",
          "ext-util-taglib/ext-util-taglib.jar",
          "ext-util-taglib/src/**",
          "liferay-plugin-package.properties"
        });

    ds.scan();

    String[] files = ds.getIncludedFiles();

    Arrays.sort(files);

    Element rootElement = new ElementImpl(DocumentHelper.createElement("ext-info"));

    Document document = new DocumentImpl(DocumentHelper.createDocument());

    document.setRootElement(rootElement);

    DocUtil.add(rootElement, "servlet-context-name", servletContextName);

    Element filesElement = rootElement.addElement("files");

    for (String file : files) {
      DocUtil.add(
          filesElement, "file", StringUtil.replace(file, StringPool.BACK_SLASH, StringPool.SLASH));
    }

    _fileUtil.write(outputDir + "/ext-" + servletContextName + ".xml", document.formattedString());
  }
  private Collection<Violation> parseReportIn(
      final String baseDir, final SwiftLintReportParser parser) {

    DirectoryScanner scanner = new DirectoryScanner();
    scanner.setIncludes(new String[] {reportPath()});
    scanner.setBasedir(baseDir);
    scanner.setCaseSensitive(false);
    scanner.scan();
    String[] files = scanner.getIncludedFiles();

    Collection<Violation> result = new ArrayList<Violation>();
    for (String filename : files) {
      LOGGER.info("Processing SwiftLint report {}", filename);
      result.addAll(parser.parseReport(new File(filename)));
    }

    return result;
  }
Beispiel #10
0
  /**
   * Protected method for simplyfied addinng of mapped files
   *
   * @param file file to add
   * @param baseDir base directory for file
   */
  protected void addMappedFile(File file, File baseDir) {
    if (file.isFile()) {
      if (baseDir == null) {
        baseDir = file.getParentFile();
      }
      MappedFile mappedFile = new MappedFile();
      mappedFile.setFrom(file);
      String filename = file.getName();

      String[] names = getMapper().mapFileName(filename);
      // we don't use original filename if no mapping is available
      if (names == null || names.length == 0) {
        return;
      }

      File newFile = new File(file.getParent() + System.getProperty("file.separator") + names[0]);
      if (getDestDir() != null) {
        try {
          newFile =
              new File(
                  newFile
                      .getCanonicalPath()
                      .replace(baseDir.getCanonicalPath(), getDestDir().getCanonicalPath()));
        } catch (IOException ex) {
          log("Couldn't map file", ex, Project.MSG_WARN);
          return;
        }
      }
      mappedFile.setTo(newFile);
      mappedFiles.add(mappedFile);
    } else if (file.isDirectory()) {
      if (baseDir == null) {
        baseDir = file;
      }
      DirectoryScanner ds = new DirectoryScanner();
      ds.setBasedir(file);
      ds.scan();

      for (String fileName : ds.getIncludedFiles()) {
        addMappedFile(new File(file + System.getProperty("file.separator") + fileName), baseDir);
      }
    }
  }
Beispiel #11
0
 /**
  * Fulfill the ResourceCollection contract.
  *
  * @return an Iterator of Resources.
  */
 public synchronized Iterator iterator() {
   if (isReference()) {
     return getRef().iterator();
   }
   ensureDirectoryScannerSetup();
   ds.scan();
   int fct = ds.getIncludedFilesCount();
   int dct = ds.getIncludedDirsCount();
   if (fct + dct == 0) {
     return EMPTY_ITERATOR;
   }
   FileResourceIterator result = new FileResourceIterator(getProject());
   if (fct > 0) {
     result.addFiles(ds.getIncludedFiles());
   }
   if (dct > 0) {
     result.addFiles(ds.getIncludedDirectories());
   }
   return result;
 }
  private void _collectSassFiles(List<String> fileNames, String dirName, String docrootDirName)
      throws Exception {

    DirectoryScanner directoryScanner = new DirectoryScanner();

    String basedir = docrootDirName.concat(dirName);

    directoryScanner.setBasedir(basedir);

    directoryScanner.setExcludes(
        new String[] {
          "**\\_*.scss",
          "**\\_diffs\\**",
          "**\\.sass-cache*\\**",
          "**\\.sass_cache_*\\**",
          "**\\_sass_cache_*\\**",
          "**\\_styled\\**",
          "**\\_unstyled\\**",
          "**\\css\\aui\\**",
          "**\\tmp\\**"
        });
    directoryScanner.setIncludes(new String[] {"**\\*.css", "**\\*.scss"});

    directoryScanner.scan();

    String[] fileNamesArray = directoryScanner.getIncludedFiles();

    if (!_isModified(basedir, fileNamesArray)) {
      return;
    }

    for (String fileName : fileNamesArray) {
      if (fileName.contains("_rtl")) {
        continue;
      }

      fileNames.add(_normalizeFileName(dirName, fileName));
    }
  }
Beispiel #13
0
  @Override
  public void execute() throws BuildException {
    ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
    try {
      // make sure RESTEasy classes will be found:
      Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
      DirectoryScanner ds = getDirectoryScanner(srcDir);
      // use default includes if unset:
      if (!getImplicitFileSet().hasPatterns()) {
        ds.setIncludes(new String[] {"**/*.properties"}); // $NON-NLS-1$
      }
      ds.setSelectors(getSelectors());
      ds.scan();
      String[] files = ds.getIncludedFiles();

      Marshaller m = null;
      // JAXBContext jc = JAXBContext.newInstance(Documents.class);
      // m = jc.createMarshaller();
      if (debug) {
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
      }

      // Documents docs = new Documents();
      // List<Document> docList = docs.getDocuments();
      PropReader propReader = new PropReader();
      // for each of the base props files under srcdir:
      int i = 0;
      for (String filename : files) {
        progress.update(i++, files.length);
        // Document doc = new Document(filename, ContentType.TextPlain);
        // doc.setLang(LocaleId.fromJavaName(sourceLang));
        File f = new File(srcDir, filename);
        // propReader.extractAll(doc, f, locales, contentState);
        // docList.add(doc);
      }
      progress.finished();
      if (debug) {
        StringWriter writer = new StringWriter();
        // m.marshal(docs, writer);
        log.debug("{}", writer);
      }

      if (dst == null) return;

      URL dstURL = Utility.createURL(dst, getProject());
      if ("file".equals(dstURL.getProtocol())) {
        // m.marshal(docs, new File(dstURL.getFile()));
      } else {
        // send project to rest api
        ZanataProxyFactory factory =
            new ZanataProxyFactory(user, apiKey, new VersionInfo("SNAPSHOT", "Unknow"));
        // IDocumentsResource documentsResource =
        // factory.getDocuments(dstURL.toURI());
        // ClientResponse response = documentsResource.put(docs);
        // ClientUtility.checkResult(response, dstURL.toURI());
      }

    } catch (Exception e) {
      throw new BuildException(e);
    } finally {
      Thread.currentThread().setContextClassLoader(oldLoader);
    }
  }
  @Override
  public void execute() throws BuildException {
    DirUtil.checkDir(dir1, "dir1", false); // $NON-NLS-1$
    DirUtil.checkDir(dir2, "dir2", false); // $NON-NLS-1$

    if (mapper == null) {
      add(new IdentityMapper());
    }
    try {
      DirectoryScanner ds = super.getDirectoryScanner(dir1);
      // use default includes if unset:
      if (!getImplicitFileSet().hasPatterns())
        ds.setIncludes(new String[] {"**/*.properties"}); // $NON-NLS-1$
      ds.scan();
      String[] files = ds.getIncludedFiles();

      for (int i = 0; i < files.length; i++) {
        String prop1Filename = files[i];
        File prop1File = new File(dir1, prop1Filename);
        String[] outFile = mapper.getImplementation().mapFileName(prop1Filename);
        if (outFile == null || outFile.length == 0) {
          if (failOnNull)
            throw new BuildException("Input filename " + prop1File + " mapped to null");
          log("Skipping " + prop1File + ": filename mapped to null", Project.MSG_VERBOSE);
          continue;
        }
        String prop2Filename = outFile[0]; // FIXME support multiple output mappings?
        File prop2File = new File(dir2, prop2Filename);

        Properties props1 = new Properties();
        InputStream in1 = new FileInputStream(prop1File);
        try {
          props1.load(in1);
          Properties props2 = new Properties();
          InputStream in2 = new FileInputStream(prop2File);
          try {
            props2.load(in2);
            int errorCount = 0;
            StringBuilder errors = new StringBuilder();
            errors.append(prop1File.getPath() + " is different from " + prop2File.getPath() + ": ");
            errors.append(System.getProperty("line.separator")); // $NON-NLS-1$

            for (Map.Entry<Object, Object> entry : props1.entrySet()) {
              String propName = (String) entry.getKey();
              String prop1Val = (String) entry.getValue();
              String prop2Val = (String) props2.remove(propName);
              if (!equivalent(prop1Val, prop2Val)) {
                ++errorCount;
                recordError(
                    errors,
                    propName + " -> {" + prop1Val + ", " + prop2Val
                        + "}"); //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$
              }
            }
            if (!props2.isEmpty()) {
              ++errorCount;
              String message = "second file contains extra keys: " + props2.keySet();
              recordError(errors, message);
            }

            if (errorCount != 0) throw new BuildException(errors.toString());
          } finally {
            in2.close();
          }
        } finally {
          in1.close();
        }
      }
      log("Verified .properties files in " + dir1 + " against " + dir2, Project.MSG_VERBOSE);
    } catch (Exception e) {
      throw new BuildException(e);
    }
  }
  public JavadocFormatter(String[] args) throws Exception {
    Map<String, String> arguments = ArgumentsUtil.parseArguments(args);

    String init = arguments.get("javadoc.init");

    if (Validator.isNotNull(init) && !init.startsWith("$")) {
      _initializeMissingJavadocs = GetterUtil.getBoolean(init);
    }

    _inputDir = GetterUtil.getString(arguments.get("javadoc.input.dir"));

    if (_inputDir.startsWith("$")) {
      _inputDir = "./";
    }

    if (!_inputDir.endsWith("/")) {
      _inputDir += "/";
    }

    System.out.println("Input directory is " + _inputDir);

    String limit = arguments.get("javadoc.limit");

    _outputFilePrefix = GetterUtil.getString(arguments.get("javadoc.output.file.prefix"));

    if (_outputFilePrefix.startsWith("$")) {
      _outputFilePrefix = "javadocs";
    }

    String update = arguments.get("javadoc.update");

    if (Validator.isNotNull(update) && !update.startsWith("$")) {
      _updateJavadocs = GetterUtil.getBoolean(update);
    }

    DirectoryScanner directoryScanner = new DirectoryScanner();

    directoryScanner.setBasedir(_inputDir);
    directoryScanner.setExcludes(new String[] {"**\\classes\\**", "**\\portal-client\\**"});

    List<String> includes = new ArrayList<String>();

    if (Validator.isNotNull(limit) && !limit.startsWith("$")) {
      System.out.println("Limit on " + limit);

      String[] limitArray = StringUtil.split(limit, '/');

      for (String curLimit : limitArray) {
        includes.add("**\\" + StringUtil.replace(curLimit, ".", "\\") + "\\**\\*.java");
        includes.add("**\\" + curLimit + ".java");
      }
    } else {
      includes.add("**\\*.java");
    }

    directoryScanner.setIncludes(includes.toArray(new String[includes.size()]));

    directoryScanner.scan();

    String[] fileNames = directoryScanner.getIncludedFiles();

    if ((fileNames.length == 0) && Validator.isNotNull(limit) && !limit.startsWith("$")) {

      StringBundler sb = new StringBundler("Limit file not found: ");

      sb.append(limit);

      if (limit.contains(".")) {
        sb.append(" Specify limit filename without package path or ");
        sb.append("file type suffix.");
      }

      System.out.println(sb.toString());
    }

    _languagePropertiesFile = new File("src/content/Language.properties");

    if (_languagePropertiesFile.exists()) {
      _languageProperties = new Properties();

      _languageProperties.load(new FileInputStream(_languagePropertiesFile.getAbsolutePath()));
    }

    for (String fileName : fileNames) {
      fileName = StringUtil.replace(fileName, "\\", "/");

      _format(fileName);
    }

    for (Map.Entry<String, Tuple> entry : _javadocxXmlTuples.entrySet()) {
      Tuple tuple = entry.getValue();

      File javadocsXmlFile = (File) tuple.getObject(1);
      String oldJavadocsXmlContent = (String) tuple.getObject(2);
      Document javadocsXmlDocument = (Document) tuple.getObject(3);

      Element javadocsXmlRootElement = javadocsXmlDocument.getRootElement();

      javadocsXmlRootElement.sortElementsByChildElement("javadoc", "type");

      String newJavadocsXmlContent = javadocsXmlDocument.formattedString();

      if (!oldJavadocsXmlContent.equals(newJavadocsXmlContent)) {
        _fileUtil.write(javadocsXmlFile, newJavadocsXmlContent);
      }

      _detachUnnecessaryTypes(javadocsXmlRootElement);

      File javadocsRuntimeXmlFile =
          new File(StringUtil.replaceLast(javadocsXmlFile.toString(), "-all.xml", "-rt.xml"));

      String oldJavadocsRuntimeXmlContent = StringPool.BLANK;

      if (javadocsRuntimeXmlFile.exists()) {
        oldJavadocsRuntimeXmlContent = _fileUtil.read(javadocsRuntimeXmlFile);
      }

      String newJavadocsRuntimeXmlContent = javadocsXmlDocument.compactString();

      if (!oldJavadocsRuntimeXmlContent.equals(newJavadocsRuntimeXmlContent)) {

        _fileUtil.write(javadocsRuntimeXmlFile, newJavadocsRuntimeXmlContent);
      }
    }
  }
Beispiel #16
0
  @Override
  public void execute() throws BuildException {
    if (productDir == null) {
      throw new BuildException("must set directory of compiled product", getLocation());
    }
    if (file == null) {
      throw new BuildException("must set file for makenbm", getLocation());
    }
    if (manifest == null && moduleName == null) {
      throw new BuildException("must set module for makenbm", getLocation());
    }
    if (manifest != null && moduleName != null) {
      throw new BuildException("cannot set both manifest and module for makenbm", getLocation());
    }
    if (locales == null) {
      locales = new ArrayList<String>();
    }

    File nbm;
    String rootDir = getProject().getProperty("nbm.target.dir");
    if (rootDir != null && !rootDir.equals("")) {
      nbm = new File(rootDir, this.file.getName());
    } else {
      nbm = this.file;
    }

    // If desired, override the license and/or URL. //
    overrideURLIfNeeded();
    overrideLicenseIfNeeded();

    moduleAttributes = new ArrayList<Attributes>();
    File module = new File(productDir, moduleName);
    Attributes attr = getModuleAttributesForLocale("");
    if (attr == null) {
      // #181025: OSGi bundle, copy unmodified.
      Copy copy = new Copy();
      copy.setProject(getProject());
      copy.setOwningTarget(getOwningTarget());
      copy.setFile(module);
      copy.setTofile(new File(nbm.getAbsolutePath().replaceFirst("[.]nbm$", ".jar")));
      copy.execute();
      // XXX possibly sign it
      // XXX could try to run pack200, though not if it was signed
      return;
    }
    moduleAttributes.add(attr);
    for (String locale : locales) {
      Attributes a = getModuleAttributesForLocale(locale);
      if (a != null) moduleAttributes.add(a);
    }

    // Will create a file Info/info.xml to be stored in tmp
    // The normal case; read attributes from its manifest and maybe bundle.
    long mMod = module.lastModified();
    if (mostRecentInput < mMod) mostRecentInput = mMod;

    if (mostRecentInput < nbm.lastModified()) {
      log(
          "Skipping NBM creation as most recent input is younger: "
              + mostRecentInput
              + " than the target file: "
              + nbm.lastModified(),
          Project.MSG_VERBOSE);
      return;
    } else {
      log(
          "Most recent input: " + mostRecentInput + " file: " + nbm.lastModified(),
          Project.MSG_DEBUG);
    }

    ArrayList<ZipFileSet> infoXMLFileSets = new ArrayList<ZipFileSet>();
    for (Attributes modAttr : moduleAttributes) {
      Document infoXmlContents = createInfoXml(modAttr);
      File infofile;
      String loc = modAttr.getValue("locale");
      if (loc == null)
        throw new BuildException("Found attributes without assigned locale code", getLocation());
      try {
        infofile = File.createTempFile("info_" + loc, ".xml");
        OutputStream infoStream = new FileOutputStream(infofile);
        try {
          XMLUtil.write(infoXmlContents, infoStream);
        } finally {
          infoStream.close();
        }
      } catch (IOException e) {
        throw new BuildException(
            "exception when creating Info/info.xml for locale '" + loc + "'", e, getLocation());
      }
      infofile.deleteOnExit();
      ZipFileSet infoXML = new ZipFileSet();
      infoXML.setFile(infofile);
      if (loc.equals("")) {
        infoXML.setFullpath("Info/info.xml");
      } else {
        infoXML.setFullpath("Info/locale/info_" + loc + ".xml");
        log("Adding Info/locale/info_" + loc + ".xml file", Project.MSG_VERBOSE);
      }
      infoXMLFileSets.add(infoXML);
    }
    String codename = englishAttr.getValue("OpenIDE-Module");
    if (codename == null) new BuildException("Can't get codenamebase");

    UpdateTracking tracking = new UpdateTracking(productDir.getAbsolutePath());
    Set<String> _files = new LinkedHashSet<String>(Arrays.asList(tracking.getListOfNBM(codename)));
    List<String> __files = new ArrayList<String>(_files);
    for (String f : _files) {
      if (f.endsWith(".external")) { // #195041
        __files.remove(f.substring(0, f.length() - 9));
      }
    }
    String[] files = __files.toArray(new String[__files.size()]);
    ZipFileSet fs = new ZipFileSet();
    List<String> moduleFiles = new ArrayList<String>();
    fs.setDir(productDir);
    String[] filesForPackaging = null;
    if (usePack200 && pack200excludes != null && !pack200excludes.equals("")) {
      FileSet pack200Files = new FileSet();
      pack200Files.setDir(productDir);
      pack200Files.setExcludes(pack200excludes);
      pack200Files.setProject(getProject());
      for (int i = 0; i < files.length; i++) {
        pack200Files.createInclude().setName(files[i]);
      }
      DirectoryScanner ds = pack200Files.getDirectoryScanner();
      ds.scan();
      filesForPackaging = ds.getIncludedFiles();
    }

    List<File> packedFiles = new ArrayList<File>();
    for (int i = 0; i < files.length; i++) {
      if (usePack200) {
        File sourceFile = new File(productDir, files[i]);
        if (sourceFile.isFile() && sourceFile.getName().endsWith(".jar")) {

          boolean doPackage = true;
          if (filesForPackaging != null) {
            doPackage = false;
            for (String f : filesForPackaging) {
              if (new File(productDir, f).equals(sourceFile)) {
                doPackage = true;
                break;
              }
            }
          }
          if (doPackage) {
            // if both <filename>.jar and <filename>.jad exist - skip it
            // if both <filename>.jar and <filename>.jar.pack.gz exist - skip it
            for (String f : files) {
              if (f.equals(files[i].substring(0, files[i].lastIndexOf(".jar")) + ".jad")
                  || f.equals(files[i] + ".pack.gz")) {
                doPackage = false;
                break;
              }
            }
          }
          if (doPackage) {
            File targetFile = new File(productDir, files[i] + ".pack.gz");
            try {
              if (pack200(sourceFile, targetFile)) {
                packedFiles.add(targetFile);
                files[i] = files[i] + ".pack.gz";
              }
            } catch (IOException e) {
              if (targetFile.exists()) {
                targetFile.delete();
              }
              log("Cannot pack file " + sourceFile, e, Project.MSG_WARN);
            }
          }
        }
      }

      fs.createInclude().setName(files[i]);
      moduleFiles.add(files[i]);
    }
    fs.setPrefix("netbeans/");

    // JAR it all up together.
    long jarModified = nbm.lastModified(); // may be 0
    // log ("Ensuring existence of NBM file " + file);
    Jar jar = (Jar) getProject().createTask("jar");

    jar.setDestFile(nbm);
    jar.addZipfileset(fs);
    for (ZipFileSet zfs : infoXMLFileSets) {
      jar.addFileset(zfs);
    }

    if (main != null) { // Add the main dir
      main.setPrefix("main"); // use main prefix
      jar.addZipfileset(main);
      DirectoryScanner ds = main.getDirectoryScanner();
      ds.scan();
      String[] mainFiles = ds.getIncludedFiles();
      for (String m : mainFiles) {
        moduleFiles.add(m);
      }
    }

    if (executablesSet != null) {
      DirectoryScanner eds = executablesSet.getDirectoryScanner();
      eds.scan();
      String[] executables = eds.getIncludedFiles();

      if (executables.length > 0) {
        ZipFileSet executablesList = new ZipFileSet();
        File executablesFile;
        StringBuilder sb = new StringBuilder("");
        String ls = System.getProperty("line.separator");
        for (int i = 0; i < executables.length; i++) {
          if (i != 0) {
            sb.append(ls);
          }
          sb.append(executables[i].replace("\\", "/"));
        }
        try {
          executablesFile = File.createTempFile("executables", ".list");
          OutputStream infoStream = new FileOutputStream(executablesFile);
          try {
            infoStream.write(sb.toString().getBytes("UTF-8"));
          } finally {
            infoStream.close();
          }
        } catch (IOException e) {
          throw new BuildException(
              "exception when creating Info/executables.list", e, getLocation());
        }
        executablesFile.deleteOnExit();
        executablesList.setFile(executablesFile);
        executablesList.setFullpath("Info/executables.list");
        jar.addZipfileset(executablesList);
      }
    }

    jar.setCompress(true);
    jar.setLocation(getLocation());
    jar.init();
    jar.execute();
    for (File f : packedFiles) {
      f.delete();
    }

    // Print messages if we overrode anything. //
    if (nbm.lastModified() != jarModified) {
      if (overrideLicense()) {
        log("Overriding license with: " + getLicenseOverride());
      }
      if (overrideURL()) {
        log("Overriding homepage URL with: " + getURLOverride());
      }
    }

    // Maybe sign it.
    if (signature != null && nbm.lastModified() != jarModified) {
      if (signature.keystore == null)
        throw new BuildException("must define keystore attribute on <signature/>");
      if (signature.storepass == null)
        throw new BuildException("must define storepass attribute on <signature/>");
      if (signature.alias == null)
        throw new BuildException("must define alias attribute on <signature/>");
      if (signature.storepass.equals("?")
          || signature.storepass.indexOf("${") != -1
          || !signature.keystore.exists()) {
        log(
            "Not signing NBM file "
                + nbm
                + "; no stored-key password provided or keystore ("
                + signature.keystore.toString()
                + ") doesn't exist",
            Project.MSG_WARN);
      } else {
        log("Signing NBM file " + nbm);
        SignJar signjar = (SignJar) getProject().createTask("signjar");
        try { // Signatures changed in various Ant versions.
          try {
            SignJar.class.getMethod("setKeystore", File.class).invoke(signjar, signature.keystore);
          } catch (NoSuchMethodException x) {
            SignJar.class
                .getMethod("setKeystore", String.class)
                .invoke(signjar, signature.keystore.getAbsolutePath());
          }
          try {
            SignJar.class.getMethod("setJar", File.class).invoke(signjar, nbm);
          } catch (NoSuchMethodException x) {
            SignJar.class.getMethod("setJar", String.class).invoke(signjar, nbm.getAbsolutePath());
          }
        } catch (BuildException x) {
          throw x;
        } catch (Exception x) {
          throw new BuildException(x);
        }
        signjar.setStorepass(signature.storepass);
        signjar.setAlias(signature.alias);
        signjar.setLocation(getLocation());
        signjar.setMaxmemory(this.jarSignerMaxMemory);
        signjar.init();
        signjar.execute();
      }
    }
  }
  private void _process(String command, String limit, Boolean ignoreAutogenerated)
      throws Exception {

    DirectoryScanner ds = new DirectoryScanner();

    ds.setBasedir(_basedir);
    ds.setExcludes(new String[] {"**\\classes\\**", "**\\portal-client\\**", "**\\portal-web\\**"});

    List<String> includes = new ArrayList<String>();

    if (Validator.isNotNull(limit) && !limit.startsWith("$")) {
      String[] limitArray = StringUtil.split(limit, '/');

      for (String curLimit : limitArray) {
        includes.add("**\\" + StringUtil.replace(curLimit, ".", "\\") + "\\**\\*.java");
        includes.add("**\\" + curLimit + ".java");
      }
    } else {
      includes.add("**\\*.java");
    }

    ds.setIncludes(includes.toArray(new String[includes.size()]));

    ds.scan();

    String[] fileNames = ds.getIncludedFiles();

    for (String fileName : fileNames) {
      fileName = StringUtil.replace(fileName, "\\", "/");

      /*if (!fileName.endsWith("Isolation.java")) {
      	continue;
      }*/

      if ((ignoreAutogenerated != null) && (ignoreAutogenerated.booleanValue())) {

        File file = new File(_basedir + fileName);

        if (file.exists()) {
          String oldContent = _fileUtil.read(_basedir + fileName + "doc");

          if (_isGenerated(oldContent)) {
            continue;
          }
        }
      }

      if (command.equals("cleanup")) {
        _processGet(fileName);
        _processSave(fileName);
        _processDelete(fileName);
      } else if (command.equals("commit")) {
        _processSave(fileName);
        _processDelete(fileName);
      } else if (command.equals("delete")) {
        _processDelete(fileName);
      } else if (command.equals("get")) {
        _processGet(fileName);
      } else if (command.equals("save")) {
        _processSave(fileName);
      }
    }
  }
  public void produce(final DataConsumer pReceiver) throws IOException {
    String user = Producers.ROOT_NAME;
    int uid = Producers.ROOT_UID;
    String group = Producers.ROOT_NAME;
    int gid = Producers.ROOT_UID;
    int filemode = TarEntry.DEFAULT_FILE_MODE;
    int dirmode = TarEntry.DEFAULT_DIR_MODE;
    String prefix = "";

    if (fileset instanceof Tar.TarFileSet) {
      Tar.TarFileSet tarfileset = (Tar.TarFileSet) fileset;
      user = tarfileset.getUserName();
      uid = tarfileset.getUid();
      group = tarfileset.getGroup();
      gid = tarfileset.getGid();
      filemode = tarfileset.getMode();
      dirmode = tarfileset.getDirMode(tarfileset.getProject());
      prefix = tarfileset.getPrefix(tarfileset.getProject());
    }

    final DirectoryScanner scanner = fileset.getDirectoryScanner(fileset.getProject());
    scanner.scan();

    final File basedir = scanner.getBasedir();

    for (String directory : scanner.getIncludedDirectories()) {
      String name = directory.replace('\\', '/');

      final TarArchiveEntry entry = new TarArchiveEntry(prefix + "/" + name);
      entry.setUserName(user);
      entry.setUserId(uid);
      entry.setGroupName(group);
      entry.setGroupId(gid);
      entry.setMode(dirmode);

      pReceiver.onEachDir(entry);
    }

    for (String filename : scanner.getIncludedFiles()) {
      final String name = filename.replace('\\', '/');
      final File file = new File(basedir, name);

      final InputStream inputStream = new FileInputStream(file);
      try {
        final String entryName = prefix + "/" + name;

        final File entryPath = new File(entryName);

        final boolean symbolicLink = SymlinkUtils.isSymbolicLink(entryPath);
        final TarArchiveEntry e;
        if (symbolicLink) {
          e = new TarArchiveEntry(entryName, TarConstants.LF_SYMLINK);
          e.setLinkName(SymlinkUtils.readSymbolicLink(entryPath));
        } else {
          e = new TarArchiveEntry(entryName, true);
        }

        e.setUserId(uid);
        e.setGroupId(gid);
        e.setUserName(user);
        e.setGroupName(group);
        e.setMode(filemode);
        e.setSize(file.length());

        pReceiver.onEachFile(inputStream, e);
      } finally {
        inputStream.close();
      }
    }
  }