Exemplo n.º 1
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.º 2
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());
 }
 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.º 4
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.º 5
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.º 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());
      }
    }
  }
Exemplo n.º 7
0
  /**
   * Perform the replacement on a file
   *
   * @param f the file to perform the relacement on
   * @param options the regular expressions options
   * @exception IOException if an error occurs
   */
  protected void doReplace(File f, int options) throws IOException {
    File temp = fileUtils.createTempFile("replace", ".txt", null);
    temp.deleteOnExit();

    Reader r = null;
    Writer w = null;

    try {
      if (encoding == null) {
        r = new FileReader(f);
        w = new FileWriter(temp);
      } else {
        r = new InputStreamReader(new FileInputStream(f), encoding);
        w = new OutputStreamWriter(new FileOutputStream(temp), encoding);
      }

      BufferedReader br = new BufferedReader(r);
      BufferedWriter bw = new BufferedWriter(w);
      PrintWriter pw = new PrintWriter(bw);

      boolean changes = false;

      log(
          "Replacing pattern '"
              + regex.getPattern(getProject())
              + "' with '"
              + subs.getExpression(getProject())
              + "' in '"
              + f.getPath()
              + "'"
              + (byline ? " by line" : "")
              + (flags.length() > 0 ? " with flags: '" + flags + "'" : "")
              + ".",
          Project.MSG_VERBOSE);

      if (byline) {
        StringBuffer linebuf = new StringBuffer();
        String line = null;
        String res = null;
        int c;
        boolean hasCR = false;

        do {
          c = br.read();

          if (c == '\r') {
            if (hasCR) {
              // second CR -> EOL + possibly empty line
              line = linebuf.toString();
              res = doReplace(regex, subs, line, options);

              if (!res.equals(line)) {
                changes = true;
              }

              pw.print(res);
              pw.print('\r');

              linebuf = new StringBuffer();
              // hasCR is still true (for the second one)
            } else {
              // first CR in this line
              hasCR = true;
            }
          } else if (c == '\n') {
            // LF -> EOL
            line = linebuf.toString();
            res = doReplace(regex, subs, line, options);

            if (!res.equals(line)) {
              changes = true;
            }

            pw.print(res);
            if (hasCR) {
              pw.print('\r');
              hasCR = false;
            }
            pw.print('\n');

            linebuf = new StringBuffer();
          } else { // any other char
            if ((hasCR) || (c < 0)) {
              // Mac-style linebreak or EOF (or both)
              line = linebuf.toString();
              res = doReplace(regex, subs, line, options);

              if (!res.equals(line)) {
                changes = true;
              }

              pw.print(res);
              if (hasCR) {
                pw.print('\r');
                hasCR = false;
              }

              linebuf = new StringBuffer();
            }

            if (c >= 0) {
              linebuf.append((char) c);
            }
          }
        } while (c >= 0);

        pw.flush();
      } else {
        String buf = fileUtils.readFully(br);
        if (buf == null) {
          buf = "";
        }

        String res = doReplace(regex, subs, buf, options);

        if (!res.equals(buf)) {
          changes = true;
        }

        pw.print(res);
        pw.flush();
      }

      r.close();
      r = null;
      w.close();
      w = null;

      if (changes) {
        log("File has changed; saving the updated file", Project.MSG_VERBOSE);
        try {
          fileUtils.rename(temp, f);
          temp = null;
        } catch (IOException e) {
          throw new BuildException("Couldn't rename temporary file " + temp, getLocation());
        }
      } else {
        log("No change made", Project.MSG_DEBUG);
      }
    } finally {
      try {
        if (r != null) {
          r.close();
        }
      } catch (Exception e) {
        // ignore any secondary exceptions
      }

      try {
        if (w != null) {
          w.close();
        }
      } catch (Exception e) {
        // ignore any secondary exceptions
      }
      if (temp != null) {
        temp.delete();
      }
    }
  }