Java Code Examples for org.apache.tools.ant.types.resources.FileResource

The following examples show how to use org.apache.tools.ant.types.resources.FileResource. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: ant-ivy   Source File: AntWorkspaceResolver.java    License: Apache License 2.0 6 votes vote down vote up
private synchronized Map<ModuleDescriptor, File> getModuleDescriptors() {
    if (md2IvyFile == null) {
        md2IvyFile = new HashMap<>();
        for (ResourceCollection resources : allResources) {
            for (Resource resource : resources) {
                File ivyFile = ((FileResource) resource).getFile();
                try {
                    ModuleDescriptor md = ModuleDescriptorParserRegistry.getInstance()
                            .parseDescriptor(getParserSettings(), ivyFile.toURI().toURL(),
                                isValidate());
                    md2IvyFile.put(md, ivyFile);
                    Message.debug("Add " + md.getModuleRevisionId().getModuleId());
                } catch (Exception ex) {
                    if (haltOnError) {
                        throw new BuildException("impossible to parse ivy file " + ivyFile
                                + " exception=" + ex, ex);
                    } else {
                        Message.warn("impossible to parse ivy file " + ivyFile
                                + " exception=" + ex.getMessage());
                    }
                }
            }
        }
    }
    return md2IvyFile;
}
 
Example 2
Source Project: netbeans   Source File: PathFileSetTest.java    License: Apache License 2.0 5 votes vote down vote up
private void executeAndCheckResults(String[] expected) throws BuildException, IOException {
    String[] output = new String[pfs.size()];
    int j = 0;
    for (Iterator it = pfs.iterator(); it.hasNext(); j++) {
        FileResource fileResource = (FileResource) it.next();
        String path = fileResource.getFile().getAbsolutePath().replace('\\', '/');
        output[j] = path;
    }
    Arrays.sort(output);
    String wd = getWorkDir().getPath().replace('\\', '/').concat("/");
    for (int i = 0; i < expected.length; i++) {
        expected[i] = wd + expected[i];
    }
    assertArrayEquals(expected, output);
}
 
Example 3
Source Project: netbeans   Source File: MakeMasterJNLP.java    License: Apache License 2.0 5 votes vote down vote up
private void generateFiles() throws IOException, BuildException {
    for (Iterator<Resource> fileIt = files.iterator(); fileIt.hasNext();) {
        FileResource fr = (FileResource) fileIt.next();
        File jar = fr.getFile();

        if (!jar.canRead()) {
            throw new BuildException("Cannot read file: " + jar);
        }
        
        try (JarFile theJar = new JarFile(jar)) {
            String codenamebase = JarWithModuleAttributes.extractCodeName(theJar.getManifest().getMainAttributes());
            if (codenamebase == null) {
                throw new BuildException("Not a NetBeans Module: " + jar);
            }
            if (codenamebase.equals("org.objectweb.asm.all")
                    && jar.getParentFile().getName().equals("core")
                    && jar.getParentFile().getParentFile().getName().startsWith("platform")) {
                continue;
            }
            {
                int slash = codenamebase.indexOf('/');
                if (slash >= 0) {
                    codenamebase = codenamebase.substring(0, slash);
                }
            }
            String dashcnb = codenamebase.replace('.', '-');
            
            File n = new File(target, dashcnb + ".ref");
            try (FileWriter w = new FileWriter(n)) {
                w.write("    <extension name='" + codenamebase + "' href='" + this.masterPrefix + dashcnb + ".jnlp' />\n");
            }
        }
    }
    
}
 
Example 4
Source Project: lucene-solr   Source File: LicenseCheckTask.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Process all JARs.
 */
private void processJars() {
  log("Starting scan.", verboseLevel);
  long start = System.currentTimeMillis();

  @SuppressWarnings("unchecked")
  Iterator<Resource> iter = (Iterator<Resource>) jarResources.iterator();
  int checked = 0;
  int errors = 0;
  while (iter.hasNext()) {
    final Resource r = iter.next();
    if (!r.isExists()) { 
      throw new BuildException("JAR resource does not exist: " + r.getName());
    }
    if (!(r instanceof FileResource)) {
      throw new BuildException("Only filesystem resource are supported: " + r.getName()
          + ", was: " + r.getClass().getName());
    }

    File jarFile = ((FileResource) r).getFile();
    if (! checkJarFile(jarFile) ) {
      errors++;
    }
    checked++;
  }

  log(String.format(Locale.ROOT, 
      "Scanned %d JAR file(s) for licenses (in %.2fs.), %d error(s).",
      checked, (System.currentTimeMillis() - start) / 1000.0, errors),
      errors > 0 ? Project.MSG_ERR : Project.MSG_INFO);
}
 
