Search in sources :

Example 26 with ZipEntry

use of org.apache.tools.zip.ZipEntry in project ant by apache.

the class Zip method getUnixMode.

/**
 * Determine a Resource's Unix mode or return the given default
 * value if not available.
 */
private int getUnixMode(final Resource r, final ZipFile zf, final int defaultMode) {
    int unixMode = defaultMode;
    if (zf != null) {
        final ZipEntry ze = zf.getEntry(r.getName());
        unixMode = ze.getUnixMode();
        if ((unixMode == 0 || unixMode == UnixStat.DIR_FLAG) && !preserve0Permissions) {
            unixMode = defaultMode;
        }
    } else if (r instanceof ArchiveResource) {
        unixMode = ((ArchiveResource) r).getMode();
    }
    return unixMode;
}
Also used : ZipEntry(org.apache.tools.zip.ZipEntry) ArchiveResource(org.apache.tools.ant.types.resources.ArchiveResource)

Example 27 with ZipEntry

use of org.apache.tools.zip.ZipEntry in project ant by apache.

the class Zip method zipDir.

/**
 * Add a directory to the zip stream.
 * @param dir  the directory to add to the archive
 * @param zOut the stream to write to
 * @param vPath the name this entry shall have in the archive
 * @param mode the Unix permissions to set.
 * @param extra ZipExtraFields to add
 * @throws IOException on error
 * @since Ant 1.8.0
 */
protected void zipDir(final Resource dir, final ZipOutputStream zOut, final String vPath, final int mode, final ZipExtraField[] extra) throws IOException {
    if (doFilesonly) {
        logWhenWriting("skipping directory " + vPath + " for file-only archive", Project.MSG_VERBOSE);
        return;
    }
    if (addedDirs.get(vPath) != null) {
        // no warning if we try, it is harmless in and of itself
        return;
    }
    logWhenWriting("adding directory " + vPath, Project.MSG_VERBOSE);
    addedDirs.put(vPath, vPath);
    if (!skipWriting) {
        final ZipEntry ze = new ZipEntry(vPath);
        // ZIPs store time with a granularity of 2 seconds, round up
        final int millisToAdd = roundUp ? ROUNDUP_MILLIS : 0;
        if (fixedModTime != null) {
            ze.setTime(modTimeMillis);
        } else if (dir != null && dir.isExists()) {
            ze.setTime(dir.getLastModified() + millisToAdd);
        } else {
            ze.setTime(System.currentTimeMillis() + millisToAdd);
        }
        ze.setSize(0);
        ze.setMethod(ZipEntry.STORED);
        // This is faintly ridiculous:
        ze.setCrc(EMPTY_CRC);
        ze.setUnixMode(mode);
        if (extra != null) {
            ze.setExtraFields(extra);
        }
        zOut.putNextEntry(ze);
    }
}
Also used : ZipEntry(org.apache.tools.zip.ZipEntry)

Example 28 with ZipEntry

use of org.apache.tools.zip.ZipEntry in project ant by apache.

the class IsSigned method isSigned.

/**
 * Returns <code>true</code> if the file exists and is signed with
 * the signature specified, or, if <code>name</code> wasn't
 * specified, if the file contains a signature.
 * @param zipFile the zipfile to check
 * @param name the signature to check (may be killed)
 * @return true if the file is signed.
 * @throws IOException on error
 */
public static boolean isSigned(File zipFile, String name) throws IOException {
    try (ZipFile jarFile = new ZipFile(zipFile)) {
        if (null == name) {
            Enumeration<ZipEntry> entries = jarFile.getEntries();
            while (entries.hasMoreElements()) {
                String eName = entries.nextElement().getName();
                if (eName.startsWith(SIG_START) && eName.endsWith(SIG_END)) {
                    return true;
                }
            }
            return false;
        }
        name = replaceInvalidChars(name);
        boolean shortSig = jarFile.getEntry(SIG_START + name.toUpperCase() + SIG_END) != null;
        boolean longSig = false;
        if (name.length() > SHORT_SIG_LIMIT) {
            longSig = jarFile.getEntry(SIG_START + name.substring(0, SHORT_SIG_LIMIT).toUpperCase() + SIG_END) != null;
        }
        return shortSig || longSig;
    }
}
Also used : ZipFile(org.apache.tools.zip.ZipFile) ZipEntry(org.apache.tools.zip.ZipEntry)

Example 29 with ZipEntry

use of org.apache.tools.zip.ZipEntry 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)

Example 30 with ZipEntry

use of org.apache.tools.zip.ZipEntry in project support-core-plugin by jenkinsci.

the class SupportPlugin method writeBundle.

