Exemplo n.º 1
0
  /** Executes the task. */
  public void execute() throws BuildException {
    checkParameters();

    final FileUtils fUtils = FileUtils.getFileUtils();
    final Project project = getProject();
    for (FileSet fileset : filesets) {
      final DirectoryScanner scanner = fileset.getDirectoryScanner(project);

      final File fromDir = fileset.getDir(project);
      final String[] srcFiles = scanner.getIncludedFiles();

      for (int fIndex = 0; fIndex < srcFiles.length; fIndex++) {
        final File file = fUtils.resolveFile(fromDir, srcFiles[fIndex]);

        if (!file.isFile()) {
          continue;
        }

        if (false == forceAllFiles && false == file.getName().endsWith(".java")) {
          throw new BuildException(
              "File does not end with '.java'. Use 'force' attribute to override.");
        }

        try {
          checkLicense(file);
        } catch (IOException e) {
          throw new BuildException("Could not process file: " + file.getAbsolutePath(), e);
        }
      }
    }
  }
Exemplo n.º 2
0
 public void testRealTest() throws java.io.IOException {
   FileUtils fileUtils = FileUtils.newFileUtils();
   executeTarget("realTest");
   assertTrue(
       fileUtils.contentEquals(
           project.resolveFile("../asf-logo.gif"), project.resolveFile("asf-logo.gif")));
 }
Exemplo n.º 3
0
 public void testTestUncompressedZipTask() throws java.io.IOException {
   FileUtils fileUtils = FileUtils.newFileUtils();
   executeTarget("testUncompressedZipTask");
   assertTrue(
       fileUtils.contentEquals(
           project.resolveFile("../asf-logo.gif"), project.resolveFile("asf-logo.gif")));
 }
Exemplo n.º 4
0
 /**
  * Resolves the relative or absolute pathname correctly in both Ant and command-line situations.
  * If Ant launched us, we should use the basedir of the current project to resolve relative paths.
  *
  * <p>See Bugzilla 35571.
  *
  * @param s The file
  * @return The file resolved
  */
 protected File resolveFile(final String s) {
   if (getProject() == null) {
     // Note FileUtils.getFileUtils replaces FileUtils.newFileUtils in Ant 1.6.3
     return FileUtils.getFileUtils().resolveFile(null, s);
   } else {
     return FileUtils.getFileUtils().resolveFile(getProject().getBaseDir(), s);
   }
 }
Exemplo n.º 5
0
 public void testRealTest() throws java.io.IOException {
   FileUtils fileUtils = FileUtils.newFileUtils();
   executeTarget("realTest");
   assertTrue(
       "File content mismatch after bunzip2",
       fileUtils.contentEquals(
           project.resolveFile("expected/asf-logo-huge.tar"),
           project.resolveFile("asf-logo-huge.tar")));
 }
