/**
   * 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);
 }
Пример #3
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);
      }
    }
  }
Пример #4
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;
  }
  /**
   * 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);
    }
  }
Пример #6
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;
  }
Пример #7
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);
   }
 }
Пример #8
0
  private void writeJavaClass() {
    try {
      File sourceFile = new File((getLocationName() + ".java"));
      verbose("Write collector class to '" + sourceFile.getAbsolutePath() + "'");

      if (sourceFile.exists() && !sourceFile.delete()) {
        throw new IOException("could not delete " + sourceFile);
      }
      writer = new BufferedWriter(new FileWriter(sourceFile));

      createClassHeader();
      createSuiteMethod();
      createClassFooter();

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      FileUtils.close(writer);
    }
  }
Пример #9
0
  private void load(final ExecFileLoader loader) {
    final Iterator<?> resourceIterator = files.iterator();
    while (resourceIterator.hasNext()) {
      final Resource resource = (Resource) resourceIterator.next();

      if (resource.isDirectory()) {
        continue;
      }

      log(format("Loading execution data file %s", resource));

      InputStream resourceStream = null;
      try {
        resourceStream = resource.getInputStream();
        loader.load(resourceStream);
      } catch (final IOException e) {
        throw new BuildException(format("Unable to read %s", resource), e, getLocation());
      } finally {
        FileUtils.close(resourceStream);
      }
    }
  }
  /**
   * Print changelog to file specified in task.
   *
   * @param entrySet the entry set to write.
   * @throws BuildException if there is an error writing changelog.
   */
  private void writeChangeLog(final CVSEntry[] entrySet) throws BuildException {
    FileOutputStream output = null;

    try {
      output = new FileOutputStream(destFile);

      final PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"));

      final ChangeLogWriter serializer = new ChangeLogWriter();

      serializer.printChangeLog(writer, entrySet);

      if (writer.checkError()) {
        throw new IOException("Encountered an error writing changelog");
      }
    } catch (final UnsupportedEncodingException uee) {
      getProject().log(uee.toString(), Project.MSG_ERR);
    } catch (final IOException ioe) {
      throw new BuildException(ioe.toString(), ioe);
    } finally {
      FileUtils.close(output);
    }
  }
Пример #11
0
 /**
  * Close the streams belonging to the given Process.
  *
  * @param process the <code>Process</code>.
  * @throws IOException
  */
 public static void closeStreams(ChannelExec process) throws IOException {
   FileUtils.close(process.getInputStream());
   FileUtils.close(process.getOutputStream());
   FileUtils.close(process.getErrStream());
 }
  /**
   * Parses the project file, configuring the project as it goes.
   *
   * @param project the current project
   * @param source the xml source
   * @param handler the root handler to use (contains the current context)
   * @exception BuildException if the configuration is invalid or cannot be read
   */
  public void parse(Project project, Object source, RootHandler handler) throws BuildException {

    AntXMLContext context = handler.context;

    File buildFile = null;
    URL url = null;
    String buildFileName = null;

    if (source instanceof File) {
      buildFile = (File) source;
    } else if (source instanceof URL) {
      url = (URL) source;
    } else if (source instanceof Resource) {
      FileProvider fp = (FileProvider) ((Resource) source).as(FileProvider.class);
      if (fp != null) {
        buildFile = fp.getFile();
      } else {
        URLProvider up = (URLProvider) ((Resource) source).as(URLProvider.class);
        if (up != null) {
          url = up.getURL();
        }
      }
    }
    if (buildFile != null) {
      buildFile = FILE_UTILS.normalize(buildFile.getAbsolutePath());
      context.setBuildFile(buildFile);
      buildFileName = buildFile.toString();
    } else if (url != null) {
      try {
        context.setBuildFile((File) null);
        context.setBuildFile(url);
      } catch (java.net.MalformedURLException ex) {
        throw new BuildException(ex);
      }
      buildFileName = url.toString();
    } else {
      throw new BuildException(
          "Source " + source.getClass().getName() + " not supported by this plugin");
    }
    InputStream inputStream = null;
    InputSource inputSource = null;
    ZipFile zf = null;

    try {
      /** SAX 2 style parser used to parse the given file. */
      XMLReader parser = JAXPUtils.getNamespaceXMLReader();

      String uri = null;
      if (buildFile != null) {
        uri = FILE_UTILS.toURI(buildFile.getAbsolutePath());
        inputStream = new FileInputStream(buildFile);
      } else {
        uri = url.toString();
        int pling = -1;
        if (uri.startsWith("jar:file") && (pling = uri.indexOf("!/")) > -1) {
          zf = new ZipFile(org.apache.tools.ant.launch.Locator.fromJarURI(uri), "UTF-8");
          inputStream = zf.getInputStream(zf.getEntry(uri.substring(pling + 1)));
        } else {
          inputStream = url.openStream();
        }
      }

      inputSource = new InputSource(inputStream);
      if (uri != null) {
        inputSource.setSystemId(uri);
      }
      project.log(
          "parsing buildfile "
              + buildFileName
              + " with URI = "
              + uri
              + (zf != null ? " from a zip file" : ""),
          Project.MSG_VERBOSE);

      DefaultHandler hb = handler;

      parser.setContentHandler(hb);
      parser.setEntityResolver(hb);
      parser.setErrorHandler(hb);
      parser.setDTDHandler(hb);
      parser.parse(inputSource);
    } catch (SAXParseException exc) {
      Location location =
          new Location(exc.getSystemId(), exc.getLineNumber(), exc.getColumnNumber());

      Throwable t = exc.getException();
      if (t instanceof BuildException) {
        BuildException be = (BuildException) t;
        if (be.getLocation() == Location.UNKNOWN_LOCATION) {
          be.setLocation(location);
        }
        throw be;
      }
      throw new BuildException(exc.getMessage(), t == null ? exc : t, location);
    } catch (SAXException exc) {
      Throwable t = exc.getException();
      if (t instanceof BuildException) {
        throw (BuildException) t;
      }
      throw new BuildException(exc.getMessage(), t == null ? exc : t);
    } catch (FileNotFoundException exc) {
      throw new BuildException(exc);
    } catch (UnsupportedEncodingException exc) {
      throw new BuildException("Encoding of project file " + buildFileName + " is invalid.", exc);
    } catch (IOException exc) {
      throw new BuildException(
          "Error reading project file " + buildFileName + ": " + exc.getMessage(), exc);
    } finally {
      FileUtils.close(inputStream);
      ZipFile.closeQuietly(zf);
    }
  }
Пример #13
0
 /** Not used {@inheritDoc} */
 public void setOutput(OutputStream out) {
   // unused, close output file so it can be deleted before the VM exits
   if (out != System.out) {
     FileUtils.close(out);
   }
 }