Search in sources :

Example 86 with BuildException

use of org.apache.tools.ant.BuildException in project ant by apache.

the class GreedyInputHandler method handleInput.

/**
 * Prompts and requests input.
 * @param request the request to handle
 * @throws BuildException if not possible to read from console,
 *         or if input is invalid.
 */
public void handleInput(InputRequest request) throws BuildException {
    String prompt = getPrompt(request);
    InputStream in = null;
    try {
        in = getInputStream();
        System.err.println(prompt);
        System.err.flush();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        StreamPumper p = new StreamPumper(in, baos);
        Thread t = new Thread(p);
        t.start();
        try {
            t.join();
        } catch (InterruptedException e) {
            try {
                t.join();
            } catch (InterruptedException e2) {
            // Ignore
            }
        }
        request.setInput(new String(baos.toByteArray()));
        if (!request.isInputValid()) {
            throw new BuildException("Received invalid console input");
        }
        if (p.getException() != null) {
            throw new BuildException("Failed to read input from console", p.getException());
        }
    } finally {
        FileUtils.close(in);
    }
}
Also used : InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) StreamPumper(org.apache.tools.ant.taskdefs.StreamPumper) BuildException(org.apache.tools.ant.BuildException)

Example 87 with BuildException

use of org.apache.tools.ant.BuildException in project ant by apache.

the class Concat method getResources.

/**
 * Get the resources to concatenate.
 */
private ResourceCollection getResources() {
    if (rc == null) {
        return new StringResource(getProject(), textBuffer.toString());
    }
    if (dest != null) {
        Intersect checkDestNotInSources = new Intersect();
        checkDestNotInSources.setProject(getProject());
        checkDestNotInSources.add(rc);
        checkDestNotInSources.add(dest);
        if (checkDestNotInSources.size() > 0) {
            throw new BuildException("Destination resource %s was specified as an input resource.", dest);
        }
    }
    Restrict noexistRc = new Restrict();
    noexistRc.add(NOT_EXISTS);
    noexistRc.add(rc);
    for (Resource r : noexistRc) {
        log(r + " does not exist.", Project.MSG_ERR);
    }
    Restrict result = new Restrict();
    result.add(EXISTS);
    result.add(rc);
    return result;
}
Also used : StringResource(org.apache.tools.ant.types.resources.StringResource) Intersect(org.apache.tools.ant.types.resources.Intersect) Restrict(org.apache.tools.ant.types.resources.Restrict) FileResource(org.apache.tools.ant.types.resources.FileResource) LogOutputResource(org.apache.tools.ant.types.resources.LogOutputResource) Resource(org.apache.tools.ant.types.Resource) StringResource(org.apache.tools.ant.types.resources.StringResource) BuildException(org.apache.tools.ant.BuildException)

Example 88 with BuildException

use of org.apache.tools.ant.BuildException 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 89 with BuildException

use of org.apache.tools.ant.BuildException in project ant by apache.

the class Copy method doResourceOperations.

/**
 * Actually does the resource copies.
 * This is a good method for subclasses to override.
 * @param map a map of source resource to array of destination files.
 * @since Ant 1.7
 */
protected void doResourceOperations(final Map<Resource, String[]> map) {
    if (!map.isEmpty()) {
        log("Copying " + map.size() + " resource" + (map.size() == 1 ? "" : "s") + " to " + destDir.getAbsolutePath());
        for (final Map.Entry<Resource, String[]> e : map.entrySet()) {
            final Resource fromResource = e.getKey();
            for (final String toFile : e.getValue()) {
                try {
                    log("Copying " + fromResource + " to " + toFile, verbosity);
                    final FilterSetCollection executionFilters = new FilterSetCollection();
                    if (filtering) {
                        executionFilters.addFilterSet(getProject().getGlobalFilterSet());
                    }
                    for (final FilterSet filterSet : filterSets) {
                        executionFilters.addFilterSet(filterSet);
                    }
                    ResourceUtils.copyResource(fromResource, new FileResource(destDir, toFile), executionFilters, filterChains, forceOverwrite, preserveLastModified, /* append: */
                    false, inputEncoding, outputEncoding, getProject(), getForce());
                } catch (final IOException ioe) {
                    String msg = "Failed to copy " + fromResource + " to " + toFile + " due to " + getDueTo(ioe);
                    final File targetFile = new File(toFile);
                    if (!(ioe instanceof ResourceUtils.ReadOnlyTargetFileException) && targetFile.exists() && !targetFile.delete()) {
                        msg += " and I couldn't delete the corrupt " + toFile;
                    }
                    if (failonerror) {
                        throw new BuildException(msg, ioe, getLocation());
                    }
                    log(msg, Project.MSG_ERR);
                }
            }
        }
    }
}
Also used : FilterSet(org.apache.tools.ant.types.FilterSet) FilterSetCollection(org.apache.tools.ant.types.FilterSetCollection) ResourceUtils(org.apache.tools.ant.util.ResourceUtils) FileResource(org.apache.tools.ant.types.resources.FileResource) Resource(org.apache.tools.ant.types.Resource) FileResource(org.apache.tools.ant.types.resources.FileResource) IOException(java.io.IOException) BuildException(org.apache.tools.ant.BuildException) HashMap(java.util.HashMap) Map(java.util.Map) File(java.io.File)