Exemplo n.º 6
0
 /**
  * create the temp file
  *
  * @exception BuildException if something goes wrong with the build
  */
 public void execute() throws BuildException {
   if (property == null || property.length() == 0) {
     throw new BuildException("no property specified");
   }
   if (destDir == null) {
     destDir = project.resolveFile(".");
   }
   FileUtils utils = FileUtils.newFileUtils();
   File tfile = utils.createTempFile(prefix, suffix, destDir);
   project.setNewProperty(property, tfile.toString());
 }
  /**
   * load Ant properties from the source file or resource
   *
   * @exception BuildException if something goes wrong with the build
   */
  public final void execute() throws BuildException {
    // validation
    if (src == null) {
      throw new BuildException("A source resource is required.");
    }
    if (!src.isExists()) {
      if (src instanceof JavaResource) {
        // dreaded backwards compatibility
        log("Unable to find resource " + src, Project.MSG_WARN);
        return;
      }
      throw new BuildException("Source resource does not exist: " + src);
    }
    BufferedInputStream bis = null;
    Reader instream = null;
    ByteArrayInputStream tis = null;

    try {
      bis = new BufferedInputStream(src.getInputStream());
      if (encoding == null) {
        instream = new InputStreamReader(bis);
      } else {
        instream = new InputStreamReader(bis, encoding);
      }
      ChainReaderHelper crh = new ChainReaderHelper();
      crh.setPrimaryReader(instream);
      crh.setFilterChains(filterChains);
      crh.setProject(getProject());
      instream = crh.getAssembledReader();

      String text = crh.readFully(instream);

      if (text != null && text.length() != 0) {
        if (!text.endsWith("\n")) {
          text = text + "\n";
        }
        tis = new ByteArrayInputStream(text.getBytes("ISO8859_1"));
        final Properties props = new Properties();
        props.load(tis);

        Property propertyTask = new Property();
        propertyTask.bindToOwner(this);
        propertyTask.addProperties(props);
      }
    } catch (final IOException ioe) {
      throw new BuildException("Unable to load file: " + ioe, ioe, getLocation());
    } finally {
      FileUtils.close(bis);
      FileUtils.close(tis);
    }
  }
 private Class<?> findClassInComponents(final String name) throws ClassNotFoundException {
   final String classFilename = this.getClassFilename(name);
   final Enumeration<File> e = this.pathComponents.elements();
   while (e.hasMoreElements()) {
     final File pathComponent = e.nextElement();
     InputStream stream = null;
     try {
       stream = this.getResourceStream(pathComponent, classFilename);
       if (stream != null) {
         this.log("Loaded from " + pathComponent + " " + classFilename, 4);
         return this.getClassFromStream(stream, name, pathComponent);
       }
       continue;
     } catch (SecurityException se) {
       throw se;
     } catch (IOException ioe) {
       this.log(
           "Exception reading component " + pathComponent + " (reason: " + ioe.getMessage() + ")",
           3);
     } finally {
       FileUtils.close(stream);
     }
   }
   throw new ClassNotFoundException(name);
 }
Exemplo n.º 9
0
  /** Copy eligible files from the srcDir to destDir */
  private void copyFilesToDestination() {
    if (filecopyList.size() > 0) {
      log(
          "Copying "
              + filecopyList.size()
              + " file"
              + (filecopyList.size() == 1 ? "" : "s")
              + " to "
              + destDir.getAbsolutePath());

      Enumeration e = filecopyList.keys();

      while (e.hasMoreElements()) {
        String fromFile = (String) e.nextElement();
        String toFile = (String) filecopyList.get(fromFile);

        try {
          FileUtils.getFileUtils().copyFile(fromFile, toFile);
        } catch (IOException ioe) {
          String msg =
              "Failed to copy " + fromFile + " to " + toFile + " due to " + ioe.getMessage();

          throw new BuildException(msg, ioe);
        }
      }
    }
  }
  /** {@inheritDoc} */
  @Override
  protected void doConfigure(LocalContainer container) throws Exception {
    FileUtils fileUtils = FileUtils.newFileUtils();

    String autoDeployDirSetting = getPropertyValue(Oc4jPropertySet.AUTO_DEPLOY_DIR);
    if (autoDeployDirSetting == null) {
      throw new CargoException(
          "Can not start container without the "
              + Oc4jPropertySet.AUTO_DEPLOY_DIR
              + " property set");
    }
    File autoDeployDir = new File(autoDeployDirSetting);

    String appDir = autoDeployDir.getAbsolutePath();

    // Deploy all deployables into the applications directory
    for (Deployable deployable : getDeployables()) {
      if (deployable.getType() == DeployableType.EAR) {
        fileUtils.copyFile(
            deployable.getFile(),
            getFileHandler().append(appDir, getFileHandler().getName(deployable.getFile())),
            null,
            true);
      } else {
        throw new CargoException(
            "Only deployables of type " + DeployableType.EAR + " is supported");
      }
    }

    // Deploy the cargocpc web-app by packaging it as an EAR and auto-deploy
    Ear ear = (Ear) getAntUtils().createAntTask("ear");
    File tmpDir = new File(getFileHandler().createUniqueTmpDirectory());
    File appXml = new File(tmpDir, "application.xml");
    getResourceUtils()
        .copyResource(RESOURCE_PATH + "cargocpc.war", new File(tmpDir, "cargocpc.war"));
    getResourceUtils().copyResource(RESOURCE_PATH + "oc4j10x/application.xml", appXml);
    ear.setAppxml(appXml);
    FileSet fileSet = new FileSet();
    fileSet.setDir(tmpDir);
    fileSet.createInclude().setName("cargocpc.war");
    ear.addFileset(fileSet);
    ear.setDestFile(new File(appDir, "cargocpc.ear"));
    ear.execute();

    getFileHandler().delete(tmpDir.getAbsolutePath());
  }