Example 5
Source Project: groovy   Source File: Groovy.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Try to build a script name for the script of the groovy task to have an helpful value in stack traces in case of exception
 *
 * @return the name to use when compiling the script
 */
private String computeScriptName() {
    if (src instanceof FileResource) {
        FileResource fr = (FileResource) src;
        return fr.getFile().getAbsolutePath();
    } else {
        String name = PREFIX;
        if (getLocation().getFileName().length() > 0)
            name += getLocation().getFileName().replaceAll("[^\\w_\\.]", "_").replaceAll("[\\.]", "_dot_");
        else
            name += SUFFIX;

        return name;
    }
}
 
Example 6
Source Project: ant-ivy   Source File: IvyResources.java    License: Apache License 2.0 5 votes vote down vote up
private Collection<Resource> resolveResources(String id) throws BuildException {
    prepareAndCheck();
    try {
        List<Resource> resources = new ArrayList<>();
        if (id != null) {
            getProject().addReference(id, this);
        }
        for (ArtifactDownloadReport adr : getArtifactReports()) {
            resources.add(new FileResource(adr.getLocalFile()));
        }
        return resources;
    } catch (Exception ex) {
        throw new BuildException("impossible to build ivy resources: " + ex, ex);
    }
}
 
Example 7
Source Project: ant-ivy   Source File: IvyResourcesTest.java    License: Apache License 2.0 5 votes vote down vote up
private List<File> asList(IvyResources ivyResources) {
    List<File> resources = new ArrayList<>();
    for (Object r : ivyResources) {
        assertTrue(r instanceof FileResource);
        resources.add(((FileResource) r).getFile());
    }
    return resources;
}
 
Example 8
Source Project: lucene-solr   Source File: LibVersionsCheckTask.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Execute the task.
 */
@Override
public void execute() throws BuildException {
  log("Starting scan.", verboseLevel);
  long start = System.currentTimeMillis();

  setupIvy();

  int numErrors = 0;
  if ( ! verifySortedCoordinatesPropertiesFile(centralizedVersionsFile)) {
    ++numErrors;
  }
  if ( ! verifySortedCoordinatesPropertiesFile(ignoreConflictsFile)) {
    ++numErrors;
  }
  collectDirectDependencies();
  if ( ! collectVersionConflictsToIgnore()) {
    ++numErrors;
  }

  int numChecked = 0;

  @SuppressWarnings("unchecked")
  Iterator<Resource> iter = (Iterator<Resource>)ivyXmlResources.iterator();
  while (iter.hasNext()) {
    final Resource resource = iter.next();
    if ( ! resource.isExists()) {
      throw new BuildException("Resource does not exist: " + resource.getName());
    }
    if ( ! (resource instanceof FileResource)) {
      throw new BuildException("Only filesystem resources are supported: " 
          + resource.getName() + ", was: " + resource.getClass().getName());
    }

    File ivyXmlFile = ((FileResource)resource).getFile();
    try {
      if ( ! checkIvyXmlFile(ivyXmlFile)) {
        ++numErrors;
      }
      if ( ! resolveTransitively(ivyXmlFile)) {
        ++numErrors;
      }
      if ( ! findLatestConflictVersions()) {
        ++numErrors;
      }
    } catch (Exception e) {
      throw new BuildException("Exception reading file " + ivyXmlFile.getPath() + " - " + e.toString(), e);
    }
    ++numChecked;
  }

  log("Checking for orphans in " + centralizedVersionsFile.getName(), verboseLevel);
  for (Map.Entry<String,Dependency> entry : directDependencies.entrySet()) {
    String coordinateKey = entry.getKey();
    if ( ! entry.getValue().directlyReferenced) {
      log("ORPHAN coordinate key '" + coordinateKey + "' in " + centralizedVersionsFile.getName()
          + " is not found in any " + IVY_XML_FILENAME + " file.",
          Project.MSG_ERR);
      ++numErrors;
    }
  }

  int numConflicts = emitConflicts();

  int messageLevel = numErrors > 0 ? Project.MSG_ERR : Project.MSG_INFO;
  log("Checked that " + centralizedVersionsFile.getName() + " and " + ignoreConflictsFile.getName()
      + " have lexically sorted '/org/name' keys and no duplicates or orphans.",
      messageLevel);
  log("Scanned " + numChecked + " " + IVY_XML_FILENAME + " files for rev=\"${/org/name}\" format.",
      messageLevel);
  log("Found " + numConflicts + " indirect dependency version conflicts.");
  log(String.format(Locale.ROOT, "Completed in %.2fs., %d error(s).",
                    (System.currentTimeMillis() - start) / 1000.0, numErrors),
      messageLevel);

  if (numConflicts > 0 || numErrors > 0) {
    throw new BuildException("Lib versions check failed. Check the logs.");
  }
}
 
Example 9
Source Project: forbidden-apis   Source File: AntTask.java    License: Apache License 2.0 4 votes vote down vote up
/** Single file with API signatures as <signaturesFile/> nested element */
public FileResource createSignaturesFile() {
  return addSignaturesResource(new FileResource());
}
 
Example 10
Source Project: tascalate-javaflow   Source File: AntRewriteTask.java    License: Apache License 2.0 4 votes vote down vote up
public void execute() throws BuildException {
    DirectoryScanner ds = fileset.getDirectoryScanner(getProject());
    String[] fileNames = ds.getIncludedFiles();
    try {
        createClasspath();

        List<URL> classPath = new ArrayList<URL>();
        for (Iterator<Resource> i = compileClasspath.iterator(); i.hasNext();) {
            FileResource resource = (FileResource)i.next();
            classPath.add( resource.getFile().toURI().toURL() );
        }

        List<URL> classPathByDir = new ArrayList<URL>(classPath);
        classPathByDir.add(srcDir.toURI().toURL());

        ResourceTransformer dirTransformer = RewritingUtils.createTransformer(
            classPathByDir.toArray(new URL[]{}),
            transformerType
        );
        try {
            for (String fileName : fileNames) {
                File source = new File(srcDir, fileName);
                File destination = new File(dstDir, fileName);
                
                if (!destination.getParentFile().exists()) {
                    log("Creating dir: " + destination.getParentFile(), Project.MSG_VERBOSE);
                    destination.getParentFile().mkdirs();
                }

                if (source.lastModified() < destination.lastModified()) {
                    log("Omitting " + source + " as " + destination + " is up to date", Project.MSG_VERBOSE);
                    continue;
                }
                
                if (fileName.endsWith(".class")) {
                    log("Rewriting " + source + " to " + destination, Project.MSG_VERBOSE);
                    // System.out.println("Rewriting " + source);

                    RewritingUtils.rewriteClassFile( source, dirTransformer, destination );
                }

                if (fileName.endsWith(".jar") || 
                    fileName.endsWith(".ear") || 
                    fileName.endsWith(".zip") || 
                    fileName.endsWith(".war")) {

                    log("Rewriting " + source + " to " + destination, Project.MSG_VERBOSE);

                    List<URL> classPathByJar = new ArrayList<URL>(classPath);
                    classPathByJar.add(source.toURI().toURL());
                    
                    ResourceTransformer jarTransformer = RewritingUtils.createTransformer(
                       classPathByJar.toArray(new URL[]{}), 
                       transformerType
                    );
                    try {
                        RewritingUtils.rewriteJar(
                            new JarInputStream(new FileInputStream(source)),
                            jarTransformer,
                            new JarOutputStream(new FileOutputStream(destination))
                        );
                    } finally {
                        jarTransformer.release();
                    }
                    
                }
            }
        } finally {
            dirTransformer.release();
        }
    } catch (IOException e) {
        throw new BuildException(e);
    }
}
 
Example 11
Source Project: textuml   Source File: CompileTask.java    License: Eclipse Public License 1.0 4 votes vote down vote up
public synchronized void setFile(File file) {
	add(new FileResource(file));
}
 
Example 12
Source Project: textuml   Source File: CompileTask.java    License: Eclipse Public License 1.0 4 votes vote down vote up
public void setSrc(File src) {
	add(new FileResource(src));
}
 
Example 13
Source Project: groovy   Source File: Groovy.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Set the name of the file to be run. The folder of the file is automatically added to the classpath.
 * Required unless statements are enclosed in the build file or a nested resource is supplied.
 *
 * @param srcFile the file containing the groovy script to execute
 */
public void setSrc(final File srcFile) {
    addConfigured(new FileResource(srcFile));
}