Search in sources :

Example 16 with ResourceCollection

use of org.apache.tools.ant.types.ResourceCollection in project ant by apache.

the class AllButLast method getCollection.

/**
 * Take all elements except for the last <code>count</code> elements.
 * @return a Collection of Resources.
 */
@Override
protected Collection<Resource> getCollection() {
    int ct = getValidCount();
    ResourceCollection nested = getResourceCollection();
    if (ct > nested.size()) {
        return Collections.emptyList();
    }
    return nested.stream().limit((long) nested.size() - ct).collect(Collectors.toList());
}
Also used : ResourceCollection(org.apache.tools.ant.types.ResourceCollection)

Example 17 with ResourceCollection

use of org.apache.tools.ant.types.ResourceCollection in project ant by apache.

the class Zip method executeMain.

/**
 * Build the zip file.
 * This is called twice if doubleFilePass is true.
 * @throws BuildException on error
 */
public void executeMain() throws BuildException {
    checkAttributesAndElements();
    // Renamed version of original file, if it exists
    File renamedFile = null;
    addingNewFiles = true;
    processDoUpdate();
    processGroupFilesets();
    // collect filesets to pass them to getResourcesToAdd
    final List<ResourceCollection> vfss = new ArrayList<>();
    if (baseDir != null) {
        final FileSet fs = (FileSet) getImplicitFileSet().clone();
        fs.setDir(baseDir);
        vfss.add(fs);
    }
    vfss.addAll(resources);
    final ResourceCollection[] fss = vfss.toArray(new ResourceCollection[vfss.size()]);
    boolean success = false;
    try {
        // can also handle empty archives
        final ArchiveState state = getResourcesToAdd(fss, zipFile, false);
        // quick exit if the target is up to date
        if (!state.isOutOfDate()) {
            return;
        }
        final File parent = zipFile.getParentFile();
        if (parent != null && !parent.isDirectory() && !(parent.mkdirs() || parent.isDirectory())) {
            throw new BuildException("Failed to create missing parent directory for %s", zipFile);
        }
        updatedFile = true;
        if (!zipFile.exists() && state.isWithoutAnyResources()) {
            createEmptyZip(zipFile);
            return;
        }
        final Resource[][] addThem = state.getResourcesToAdd();
        if (doUpdate) {
            renamedFile = renameFile();
        }
        final String action = doUpdate ? "Updating " : "Building ";
        if (!skipWriting) {
            log(action + archiveType + ": " + zipFile.getAbsolutePath());
        }
        ZipOutputStream zOut = null;
        try {
            if (!skipWriting) {
                zOut = new ZipOutputStream(zipFile);
                zOut.setEncoding(encoding);
                zOut.setUseLanguageEncodingFlag(useLanguageEncodingFlag);
                zOut.setCreateUnicodeExtraFields(createUnicodeExtraFields.getPolicy());
                zOut.setFallbackToUTF8(fallBackToUTF8);
                zOut.setMethod(doCompress ? ZipOutputStream.DEFLATED : ZipOutputStream.STORED);
                zOut.setLevel(level);
                zOut.setUseZip64(zip64Mode.getMode());
            }
            initZipOutputStream(zOut);
            // Add the explicit resource collections to the archive.
            for (int i = 0; i < fss.length; i++) {
                if (addThem[i].length != 0) {
                    addResources(fss[i], addThem[i], zOut);
                }
            }
            if (doUpdate) {
                addingNewFiles = false;
                final ZipFileSet oldFiles = new ZipFileSet();
                oldFiles.setProject(getProject());
                oldFiles.setSrc(renamedFile);
                oldFiles.setDefaultexcludes(false);
                for (String addedFile : addedFiles) {
                    oldFiles.createExclude().setName(addedFile);
                }
                final DirectoryScanner ds = oldFiles.getDirectoryScanner(getProject());
                ((ZipScanner) ds).setEncoding(encoding);
                Stream<String> includedResourceNames = Stream.of(ds.getIncludedFiles());
                if (!doFilesonly) {
                    includedResourceNames = Stream.concat(includedResourceNames, Stream.of(ds.getIncludedDirectories()));
                }
                Resource[] r = includedResourceNames.map(ds::getResource).toArray(Resource[]::new);
                addResources(oldFiles, r, zOut);
            }
            if (zOut != null) {
                zOut.setComment(comment);
            }
            finalizeZipOutputStream(zOut);
            // temporary file
            if (doUpdate) {
                if (!renamedFile.delete()) {
                    log("Warning: unable to delete temporary file " + renamedFile.getName(), Project.MSG_WARN);
                }
            }
            success = true;
        } finally {
            // Close the output stream.
            closeZout(zOut, success);
        }
    } catch (final IOException ioe) {
        String msg = "Problem creating " + archiveType + ": " + ioe.getMessage();
        // delete a bogus ZIP file (but only if it's not the original one)
        if ((!doUpdate || renamedFile != null) && !zipFile.delete()) {
            msg += " (and the archive is probably corrupt but I could not " + "delete it)";
        }
        if (doUpdate && renamedFile != null) {
            try {
                FILE_UTILS.rename(renamedFile, zipFile);
            } catch (final IOException e) {
                msg += " (and I couldn't rename the temporary file " + renamedFile.getName() + " back)";
            }
        }
        throw new BuildException(msg, ioe, getLocation());
    } finally {
        cleanUp();
    }
}
Also used : ArchiveFileSet(org.apache.tools.ant.types.ArchiveFileSet) FileSet(org.apache.tools.ant.types.FileSet) ZipFileSet(org.apache.tools.ant.types.ZipFileSet) ArrayList(java.util.ArrayList) FileResource(org.apache.tools.ant.types.resources.FileResource) Resource(org.apache.tools.ant.types.Resource) ArchiveResource(org.apache.tools.ant.types.resources.ArchiveResource) ZipResource(org.apache.tools.ant.types.resources.ZipResource) IOException(java.io.IOException) ZipFileSet(org.apache.tools.ant.types.ZipFileSet) ZipOutputStream(org.apache.tools.zip.ZipOutputStream) DirectoryScanner(org.apache.tools.ant.DirectoryScanner) BuildException(org.apache.tools.ant.BuildException) ZipScanner(org.apache.tools.ant.types.ZipScanner) ZipFile(org.apache.tools.zip.ZipFile) File(java.io.File) ResourceCollection(org.apache.tools.ant.types.ResourceCollection)