Exemplo n.º 11
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));
 }
Exemplo n.º 12
0
  /**
   * Creates a list file. This temporary file contains a list of all files to be included in the
   * cab, one file per line.
   *
   * <p>This method expects to only be called on Windows and thus quotes the file names.
   *
   * @param files the list of files to use.
   * @return the list file created.
   * @throws IOException if there is an error.
   */
  protected File createListFile(Vector files) throws IOException {
    File listFile = FILE_UTILS.createTempFile("ant", "", null, true, true);

    BufferedWriter writer = null;
    try {
      writer = new BufferedWriter(new FileWriter(listFile));

      final int size = files.size();
      for (int i = 0; i < size; i++) {
        writer.write('\"' + files.elementAt(i).toString() + '\"');
        writer.newLine();
      }
    } finally {
      FileUtils.close(writer);
    }

    return listFile;
  }
Exemplo n.º 13
0
 /**
  * Creates the temporary file.
  *
  * @exception BuildException if something goes wrong with the build
  */
 public void execute() throws BuildException {
   if (property == null || property.length() == 0) {
     throw new BuildException("no property specified");
   }
   if (destDir == null) {
     destDir = getProject().resolveFile(".");
   }
   File tfile = FILE_UTILS.createTempFile(prefix, suffix, destDir, deleteOnExit, createFile);
   getProject().setNewProperty(property, tfile.toString());
 }
Exemplo n.º 14
0
 /**
  * Check to see if the target is up to date with respect to input files.
  *
  * @param files the list of files to check.
  * @return true if the cab file is newer than its dependents.
  */
 protected boolean isUpToDate(Vector files) {
   boolean upToDate = true;
   final int size = files.size();
   for (int i = 0; i < size && upToDate; i++) {
     String file = files.elementAt(i).toString();
     if (FILE_UTILS.resolveFile(baseDir, file).lastModified() > cabFile.lastModified()) {
       upToDate = false;
     }
   }
   return upToDate;
 }
Exemplo n.º 15
0
  public void fill() throws JRException {
    try {
      long start = System.currentTimeMillis();

      String rtfText = FileUtils.readFully(new FileReader(new File("reports/rtf.txt")));
      String htmlText = FileUtils.readFully(new FileReader(new File("reports/html.txt")));

      Map<String, Object> parameters = new HashMap<String, Object>();
      parameters.put("RtfText", rtfText);
      parameters.put("HtmlText", htmlText);

      JasperFillManager.fillReportToFile(
          "build/reports/MarkupReport.jasper", parameters, (JRDataSource) null);
      System.err.println("Filling time : " + (System.currentTimeMillis() - start));
    } catch (FileNotFoundException e) {
      throw new JRException(e);
    } catch (IOException e) {
      throw new JRException(e);
    }
  }
  /**
   * transformation
   *
   * @throws BuildException exception if something goes wrong with the transformation.
   */
  public void transform() throws BuildException {
    checkOptions();
    Project project = task.getProject();

    TempFile tempFileTask = new TempFile();
    tempFileTask.bindToOwner(task);

    XSLTProcess xsltTask = new XSLTProcess();
    xsltTask.bindToOwner(task);

    xsltTask.setXslResource(getStylesheet());

    // acrobatic cast.
    xsltTask.setIn(((XMLResultAggregator) task).getDestinationFile());
    File outputFile = null;
    if (format.equals(FRAMES)) {
      String tempFileProperty = getClass().getName() + String.valueOf(counter++);
      File tmp =
          FILE_UTILS.resolveFile(project.getBaseDir(), project.getProperty("java.io.tmpdir"));
      tempFileTask.setDestDir(tmp);
      tempFileTask.setProperty(tempFileProperty);
      tempFileTask.execute();
      outputFile = new File(project.getProperty(tempFileProperty));
    } else {
      outputFile = new File(toDir, "junit-noframes.html");
    }
    xsltTask.setOut(outputFile);
    for (Iterator i = params.iterator(); i.hasNext(); ) {
      XSLTProcess.Param param = (XSLTProcess.Param) i.next();
      XSLTProcess.Param newParam = xsltTask.createParam();
      newParam.setProject(task.getProject());
      newParam.setName(param.getName());
      newParam.setExpression(param.getExpression());
    }
    XSLTProcess.Param paramx = xsltTask.createParam();
    paramx.setProject(task.getProject());
    paramx.setName("output.dir");
    paramx.setExpression(toDir.getAbsolutePath());
    final long t0 = System.currentTimeMillis();
    try {
      xsltTask.execute();
    } catch (Exception e) {
      throw new BuildException("Errors while applying transformations: " + e.getMessage(), e);
    }
    final long dt = System.currentTimeMillis() - t0;
    task.log("Transform time: " + dt + "ms");
    if (format.equals(FRAMES)) {
      Delete delete = new Delete();
      delete.bindToOwner(task);
      delete.setFile(outputFile);
      delete.execute();
    }
  }
