Example #1
0
  /**
   * Binary compares the contents of two Resources.
   *
   * <p>simple but sub-optimal comparision algorithm. written for working rather than fast. Better
   * would be a block read into buffers followed by long comparisions apart from the final 1-7
   * bytes.
   *
   * @param r1 the Resource whose content is to be compared.
   * @param r2 the other Resource whose content is to be compared.
   * @return a negative integer, zero, or a positive integer as the first argument is less than,
   *     equal to, or greater than the second.
   * @throws IOException if the Resources cannot be read.
   * @since Ant 1.7
   */
  private static int binaryCompare(Resource r1, Resource r2) throws IOException {
    InputStream in1 = null;
    InputStream in2 = null;
    try {
      in1 = new BufferedInputStream(r1.getInputStream());
      in2 = new BufferedInputStream(r2.getInputStream());

      for (int b1 = in1.read(); b1 != -1; b1 = in1.read()) {
        int b2 = in2.read();
        if (b1 != b2) {
          return b1 > b2 ? 1 : -1;
        }
      }
      return in2.read() == -1 ? 0 : -1;
    } finally {
      FileUtils.close(in1);
      FileUtils.close(in2);
    }
  }
Example #2
0
 /**
  * Add a resource to the source list.
  *
  * @since Ant 1.7.1
  * @param sourceResource the resource to load
  * @throws BuildException if the resource cannot be read
  */
 public void loadResource(Resource sourceResource) {
   String name = sourceResource.toLongString();
   InputStream in = null;
   try {
     in = sourceResource.getInputStream();
   } catch (IOException e) {
     throw new BuildException("Failed to open " + name, e);
   } catch (UnsupportedOperationException e) {
     throw new BuildException("Failed to open " + name + " -it is not readable", e);
   }
   readSource(new InputStreamReader(in), name);
 }
Example #3
0
  /**
   * Text compares the contents of two Resources. Ignores different kinds of line endings.
   *
   * @param r1 the Resource whose content is to be compared.
   * @param r2 the other Resource whose content is to be compared.
   * @return a negative integer, zero, or a positive integer as the first argument is less than,
   *     equal to, or greater than the second.
   * @throws IOException if the Resources cannot be read.
   * @since Ant 1.7
   */
  private static int textCompare(Resource r1, Resource r2) throws IOException {
    BufferedReader in1 = null;
    BufferedReader in2 = null;
    try {
      in1 = new BufferedReader(new InputStreamReader(r1.getInputStream()));
      in2 = new BufferedReader(new InputStreamReader(r2.getInputStream()));

      String expected = in1.readLine();
      while (expected != null) {
        String actual = in2.readLine();
        if (!expected.equals(actual)) {
          return expected.compareTo(actual);
        }
        expected = in1.readLine();
      }
      return in2.readLine() == null ? 0 : -1;
    } finally {
      FileUtils.close(in1);
      FileUtils.close(in2);
    }
  }
