Search in sources :

Example 1 with FileProvider

use of org.apache.tools.ant.types.resources.FileProvider in project ant by apache.

the class ProjectHelper2 method parse.

/**
 * 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 = ((Resource) source).as(FileProvider.class);
        if (fp != null) {
            buildFile = fp.getFile();
        } else {
            URLProvider up = ((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 = Files.newInputStream(buildFile.toPath());
        } 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 + 2)));
            } else {
                URLConnection conn = url.openConnection();
                conn.setUseCaches(false);
                inputStream = conn.getInputStream();
            }
        }
        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);
    }
}
Also used : InputSource(org.xml.sax.InputSource) URLProvider(org.apache.tools.ant.types.resources.URLProvider) InputStream(java.io.InputStream) Resource(org.apache.tools.ant.types.Resource) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) URL(java.net.URL) ExtensionPoint(org.apache.tools.ant.ExtensionPoint) URLConnection(java.net.URLConnection) DefaultHandler(org.xml.sax.helpers.DefaultHandler) SAXException(org.xml.sax.SAXException) ZipFile(org.apache.tools.zip.ZipFile) SAXParseException(org.xml.sax.SAXParseException) FileProvider(org.apache.tools.ant.types.resources.FileProvider) BuildException(org.apache.tools.ant.BuildException) ZipFile(org.apache.tools.zip.ZipFile) File(java.io.File) XMLReader(org.xml.sax.XMLReader) Location(org.apache.tools.ant.Location)

Example 2 with FileProvider

use of org.apache.tools.ant.types.resources.FileProvider in project ant by apache.

the class Copy method execute.

/**
 * Perform the copy operation.
 * @exception BuildException if an error occurs.
 */