Exemplo n.º 17
0
 private void setLastModified(File localFile) throws JSchException {
   SftpATTRS fileAttributes = null;
   String remotePath = null;
   ChannelSftp channel = openSftpChannel();
   channel.connect();
   try {
     fileAttributes = channel.lstat(remoteDir(remoteFile) + localFile.getName());
   } catch (SftpException e) {
     throw new JSchException("failed to stat remote file", e);
   }
   FileUtils.getFileUtils()
       .setFileLastModified(localFile, ((long) fileAttributes.getMTime()) * 1000);
 }
Exemplo n.º 18
0
  /**
   * helper method to execute our command on VMS.
   *
   * @param cmd
   * @param firstFileName
   * @return
   */
  private boolean execOnVMS(Commandline cmd, int firstFileName) {
    File vmsFile = null;
    try {
      vmsFile = JavaEnvUtils.createVmsJavaOptionFile(cmd.getArguments());
      String[] commandLine = {cmd.getExecutable(), "-V", vmsFile.getPath()};
      return 0 == executeExternalCompile(commandLine, firstFileName, true);

    } catch (IOException e) {
      throw new BuildException("Failed to create a temporary file for \"-V\" switch");
    } finally {
      FileUtils.delete(vmsFile);
    }
  }
 static {
   FILE_UTILS = FileUtils.getFileUtils();
   AntClassLoader.pathMap = Collections.synchronizedMap(new HashMap<String, String>());
   AntClassLoader.subClassToLoad = null;
   CONSTRUCTOR_ARGS = new Class[] {ClassLoader.class, Project.class, Path.class, Boolean.TYPE};
   if (JavaEnvUtils.isAtLeastJavaVersion("1.5")) {
     try {
       AntClassLoader.subClassToLoad =
           Class.forName("org.apache.tools.ant.loader.AntClassLoader5");
     } catch (ClassNotFoundException ex) {
     }
   }
 }
Exemplo n.º 20
0
  /** Do the unbzipping. */
  protected void extract() {
    if (source.lastModified() > dest.lastModified()) {
      log("Expanding " + source.getAbsolutePath() + " to " + dest.getAbsolutePath());

      FileOutputStream out = null;
      CBZip2InputStream zIn = null;
      InputStream fis = null;
      BufferedInputStream bis = null;
      try {
        out = new FileOutputStream(dest);
        fis = srcResource.getInputStream();
        bis = new BufferedInputStream(fis);
        int b = bis.read();
        if (b != 'B') {
          throw new BuildException("Invalid bz2 file.", getLocation());
        }
        b = bis.read();
        if (b != 'Z') {
          throw new BuildException("Invalid bz2 file.", getLocation());
        }
        zIn = new CBZip2InputStream(bis, true);
        byte[] buffer = new byte[BUFFER_SIZE];
        int count = 0;
        do {
          out.write(buffer, 0, count);
          count = zIn.read(buffer, 0, buffer.length);
        } while (count != -1);
      } catch (IOException ioe) {
        String msg = "Problem expanding bzip2 " + ioe.getMessage();
        throw new BuildException(msg, ioe, getLocation());
      } finally {
        FileUtils.close(bis);
        FileUtils.close(fis);
        FileUtils.close(out);
        FileUtils.close(zIn);
      }
    }
  }