Example 18 with ResourceCollection

use of org.apache.tools.ant.types.ResourceCollection in project ant by apache.

the class Zip method selectOutOfDateResources.

private Resource[] selectOutOfDateResources(final Resource[] initial, final FileNameMapper mapper) {
    final Resource[] rs = selectFileResources(initial);
    Resource[] result = ResourceUtils.selectOutOfDateSources(this, rs, mapper, getZipScanner(), ZIP_FILE_TIMESTAMP_GRANULARITY);
    if (!doFilesonly) {
        final Union u = new Union();
        u.addAll(Arrays.asList(selectDirectoryResources(initial)));
        final ResourceCollection rc = ResourceUtils.selectSources(this, u, mapper, getZipScanner(), MISSING_DIR_PROVIDER);
        if (!rc.isEmpty()) {
            final List<Resource> newer = new ArrayList<>();
            newer.addAll(Arrays.asList(((Union) rc).listResources()));
            newer.addAll(Arrays.asList(result));
            result = newer.toArray(result);
        }
    }
    return result;
}
Also used : FileResource(org.apache.tools.ant.types.resources.FileResource) Resource(org.apache.tools.ant.types.Resource) ArchiveResource(org.apache.tools.ant.types.resources.ArchiveResource) ZipResource(org.apache.tools.ant.types.resources.ZipResource) ArrayList(java.util.ArrayList) Union(org.apache.tools.ant.types.resources.Union) ResourceCollection(org.apache.tools.ant.types.ResourceCollection)

Example 19 with ResourceCollection

use of org.apache.tools.ant.types.ResourceCollection in project ant by apache.

the class Tar method execute.

/**
 * do the business
 * @throws BuildException on error
 */
@Override
public void execute() throws BuildException {
    if (tarFile == null) {
        throw new BuildException("tarfile attribute must be set!", getLocation());
    }
    if (tarFile.exists() && tarFile.isDirectory()) {
        throw new BuildException("tarfile is a directory!", getLocation());
    }
    if (tarFile.exists() && !tarFile.canWrite()) {
        throw new BuildException("Can not write to the specified tarfile!", getLocation());
    }
    final Vector<TarFileSet> savedFileSets = new Vector<>(filesets);
    try {
        if (baseDir != null) {
            if (!baseDir.exists()) {
                throw new BuildException("basedir does not exist!", getLocation());
            }
            // add the main fileset to the list of filesets to process.
            final TarFileSet mainFileSet = new TarFileSet(fileset);
            mainFileSet.setDir(baseDir);
            filesets.addElement(mainFileSet);
        }
        if (filesets.isEmpty() && resourceCollections.isEmpty()) {
            throw new BuildException("You must supply either a basedir attribute or some nested resource collections.", getLocation());
        }
        // check if tar is out of date with respect to each
        // fileset
        boolean upToDate = true;
        for (final TarFileSet tfs : filesets) {
            upToDate &= check(tfs);
        }
        for (final ResourceCollection rcol : resourceCollections) {
            upToDate &= check(rcol);
        }
        if (upToDate) {
            log("Nothing to do: " + tarFile.getAbsolutePath() + " is up to date.", Project.MSG_INFO);
            return;
        }
        final File parent = tarFile.getParentFile();
        if (parent != null && !parent.isDirectory() && !(parent.mkdirs() || parent.isDirectory())) {
            throw new BuildException("Failed to create missing parent directory for %s", tarFile);
        }
        log("Building tar: " + tarFile.getAbsolutePath(), Project.MSG_INFO);
        try (TarOutputStream tOut = new TarOutputStream(compression.compress(new BufferedOutputStream(Files.newOutputStream(tarFile.toPath()))), encoding)) {
            tOut.setDebug(true);
            if (longFileMode.isTruncateMode()) {
                tOut.setLongFileMode(TarOutputStream.LONGFILE_TRUNCATE);
            } else if (longFileMode.isFailMode() || longFileMode.isOmitMode()) {
                tOut.setLongFileMode(TarOutputStream.LONGFILE_ERROR);
            } else if (longFileMode.isPosixMode()) {
                tOut.setLongFileMode(TarOutputStream.LONGFILE_POSIX);
            } else {
                // warn or GNU
                tOut.setLongFileMode(TarOutputStream.LONGFILE_GNU);
            }
            longWarningGiven = false;
            for (final TarFileSet tfs : filesets) {
                tar(tfs, tOut);
            }
            for (final ResourceCollection rcol : resourceCollections) {
                tar(rcol, tOut);
            }
        } catch (final IOException ioe) {
            final String msg = "Problem creating TAR: " + ioe.getMessage();
            throw new BuildException(msg, ioe, getLocation());
        }
    } finally {
        filesets = savedFileSets;
    }
}
Also used : TarOutputStream(org.apache.tools.tar.TarOutputStream) BuildException(org.apache.tools.ant.BuildException) IOException(java.io.IOException) Vector(java.util.Vector) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream) ResourceCollection(org.apache.tools.ant.types.ResourceCollection)