Example 90 with BuildException

use of org.apache.tools.ant.BuildException in project ant by apache.

the class Copy method buildMap.

/**
 * Create a map of resources to copy.
 *
 * @param fromResources  The source resources.
 * @param toDir   the destination directory.
 * @param mapper  a <code>FileNameMapper</code> value.
 * @return a map of source resource to array of destination files.
 * @since Ant 1.7
 */
protected Map<Resource, String[]> buildMap(final Resource[] fromResources, final File toDir, final FileNameMapper mapper) {
    final Map<Resource, String[]> map = new HashMap<>();
    Resource[] toCopy;
    if (forceOverwrite) {
        final List<Resource> v = new ArrayList<>();
        for (Resource rc : fromResources) {
            if (mapper.mapFileName(rc.getName()) != null) {
                v.add(rc);
            }
        }
        toCopy = v.toArray(new Resource[v.size()]);
    } else {
        toCopy = ResourceUtils.selectOutOfDateSources(this, fromResources, mapper, name -> new FileResource(toDir, name), granularity);
    }
    for (Resource rc : toCopy) {
        final String[] mappedFiles = mapper.mapFileName(rc.getName());
        if (mappedFiles == null || mappedFiles.length == 0) {
            throw new BuildException("Can't copy a resource without a" + " name if the mapper doesn't" + " provide one.");
        }
        if (!enableMultipleMappings) {
            map.put(rc, new String[] { new File(toDir, mappedFiles[0]).getAbsolutePath() });
        } else {
            // reuse the array created by the mapper
            for (int k = 0; k < mappedFiles.length; k++) {
                mappedFiles[k] = new File(toDir, mappedFiles[k]).getAbsolutePath();
            }
            map.put(rc, mappedFiles);
        }
    }
    return map;
}
Also used : Mapper(org.apache.tools.ant.types.Mapper) Task(org.apache.tools.ant.Task) FilterChain(org.apache.tools.ant.types.FilterChain) FilterSetCollection(org.apache.tools.ant.types.FilterSetCollection) HashMap(java.util.HashMap) ResourceCollection(org.apache.tools.ant.types.ResourceCollection) FileNameMapper(org.apache.tools.ant.util.FileNameMapper) FileResource(org.apache.tools.ant.types.resources.FileResource) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) FilterSet(org.apache.tools.ant.types.FilterSet) SourceFileScanner(org.apache.tools.ant.util.SourceFileScanner) Vector(java.util.Vector) FileSet(org.apache.tools.ant.types.FileSet) Map(java.util.Map) Project(org.apache.tools.ant.Project) Hashtable(java.util.Hashtable) FileUtils(org.apache.tools.ant.util.FileUtils) Resource(org.apache.tools.ant.types.Resource) LinkedHashtable(org.apache.tools.ant.util.LinkedHashtable) Set(java.util.Set) IOException(java.io.IOException) BuildException(org.apache.tools.ant.BuildException) DirectoryScanner(org.apache.tools.ant.DirectoryScanner) FlatFileNameMapper(org.apache.tools.ant.util.FlatFileNameMapper) IdentityMapper(org.apache.tools.ant.util.IdentityMapper) File(java.io.File) List(java.util.List) FileProvider(org.apache.tools.ant.types.resources.FileProvider) ResourceUtils(org.apache.tools.ant.util.ResourceUtils) 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) BuildException(org.apache.tools.ant.BuildException) File(java.io.File)

Aggregations

BuildException (org.apache.tools.ant.BuildException)930 IOException (java.io.IOException)390 File (java.io.File)365 DirectoryScanner (org.apache.tools.ant.DirectoryScanner)75 ArrayList (java.util.ArrayList)65 InputStream (java.io.InputStream)62 Project (org.apache.tools.ant.Project)61 Resource (org.apache.tools.ant.types.Resource)58 FileSet (org.apache.tools.ant.types.FileSet)52 Path (org.apache.tools.ant.types.Path)52 Commandline (org.apache.tools.ant.types.Commandline)51 Properties (java.util.Properties)50 OutputStream (java.io.OutputStream)44 FileOutputStream (java.io.FileOutputStream)42 FileResource (org.apache.tools.ant.types.resources.FileResource)42 FileInputStream (java.io.FileInputStream)41 URL (java.net.URL)40 BufferedReader (java.io.BufferedReader)37 Writer (java.io.Writer)37 MalformedURLException (java.net.MalformedURLException)37