Exemplo n.º 21
0
  /**
   * Returns properties from a specified properties file.
   *
   * @param fileName The file to load properties from.
   */
  private Properties getProperties(Resource r) {
    InputStream in = null;
    Properties props = new Properties();
    try {
      in = r.getInputStream();
      props.load(in);
    } catch (IOException ioe) {
      ioe.printStackTrace();
    } finally {
      FileUtils.close(in);
    }

    return props;
  }
Exemplo n.º 22
0
  public List<String> getKeyRings() throws IOException {
    List<String> keys = new ArrayList<String>();
    for (Resource resource : keyrings) {
      log("Include keyring: " + resource.getName());
      String key =
          FileUtils.readFully(
              new InputStreamReader(resource.getInputStream(), StandardCharsets.US_ASCII));
      if (key != null) {
        keys.add(key);
      }
    }

    return keys;
  }
    /**
     * Resolves file: URIs relative to the build file.
     *
     * @param publicId The public identifier, or <code>null</code> if none is available. Ignored in
     *     this implementation.
     * @param systemId The system identifier provided in the XML document. Will not be <code>null
     *     </code>.
     * @return an inputsource for this identifier
     */
    public InputSource resolveEntity(String publicId, String systemId) {

      context.getProject().log("resolving systemId: " + systemId, Project.MSG_VERBOSE);

      if (systemId.startsWith("file:")) {
        String path = FILE_UTILS.fromURI(systemId);

        File file = new File(path);
        if (!file.isAbsolute()) {
          file = FILE_UTILS.resolveFile(context.getBuildFileParent(), path);
          context
              .getProject()
              .log(
                  "Warning: '"
                      + systemId
                      + "' in "
                      + context.getBuildFile()
                      + " should be expressed simply as '"
                      + path.replace('\\', '/')
                      + "' for compliance with other XML tools",
                  Project.MSG_WARN);
        }
        context.getProject().log("file=" + file, Project.MSG_DEBUG);
        try {
          InputSource inputSource = new InputSource(new FileInputStream(file));
          inputSource.setSystemId(FILE_UTILS.toURI(file.getAbsolutePath()));
          return inputSource;
        } catch (FileNotFoundException fne) {
          context
              .getProject()
              .log(file.getAbsolutePath() + " could not be found", Project.MSG_WARN);
        }
      }
      // use default if not file or file not found
      context.getProject().log("could not resolve systemId", Project.MSG_DEBUG);
      return null;
    }
Exemplo n.º 24
0
  /**
   * Move the generated source file(s) to the base directory
   *
   * @throws org.apache.tools.ant.BuildException When error copying/removing files.
   */
  private void moveGeneratedFile(
      File baseDir, File sourceBaseFile, String classname, RmicAdapter adapter)
      throws BuildException {
    String classFileName = classname.replace('.', File.separatorChar) + ".class";
    String[] generatedFiles = adapter.getMapper().mapFileName(classFileName);

    for (int i = 0; i < generatedFiles.length; i++) {
      final String generatedFile = generatedFiles[i];
      if (!generatedFile.endsWith(".class")) {
        // don't know how to handle that - a IDL file doesn't
        // have a corresponding Java source for example.
        continue;
      }
      String sourceFileName = StringUtils.removeSuffix(generatedFile, ".class") + ".java";

      File oldFile = new File(baseDir, sourceFileName);
      if (!oldFile.exists()) {
        // no source file generated, nothing to move
        continue;
      }

      File newFile = new File(sourceBaseFile, sourceFileName);
      try {
        if (filtering) {
          FILE_UTILS.copyFile(
              oldFile, newFile, new FilterSetCollection(getProject().getGlobalFilterSet()));
        } else {
          FILE_UTILS.copyFile(oldFile, newFile);
        }
        oldFile.delete();
      } catch (IOException ioe) {
        String msg = "Failed to copy " + oldFile + " to " + newFile + " due to " + ioe.getMessage();
        throw new BuildException(msg, ioe, getLocation());
      }
    }
  }