Example #4
0
  protected void analyzeClass(Resource res) throws BuildException {
    log("Analyze class file " + res, Project.MSG_VERBOSE);

    try {
      asmAnalyser.analyseClass(res.getInputStream(), res.toString());
    } catch (final BuildException be) {
      throw be;
    } catch (final Exception e) {
      e.printStackTrace();
      throw new BuildException(
          "Failed to analyze class-file " + res + ", exception=" + e, getLocation());
    }
  }
  /**
   * 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);
    }
  }
Example #6
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;
  }
Example #7
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;
  }
  /**
   * Tests a regular expression against each line of text in a Resource.
   *
   * @param r the Resource to check.
   * @return whether the Resource is selected or not
   */
  public boolean isSelected(Resource r) {
    String teststr = null;
    BufferedReader in = null;

    // throw BuildException on error

    validate();

    if (r.isDirectory()) {
      return true;
    }

    if (myRegExp == null) {
      myRegExp = new RegularExpression();
      myRegExp.setPattern(userProvidedExpression);
      myExpression = myRegExp.getRegexp(getProject());
    }

    try {
      in = new BufferedReader(new InputStreamReader(r.getInputStream()));
    } catch (Exception e) {
      throw new BuildException("Could not get InputStream from " + r.toLongString(), e);
    }
    try {
      teststr = in.readLine();

      while (teststr != null) {

        if (myExpression.matches(
            teststr, RegexpUtil.asOptions(caseSensitive, multiLine, singleLine))) {
          return true;
        }
        teststr = in.readLine();
      }

      return false;
    } catch (IOException ioe) {
      throw new BuildException("Could not read " + r.toLongString());
    } finally {
      try {
        in.close();
      } catch (Exception e) {
        throw new BuildException("Could not close " + r.toLongString());
      }
    }
  }
  /**
   * 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);
    }
  }
Example #10
0
  protected void analyzeJar(Resource res) throws BuildException {
    log("Analyze jar file " + res, Project.MSG_VERBOSE);

    try {
      final JarInputStream jarStream = new JarInputStream(res.getInputStream());

      ZipEntry ze = jarStream.getNextEntry();
      while (null != ze) {
        final String fileName = ze.getName();
        if (fileName.endsWith(".class")) {
          log("Analyze jar class file " + fileName, Project.MSG_VERBOSE);
          asmAnalyser.analyseClass(jarStream, fileName);
        }
        ze = jarStream.getNextEntry();
      }
    } catch (final Exception e) {
      e.printStackTrace();
      throw new BuildException(
          "Failed to analyze class-file " + res + ", exception=" + e, getLocation());
    }
  }
  private void doExecute() throws BuildException {
    for (AddUser userAdder : users) {
      userAdder.execute();
    }

    final ExternalHostSystem host =
        new ExternalHostSystem(SUPPORTED_FEATURES, getHost(), getPort(), this, getShabang(), null);
    final ProtocolSessionBuilder builder = new ProtocolSessionBuilder();

    if (scripts == null) {
      scripts = new Union();
      scripts.add(new FileResource(script));
    }

    for (Iterator<?> it = scripts.iterator(); it.hasNext(); ) {
      final Resource resource = (Resource) it.next();
      try {
        final Runner runner = new Runner();

        try {

          final InputStream inputStream = resource.getInputStream();
          final String name = resource.getName();
          builder.addProtocolLines(
              name == null ? "[Unknown]" : name, inputStream, runner.getTestElements());
          runner.runSessions(host);

        } catch (UnsupportedOperationException e) {
          log("Resource cannot be read: " + resource.getName(), Project.MSG_WARN);
        }
      } catch (IOException e) {
        throw new BuildException("Cannot load script " + resource.getName(), e);
      } catch (Exception e) {
        log(e.getMessage(), Project.MSG_ERR);
        throw new BuildException(
            "[FAILURE] in script " + resource.getName() + "\n" + e.getMessage(), e);
      }
    }
  }
Example #12
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);
      }
    }
  }
Example #13
0
  public List<Map<String, Object>> getPackages() throws IOException {
    List<Map<String, Object>> packages = new ArrayList<Map<String, Object>>();

    for (SPK spk : spks) {
      log("Include SPK: " + spk.file.getName());

      // make sure file is cached locally
      if (spk.url != null) {
        log("Using " + spk.url);
        if (!spk.file.exists()) {
          spk.file.getParentFile().mkdirs();
        }
        if (spk.url == null) {
          spk.url = spk.url;
        }
        Get get = new Get();
        get.bindToOwner(this);
        get.setQuiet(true);
        get.setUseTimestamp(true);
        get.setSrc(spk.url);
        get.setDest(spk.file);
        get.execute();
      } else {
        log("Using " + spk.file);
      }

      // import SPK INFO
      Map<String, Object> info = new LinkedHashMap<String, Object>();

      TarFileSet tar = new TarFileSet();
      tar.setProject(getProject());
      tar.setSrc(spk.file);
      tar.setIncludes(INFO);
      for (Resource resource : tar) {
        if (INFO.equals(resource.getName())) {
          String text =
              FileUtils.readFully(
                  new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8));
          for (String line : text.split("\\R")) {
            String[] s = line.split("=", 2);
            if (s.length == 2) {
              if (s[1].startsWith("\"") && s[1].endsWith("\"")) {
                s[1] = s[1].substring(1, s[1].length() - 1);
              }
              importSpkInfo(info, s[0], s[1]);
            }
          }
        }
      }
      log(String.format("Imported %d fields from SPK: %s", info.size(), info.keySet()));

      // add thumbnails and snapshots
      if (spk.thumbnail.size() > 0) {
        info.put(THUMBNAIL, spk.thumbnail.toArray(new String[0]));
      }
      if (spk.snapshot.size() > 0) {
        info.put(SNAPSHOT, spk.snapshot.toArray(new String[0]));
      }

      // add user-defined fields
      info.putAll(spk.infoList);

      // automatically generate file size and checksum fields
      if (!info.containsKey(LINK)) {
        info.put(LINK, spk.url);
      }
      info.put(MD5, md5(spk.file));
      info.put(SIZE, spk.file.length());

      packages.add(info);
    }

    return packages;
  }
Example #14
0
  /**
   * Convenience method to copy content from one Resource to another specifying whether token
   * filtering must be used, whether filter chains must be used, whether newer destination files may
   * be overwritten and whether the last modified time of <code>dest</code> file should be made
   * equal to the last modified time of <code>source</code>.
   *
   * @param source the Resource to copy from. Must not be <code>null</code>.
   * @param dest the Resource to copy to. Must not be <code>null</code>.
   * @param filters the collection of filters to apply to this copy.
   * @param filterChains filterChains to apply during the copy.
   * @param overwrite Whether or not the destination Resource should be overwritten if it already
   *     exists.
   * @param preserveLastModified Whether or not the last modified time of the destination Resource
   *     should be set to that of the source.
   * @param inputEncoding the encoding used to read the files.
   * @param outputEncoding the encoding used to write the files.
   * @param project the project instance.
   * @throws IOException if the copying fails.
   * @since Ant 1.7
   */
  public static void copyResource(
      Resource source,
      Resource dest,
      FilterSetCollection filters,
      Vector filterChains,
      boolean overwrite,
      boolean preserveLastModified,
      String inputEncoding,
      String outputEncoding,
      Project project)
      throws IOException {
    if (!overwrite) {
      long slm = source.getLastModified();
      if (dest.isExists() && slm != 0 && dest.getLastModified() > slm) {
        return;
      }
    }
    final boolean filterSetsAvailable = (filters != null && filters.hasFilters());
    final boolean filterChainsAvailable = (filterChains != null && filterChains.size() > 0);
    if (filterSetsAvailable) {
      BufferedReader in = null;
      BufferedWriter out = null;
      try {
        InputStreamReader isr = null;
        if (inputEncoding == null) {
          isr = new InputStreamReader(source.getInputStream());
        } else {
          isr = new InputStreamReader(source.getInputStream(), inputEncoding);
        }
        in = new BufferedReader(isr);
        OutputStreamWriter osw = null;
        if (outputEncoding == null) {
          osw = new OutputStreamWriter(dest.getOutputStream());
        } else {
          osw = new OutputStreamWriter(dest.getOutputStream(), outputEncoding);
        }
        out = new BufferedWriter(osw);
        if (filterChainsAvailable) {
          ChainReaderHelper crh = new ChainReaderHelper();
          crh.setBufferSize(FileUtils.BUF_SIZE);
          crh.setPrimaryReader(in);
          crh.setFilterChains(filterChains);
          crh.setProject(project);
          Reader rdr = crh.getAssembledReader();
          in = new BufferedReader(rdr);
        }
        LineTokenizer lineTokenizer = new LineTokenizer();
        lineTokenizer.setIncludeDelims(true);
        String newline = null;
        String line = lineTokenizer.getToken(in);
        while (line != null) {
          if (line.length() == 0) {
            // this should not happen, because the lines are
            // returned with the end of line delimiter
            out.newLine();
          } else {
            newline = filters.replaceTokens(line);
            out.write(newline);
          }
          line = lineTokenizer.getToken(in);
        }
      } finally {
        FileUtils.close(out);
        FileUtils.close(in);
      }
    } else if (filterChainsAvailable
        || (inputEncoding != null && !inputEncoding.equals(outputEncoding))
        || (inputEncoding == null && outputEncoding != null)) {
      BufferedReader in = null;
      BufferedWriter out = null;
      try {
        InputStreamReader isr = null;
        if (inputEncoding == null) {
          isr = new InputStreamReader(source.getInputStream());
        } else {
          isr = new InputStreamReader(source.getInputStream(), inputEncoding);
        }
        in = new BufferedReader(isr);
        OutputStreamWriter osw = null;
        if (outputEncoding == null) {
          osw = new OutputStreamWriter(dest.getOutputStream());
        } else {
          osw = new OutputStreamWriter(dest.getOutputStream(), outputEncoding);
        }
        out = new BufferedWriter(osw);
        if (filterChainsAvailable) {
          ChainReaderHelper crh = new ChainReaderHelper();
          crh.setBufferSize(FileUtils.BUF_SIZE);
          crh.setPrimaryReader(in);
          crh.setFilterChains(filterChains);
          crh.setProject(project);
          Reader rdr = crh.getAssembledReader();
          in = new BufferedReader(rdr);
        }
        char[] buffer = new char[FileUtils.BUF_SIZE];
        while (true) {
          int nRead = in.read(buffer, 0, buffer.length);
          if (nRead == -1) {
            break;
          }
          out.write(buffer, 0, nRead);
        }
      } finally {
        FileUtils.close(out);
        FileUtils.close(in);
      }
    } else {
      InputStream in = null;
      OutputStream out = null;
      try {
        in = source.getInputStream();
        out = dest.getOutputStream();

        byte[] buffer = new byte[FileUtils.BUF_SIZE];
        int count = 0;
        do {
          out.write(buffer, 0, count);
          count = in.read(buffer, 0, buffer.length);
        } while (count != -1);
      } finally {
        FileUtils.close(out);
        FileUtils.close(in);
      }
    }
    if (preserveLastModified && dest instanceof Touchable) {
      setLastModified((Touchable) dest, source.getLastModified());
    }
  }