public static void writeBundle(OutputStream outputStream, final List<Component> components) throws IOException {
    // TODO why is this not SupportPlugin.logger?
    Logger logger = Logger.getLogger(SupportPlugin.class.getName());
    final java.util.Queue<Content> toProcess = new ConcurrentLinkedQueue<Content>();
    final Set<String> names = new TreeSet<String>();
    Container container = new Container() {

        @Override
        public void add(@CheckForNull Content content) {
            if (content != null) {
                names.add(content.getName());
                toProcess.add(content);
            }
        }
    };
    StringBuilder manifest = new StringBuilder();
    SupportPlugin plugin = SupportPlugin.getInstance();
    SupportProvider supportProvider = plugin == null ? null : plugin.getSupportProvider();
    String bundleName = (supportProvider == null ? "Support" : supportProvider.getDisplayName()) + " Bundle Manifest";
    manifest.append(bundleName).append('\n');
    manifest.append(StringUtils.repeat("=", bundleName.length())).append('\n');
    manifest.append("\n");
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ");
    f.setTimeZone(TimeZone.getTimeZone("UTC"));
    manifest.append("Generated on ").append(f.format(new Date())).append("\n");
    manifest.append("\n");
    manifest.append("Requested components:\n\n");
    StringWriter errors = new StringWriter();
    PrintWriter errorWriter = new PrintWriter(errors);
    for (Component c : components) {
        try {
            manifest.append("  * ").append(c.getDisplayName()).append("\n\n");
            names.clear();
            c.addContents(container);
            for (String name : names) {
                manifest.append("      - `").append(name).append("`\n\n");
            }
        } catch (Throwable e) {
            String cDisplayName = null;
            try {
                cDisplayName = c.getDisplayName();
            } catch (Throwable e1) {
                // be very defensive
                cDisplayName = c.getClass().getName();
            }
            LogRecord logRecord = new LogRecord(Level.WARNING, "Could not get content from ''{0}'' for support bundle");
            logRecord.setThrown(e);
            logRecord.setParameters(new Object[] { cDisplayName });
            logger.log(logRecord);
            errorWriter.println(MessageFormat.format("Could not get content from ''{0}'' for support bundle", cDisplayName));
            errorWriter.println("-----------------------------------------------------------------------");
            errorWriter.println();
            SupportLogFormatter.printStackTrace(e, errorWriter);
            errorWriter.println();
        }
    }
    toProcess.add(new StringContent("manifest.md", manifest.toString()));
    try {
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        try {
            BufferedOutputStream bos = new BufferedOutputStream(zip, 16384) {

                @Override
                public void close() throws IOException {
                    // don't let any of the contents accidentally close the zip stream
                    super.flush();
                }
            };
            while (!toProcess.isEmpty()) {
                Content c = toProcess.poll();
                if (c == null) {
                    continue;
                }
                final String name = c.getName();
                try {
                    ZipEntry entry = new ZipEntry(name);
                    entry.setTime(c.getTime());
                    zip.putNextEntry(entry);
                    c.writeTo(bos);
                } catch (Throwable e) {
                    LogRecord logRecord = new LogRecord(Level.WARNING, "Could not attach ''{0}'' to support bundle");
                    logRecord.setThrown(e);
                    logRecord.setParameters(new Object[] { name });
                    logger.log(logRecord);
                    errorWriter.println(MessageFormat.format("Could not attach ''{0}'' to support bundle", name));
                    errorWriter.println("-----------------------------------------------------------------------");
                    errorWriter.println();
                    SupportLogFormatter.printStackTrace(e, errorWriter);
                    errorWriter.println();
                } finally {
                    bos.flush();
                }
                zip.flush();
            }
            errorWriter.close();
            String errorContent = errors.toString();
            if (!StringUtils.isBlank(errorContent)) {
                try {
                    zip.putNextEntry(new ZipEntry("manifest/errors.txt"));
                    zip.write(errorContent.getBytes("utf-8"));
                } catch (IOException e) {
                // ignore
                }
                zip.flush();
            }
        } finally {
            zip.close();
        }
    } finally {
        outputStream.flush();
    }
}
Also used : ZipEntry(org.apache.tools.zip.ZipEntry) Logger(java.util.logging.Logger) Container(com.cloudbees.jenkins.support.api.Container) StringWriter(java.io.StringWriter) LogRecord(java.util.logging.LogRecord) TreeSet(java.util.TreeSet) CheckForNull(edu.umd.cs.findbugs.annotations.CheckForNull) Component(com.cloudbees.jenkins.support.api.Component) BufferedOutputStream(java.io.BufferedOutputStream) PrintWriter(java.io.PrintWriter) StringContent(com.cloudbees.jenkins.support.api.StringContent) SupportProvider(com.cloudbees.jenkins.support.api.SupportProvider) IOException(java.io.IOException) Date(java.util.Date) StringContent(com.cloudbees.jenkins.support.api.StringContent) Content(com.cloudbees.jenkins.support.api.Content) ZipOutputStream(org.apache.tools.zip.ZipOutputStream) JSONObject(net.sf.json.JSONObject) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) SimpleDateFormat(java.text.SimpleDateFormat)

Aggregations

ZipEntry (org.apache.tools.zip.ZipEntry)32 ZipFile (org.apache.tools.zip.ZipFile)17 File (java.io.File)13 FileOutputStream (java.io.FileOutputStream)9 IOException (java.io.IOException)9 FileInputStream (java.io.FileInputStream)7 BufferedInputStream (java.io.BufferedInputStream)6 InputStream (java.io.InputStream)6 BufferedOutputStream (java.io.BufferedOutputStream)5 Enumeration (java.util.Enumeration)5 ZipException (java.util.zip.ZipException)4 BuildException (org.apache.tools.ant.BuildException)4 ZipOutputStream (org.apache.tools.zip.ZipOutputStream)4 OutputStream (java.io.OutputStream)3 ZipResource (org.apache.tools.ant.types.resources.ZipResource)3 FileNotFoundException (java.io.FileNotFoundException)2 RandomAccessFile (java.io.RandomAccessFile)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 Date (java.util.Date)2 ZipOutputStream (java.util.zip.ZipOutputStream)2