Exemplo n.º 25
0
 /**
  * Implementation of ResourceSelector.isSelected().
  *
  * @param resource The resource to check
  * @return whether the resource is selected
  * @see ResourceSelector#isSelected(Resource)
  */
 public boolean isSelected(Resource resource) {
   if (resource.isFilesystemOnly()) {
     // We have a 'resourced' file, so reconvert it and use
     // the 'old' implementation.
     FileResource fileResource = (FileResource) resource;
     File file = fileResource.getFile();
     String filename = fileResource.getName();
     File basedir = fileResource.getBaseDir();
     return isSelected(basedir, filename, file);
   } else {
     try {
       // How to handle non-file-Resources? I copy temporarily the
       // resource to a file and use the file-implementation.
       FileUtils fu = FileUtils.getFileUtils();
       File tmpFile = fu.createTempFile("modified-", ".tmp", null, true, false);
       Resource tmpResource = new FileResource(tmpFile);
       ResourceUtils.copyResource(resource, tmpResource);
       boolean isSelected =
           isSelected(tmpFile.getParentFile(), tmpFile.getName(), resource.toLongString());
       tmpFile.delete();
       return isSelected;
     } catch (UnsupportedOperationException uoe) {
       log(
           "The resource '"
               + resource.getName()
               + "' does not provide an InputStream, so it is not checked. "
               + "Akkording to 'selres' attribute value it is "
               + ((selectResourcesWithoutInputStream) ? "" : " not")
               + "selected.",
           Project.MSG_INFO);
       return selectResourcesWithoutInputStream;
     } catch (Exception e) {
       throw new BuildException(e);
     }
   }
 }