Example 20 with ResourceCollection

use of org.apache.tools.ant.types.ResourceCollection in project ant by apache.

the class ZipExtraFieldTest method testExtraField.

private void testExtraField(Zip testInstance, boolean expectZip64) throws IOException {
    File f = File.createTempFile("ziptest", ".zip");
    f.delete();
    ZipFile zf = null;
    try {
        testInstance.setDestFile(f);
        final ZipResource r = new ZipResource() {

            public String getName() {
                return "x";
            }

            public boolean isExists() {
                return true;
            }

            public boolean isDirectory() {
                return false;
            }

            public long getLastModified() {
                return 1;
            }

            public InputStream getInputStream() {
                return new ByteArrayInputStream(new byte[0]);
            }

            public ZipExtraField[] getExtraFields() {
                return new ZipExtraField[] { new JarMarker() };
            }
        };
        testInstance.add(new ResourceCollection() {

            public boolean isFilesystemOnly() {
                return false;
            }

            public int size() {
                return 1;
            }

            public Iterator<Resource> iterator() {
                return Collections.<Resource>singleton(r).iterator();
            }
        });
        testInstance.execute();
        zf = new ZipFile(f);
        ZipEntry ze = zf.getEntry("x");
        assertNotNull(ze);
        assertEquals(expectZip64 ? 2 : 1, ze.getExtraFields().length);
        assertTrue(ze.getExtraFields()[0] instanceof JarMarker);
        if (expectZip64) {
            assertTrue(ze.getExtraFields()[1] instanceof Zip64ExtendedInformationExtraField);
        }
    } finally {
        ZipFile.closeQuietly(zf);
        if (f.exists()) {
            f.delete();
        }
    }
}
Also used : ZipExtraField(org.apache.tools.zip.ZipExtraField) ZipResource(org.apache.tools.ant.types.resources.ZipResource) ZipFile(org.apache.tools.zip.ZipFile) JarMarker(org.apache.tools.zip.JarMarker) ByteArrayInputStream(java.io.ByteArrayInputStream) ZipEntry(org.apache.tools.zip.ZipEntry) Iterator(java.util.Iterator) Resource(org.apache.tools.ant.types.Resource) ZipResource(org.apache.tools.ant.types.resources.ZipResource) ZipFile(org.apache.tools.zip.ZipFile) File(java.io.File) ResourceCollection(org.apache.tools.ant.types.ResourceCollection) Zip64ExtendedInformationExtraField(org.apache.tools.zip.Zip64ExtendedInformationExtraField)

Aggregations

ResourceCollection (org.apache.tools.ant.types.ResourceCollection)21 Resource (org.apache.tools.ant.types.Resource)16 BuildException (org.apache.tools.ant.BuildException)15 ArrayList (java.util.ArrayList)9 FileResource (org.apache.tools.ant.types.resources.FileResource)8 File (java.io.File)7 IOException (java.io.IOException)6 FileSet (org.apache.tools.ant.types.FileSet)6 FileProvider (org.apache.tools.ant.types.resources.FileProvider)5 DirectoryScanner (org.apache.tools.ant.DirectoryScanner)4 ZipResource (org.apache.tools.ant.types.resources.ZipResource)4 ArchiveResource (org.apache.tools.ant.types.resources.ArchiveResource)3 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 List (java.util.List)2 Union (org.apache.tools.ant.types.resources.Union)2 ZipFile (org.apache.tools.zip.ZipFile)2 OverrideOnDemand (com.helger.commons.annotation.OverrideOnDemand)1 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)1 CommonsHashMap (com.helger.commons.collection.impl.CommonsHashMap)1