@Override
public void execute() throws BuildException {
    // may be altered in validateAttributes
    final File savedFile = file;
    final File savedDestFile = destFile;
    final File savedDestDir = destDir;
    ResourceCollection savedRc = null;
    if (file == null && destFile != null && rcs.size() == 1) {
        // will be removed in validateAttributes
        savedRc = rcs.elementAt(0);
    }
    try {
        // make sure we don't have an illegal set of options
        try {
            validateAttributes();
        } catch (final BuildException e) {
            if (failonerror || !getMessage(e).equals(MSG_WHEN_COPYING_EMPTY_RC_TO_FILE)) {
                throw e;
            } else {
                log("Warning: " + getMessage(e), Project.MSG_ERR);
                return;
            }
        }
        // deal with the single file
        copySingleFile();
        // deal with the ResourceCollections
        /* for historical and performance reasons we have to do
               things in a rather complex way.

               (1) Move is optimized to move directories if a fileset
               has been included completely, therefore FileSets need a
               special treatment.  This is also required to support
               the failOnError semantic (skip filesets with broken
               basedir but handle the remaining collections).

               (2) We carry around a few protected methods that work
               on basedirs and arrays of names.  To optimize stuff, all
               resources with the same basedir get collected in
               separate lists and then each list is handled in one go.
            */
        final Map<File, List<String>> filesByBasedir = new HashMap<>();
        final Map<File, List<String>> dirsByBasedir = new HashMap<>();
        final Set<File> baseDirs = new HashSet<>();
        final List<Resource> nonFileResources = new ArrayList<>();
        for (ResourceCollection rc : rcs) {
            // Step (1) - beware of the ZipFileSet
            if (rc instanceof FileSet && rc.isFilesystemOnly()) {
                final FileSet fs = (FileSet) rc;
                DirectoryScanner ds;
                try {
                    ds = fs.getDirectoryScanner(getProject());
                } catch (final BuildException e) {
                    if (failonerror || !getMessage(e).endsWith(DirectoryScanner.DOES_NOT_EXIST_POSTFIX)) {
                        throw e;
                    }
                    if (!quiet) {
                        log("Warning: " + getMessage(e), Project.MSG_ERR);
                    }
                    continue;
                }
                final File fromDir = fs.getDir(getProject());
                final String[] srcFiles = ds.getIncludedFiles();
                final String[] srcDirs = ds.getIncludedDirectories();
                if (!flatten && mapperElement == null && ds.isEverythingIncluded() && !fs.hasPatterns()) {
                    completeDirMap.put(fromDir, destDir);
                }
                add(fromDir, srcFiles, filesByBasedir);
                add(fromDir, srcDirs, dirsByBasedir);
                baseDirs.add(fromDir);
            } else {
                if (!rc.isFilesystemOnly() && !supportsNonFileResources()) {
                    throw new BuildException("Only FileSystem resources are supported.");
                }
                for (final Resource r : rc) {
                    if (!r.isExists()) {
                        final String message = "Warning: Could not find resource " + r.toLongString() + " to copy.";
                        if (!failonerror) {
                            if (!quiet) {
                                log(message, Project.MSG_ERR);
                            }
                        } else {
                            throw new BuildException(message);
                        }
                        continue;
                    }
                    File baseDir = NULL_FILE_PLACEHOLDER;
                    String name = r.getName();
                    final FileProvider fp = r.as(FileProvider.class);
                    if (fp != null) {
                        final FileResource fr = ResourceUtils.asFileResource(fp);
                        baseDir = getKeyFile(fr.getBaseDir());
                        if (fr.getBaseDir() == null) {
                            name = fr.getFile().getAbsolutePath();
                        }
                    }
                    // files.
                    if (r.isDirectory() || fp != null) {
                        add(baseDir, name, r.isDirectory() ? dirsByBasedir : filesByBasedir);
                        baseDirs.add(baseDir);
                    } else {
                        // a not-directory file resource
                        // needs special treatment
                        nonFileResources.add(r);
                    }
                }
            }
        }
        iterateOverBaseDirs(baseDirs, dirsByBasedir, filesByBasedir);
        // do all the copy operations now...
        try {
            doFileOperations();
        } catch (final BuildException e) {
            if (!failonerror) {
                if (!quiet) {
                    log("Warning: " + getMessage(e), Project.MSG_ERR);
                }
            } else {
                throw e;
            }
        }
        if (!nonFileResources.isEmpty() || singleResource != null) {
            final Resource[] nonFiles = nonFileResources.toArray(new Resource[nonFileResources.size()]);
            // restrict to out-of-date resources
            final Map<Resource, String[]> map = scan(nonFiles, destDir);
            if (singleResource != null) {
                map.put(singleResource, new String[] { destFile.getAbsolutePath() });
            }
            try {
                doResourceOperations(map);
            } catch (final BuildException e) {
                if (!failonerror) {
                    if (!quiet) {
                        log("Warning: " + getMessage(e), Project.MSG_ERR);
                    }
                } else {
                    throw e;
                }
            }
        }
    } finally {
        // clean up again, so this instance can be used a second
        // time
        singleResource = null;
        file = savedFile;
        destFile = savedDestFile;
        destDir = savedDestDir;
        if (savedRc != null) {
            rcs.insertElementAt(savedRc, 0);
        }
        fileCopyMap.clear();
        dirCopyMap.clear();
        completeDirMap.clear();
    }
}
Also used : FileSet(org.apache.tools.ant.types.FileSet) HashMap(java.util.HashMap) FileResource(org.apache.tools.ant.types.resources.FileResource) Resource(org.apache.tools.ant.types.Resource) ArrayList(java.util.ArrayList) FileResource(org.apache.tools.ant.types.resources.FileResource) DirectoryScanner(org.apache.tools.ant.DirectoryScanner) FileProvider(org.apache.tools.ant.types.resources.FileProvider) ArrayList(java.util.ArrayList) List(java.util.List) BuildException(org.apache.tools.ant.BuildException) File(java.io.File) ResourceCollection(org.apache.tools.ant.types.ResourceCollection) HashSet(java.util.HashSet)

Example 3 with FileProvider

use of org.apache.tools.ant.types.resources.FileProvider in project ant by apache.

the class XSLTProcess method processResources.

/**
 * Styles all existing resources.
 *
 * @param stylesheet style sheet to use
 * @since Ant 1.7
 */
private void processResources(final Resource stylesheet) {
    for (final Resource r : resources) {
        if (!r.isExists()) {
            continue;
        }
        File base = baseDir;
        String name = r.getName();
        final FileProvider fp = r.as(FileProvider.class);
        if (fp != null) {
            final FileResource f = ResourceUtils.asFileResource(fp);
            base = f.getBaseDir();
            if (base == null) {
                name = f.getFile().getAbsolutePath();
            }
        }
        process(base, name, destDir, stylesheet);
    }
}
Also used : FileProvider(org.apache.tools.ant.types.resources.FileProvider) FileResource(org.apache.tools.ant.types.resources.FileResource) Resource(org.apache.tools.ant.types.Resource) FileResource(org.apache.tools.ant.types.resources.FileResource) File(java.io.File)

Example 4 with FileProvider

use of org.apache.tools.ant.types.resources.FileProvider in project ant by apache.

the class VerifyJar method execute.

/**
 * verify our jar files
 * @throws BuildException on error.
 */
@Override
public void execute() throws BuildException {
    // validation logic
    final boolean hasJar = jar != null;
    if (!hasJar && !hasResources()) {
        throw new BuildException(ERROR_NO_SOURCE);
    }
    beginExecution();
    // patch the redirector to save output to a file
    RedirectorElement redirector = getRedirector();
    redirector.setAlwaysLog(true);
    FilterChain outputFilterChain = redirector.createOutputFilterChain();
    outputFilterChain.add(outputCache);
    try {
        Path sources = createUnifiedSourcePath();
        for (Resource r : sources) {
            FileProvider fr = r.as(FileProvider.class);
            verifyOneJar(fr.getFile());
        }
    } finally {
        endExecution();
    }
}
Also used : Path(org.apache.tools.ant.types.Path) RedirectorElement(org.apache.tools.ant.types.RedirectorElement) FilterChain(org.apache.tools.ant.types.FilterChain) FileProvider(org.apache.tools.ant.types.resources.FileProvider) Resource(org.apache.tools.ant.types.Resource) BuildException(org.apache.tools.ant.BuildException)

Example 5 with FileProvider

use of org.apache.tools.ant.types.resources.FileProvider in project ant by apache.

the class Scp method createDirectoryCollection.

private List<Directory> createDirectoryCollection(final ResourceCollection rc) {
    // not a fileset or contains non-file resources
    if (!rc.isFilesystemOnly()) {
        throw new BuildException("Only FileSystem resources are supported.");
    }
    List<Directory> ds = new ArrayList<>();
    for (Resource r : rc) {
        if (!r.isExists()) {
            throw new BuildException("Could not find resource %s to scp.", r.toLongString());
        }
        FileProvider fp = r.as(FileProvider.class);
        if (fp == null) {
            throw new BuildException("Resource %s is not a file.", r.toLongString());
        }
        FileResource fr = ResourceUtils.asFileResource(fp);
        File baseDir = fr.getBaseDir();
        if (baseDir == null) {
            throw new BuildException("basedir for resource %s is undefined.", r.toLongString());
        }
        // if the basedir is set, the name will be relative to that
        String name = r.getName();
        Directory root = new Directory(baseDir);
        Directory current = root;
        File currentParent = baseDir;
        for (String element : Directory.getPath(name)) {
            final File file = new File(currentParent, element);
            if (file.isDirectory()) {
                current.addDirectory(new Directory(file));
                current = current.getChild(file);
                currentParent = current.getDirectory();
            } else if (file.isFile()) {
                current.addFile(file);
            }
        }
        ds.add(root);
    }
    return ds;
}
Also used : FileProvider(org.apache.tools.ant.types.resources.FileProvider) ArrayList(java.util.ArrayList) Resource(org.apache.tools.ant.types.Resource) FileResource(org.apache.tools.ant.types.resources.FileResource) FileResource(org.apache.tools.ant.types.resources.FileResource) BuildException(org.apache.tools.ant.BuildException) File(java.io.File)

Aggregations

FileProvider (org.apache.tools.ant.types.resources.FileProvider)22 BuildException (org.apache.tools.ant.BuildException)13 Resource (org.apache.tools.ant.types.Resource)13 FileResource (org.apache.tools.ant.types.resources.FileResource)12 File (java.io.File)8 IOException (java.io.IOException)4 ArchiveResource (org.apache.tools.ant.types.resources.ArchiveResource)4 ResourceCollection (org.apache.tools.ant.types.ResourceCollection)3 URL (java.net.URL)2 Path (java.nio.file.Path)2 PosixFileAttributeView (java.nio.file.attribute.PosixFileAttributeView)2 ArrayList (java.util.ArrayList)2 Vector (java.util.Vector)2 DirectoryScanner (org.apache.tools.ant.DirectoryScanner)2 FileSet (org.apache.tools.ant.types.FileSet)2 URLProvider (org.apache.tools.ant.types.resources.URLProvider)2 ZipResource (org.apache.tools.ant.types.resources.ZipResource)2 ZipFile (org.apache.tools.zip.ZipFile)2 OverrideOnDemand (com.helger.commons.annotation.OverrideOnDemand)1 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)1