Exemplo n.º 26
0
  @Override
  public void execute() {
    final Project proj = getProject();
    this.projectName = proj.getName();

    if (template == null) {
      throw new BuildException("template must be set");
    }
    if (title == null) {
      title = "";
    }
    if (description == null) {
      description = "";
    }

    if (filesets.isEmpty() && fromFile == null && toFile == null) {
      throw new BuildException("Need to specify tofile and fromfile or give a fileset");
    }

    if (filesets.isEmpty()) {
      // log("Project base is: " + getProject().getBaseDir());
      // log("Attempting to transform: " + fromFile);
      if (!FileUtils.isAbsolutePath(fromFile)) {
        fromFile = getProject().getBaseDir() + File.separator + fromFile;
      }
      transform(fromFile, toFile.toString());
    } else {
      if (fromFile != null) {
        throw new BuildException("Can not specify fromfile when using filesets");
      }
      if (toFile != null) {
        throw new BuildException("Can not specify tofile when using filesets");
      }

      for (final Object element : filesets) {
        final FileSet fs = (FileSet) element;
        final DirectoryScanner ds = fs.getDirectoryScanner(getProject());
        final String[] files = ds.getIncludedFiles();

        for (final String file : files) {
          transform(new File(fs.getDir(getProject()), file).getAbsolutePath(), file);
        }
      }
    }
  }
  /**
   * Fills the file and directory maps with resources read from the archive.
   *
   * @param src the archive to scan.
   * @param encoding encoding used to encode file names inside the archive.
   * @param fileEntries Map (name to resource) of non-directory resources found inside the archive.
   * @param matchFileEntries Map (name to resource) of non-directory resources found inside the
   *     archive that matched all include patterns and didn't match any exclude patterns.
   * @param dirEntries Map (name to resource) of directory resources found inside the archive.
   * @param matchDirEntries Map (name to resource) of directory resources found inside the archive
   *     that matched all include patterns and didn't match any exclude patterns.
   */
  protected void fillMapsFromArchive(
      Resource src,
      String encoding,
      Map fileEntries,
      Map matchFileEntries,
      Map dirEntries,
      Map matchDirEntries) {
    ArchiveEntry entry = null;
    ArchiveInputStream ai = null;

    try {
      try {
        ai = StreamHelper.getInputStream(factory, src, encoding);
        if (ai == null) {
          ai = factory.getArchiveStream(new BufferedInputStream(src.getInputStream()), encoding);
        }
      } catch (IOException ex) {
        throw new BuildException("problem opening " + src, ex);
      }
      while ((entry = ai.getNextEntry()) != null) {
        if (skipUnreadable && !ai.canReadEntryData(entry)) {
          log(Messages.skippedIsUnreadable(entry));
          continue;
        }
        Resource r = builder.buildResource(src, encoding, entry);
        String name = entry.getName();
        if (entry.isDirectory()) {
          name = trimSeparator(name);
          dirEntries.put(name, r);
          if (match(name)) {
            matchDirEntries.put(name, r);
          }
        } else {
          fileEntries.put(name, r);
          if (match(name)) {
            matchFileEntries.put(name, r);
          }
        }
      }
    } catch (IOException ex) {
      throw new BuildException("problem reading " + src, ex);
    } finally {
      FileUtils.close(ai);
    }
  }
 public void testspawn() {
   project.executeTarget("init");
   if (project.getProperty("test.can.run") == null) {
     return;
   }
   myBuild = new MonitoredBuild(new File(System.getProperty("root"), BUILD_FILE), "spawn");
   logFile = FILE_UTILS.createTempFile("spawn", "log", project.getBaseDir(), false, false);
   // this is guaranteed by FileUtils#createTempFile
   assertTrue("log file not existing", !logFile.exists());
   // make the spawned process run 4 seconds
   myBuild.setTimeToWait(TIME_TO_WAIT);
   myBuild.setLogFile(logFile.getAbsolutePath());
   myBuild.addBuildListener(new MonitoredBuildListener());
   myBuild.start();
   GregorianCalendar startwait = new GregorianCalendar();
   // this loop runs parallel to the build
   while (!buildFinished) {
     try {
       Thread.sleep(10);
     } catch (InterruptedException e) {
       System.out.println("my sleep was interrupted");
     }
     GregorianCalendar now = new GregorianCalendar();
     // security
     if (now.getTime().getTime() - startwait.getTime().getTime() > MAX_BUILD_TIME) {
       System.out.println(
           "aborting wait, too long "
               + (now.getTime().getTime() - startwait.getTime().getTime())
               + "milliseconds");
       break;
     }
   }
   // now wait until the spawned process is finished
   try {
     Thread.sleep((TIME_TO_WAIT) * 1000 + SECURITY_MARGIN);
   } catch (InterruptedException e) {
     System.out.println("my sleep was interrupted");
   }
   // time of the build in milli seconds
   long elapsed = myBuild.getTimeElapsed();
   assertTrue(
       "we waited more than the process lasted", TIME_TO_WAIT * 1000 + SECURITY_MARGIN > elapsed);
   logFile = new File(logFile.getAbsolutePath());
   assertTrue("log file found after spawn", logFile.exists());
 }
Exemplo n.º 29
0
 /** execute in a forked VM */
 private int run(String[] command) throws BuildException {
   PumpStreamHandler psh =
       new PumpStreamHandler(
           new LogOutputStream(this, Project.MSG_INFO),
           new TeeOutputStream(new LogOutputStream(this, Project.MSG_WARN), bos));
   Execute exe = new Execute(psh, null);
   exe.setAntRun(getProject());
   if (workingdir != null) {
     exe.setWorkingDirectory(workingdir);
   }
   exe.setCommandline(command);
   try {
     return exe.execute();
   } catch (IOException e) {
     throw new BuildException(e, getLocation());
   } finally {
     FileUtils.close(bos);
   }
 }
Exemplo n.º 30
0
  private File createExtractedFiles() {
    final File userExtensionsJavascriptFile;
    final File userExtensions;
    final File coreDir;

    coreDir = new File(customProfileDir, "core");
    try {
      coreDir.mkdirs();
      ResourceExtractor.extractResourcePath(SafariFileBasedLauncher.class, "/core", coreDir);
      // custom user-extensions
      userExtensions = getConfiguration().getUserExtensions();
      if (userExtensions != null) {
        userExtensionsJavascriptFile = new File(coreDir, "scripts/user-extensions.js");
        FileUtils.getFileUtils().copyFile(userExtensions, userExtensionsJavascriptFile, null, true);
      }
      return new File(coreDir, "RemoteRunner.html");
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }