Search in sources :

Example 91 with ZipException

use of java.util.zip.ZipException in project gradle by gradle.

the class DefaultClasspathEntryHasher method hashJar.

private HashCode hashJar(FileDetails fileDetails, Hasher hasher, ClasspathContentHasher classpathContentHasher) {
    File jarFilePath = new File(fileDetails.getPath());
    ZipInputStream zipInput = null;
    try {
        zipInput = new ZipInputStream(new FileInputStream(jarFilePath));
        ZipEntry zipEntry;
        Multimap<String, HashCode> entriesByName = MultimapBuilder.hashKeys().arrayListValues().build();
        while ((zipEntry = zipInput.getNextEntry()) != null) {
            if (zipEntry.isDirectory()) {
                continue;
            }
            HashCode hash = hashZipEntry(zipInput, zipEntry, classpathContentHasher);
            if (hash != null) {
                entriesByName.put(zipEntry.getName(), hash);
            }
        }
        Map<String, Collection<HashCode>> map = entriesByName.asMap();
        // Ensure we hash the zip entries in a deterministic order
        String[] keys = map.keySet().toArray(new String[0]);
        Arrays.sort(keys);
        for (String key : keys) {
            for (HashCode hash : map.get(key)) {
                hasher.putBytes(hash.asBytes());
            }
        }
        return hasher.hash();
    } catch (ZipException e) {
        // ZipExceptions point to a problem with the Zip, we try to be lenient for now.
        return hashMalformedZip(fileDetails, hasher, classpathContentHasher);
    } catch (IOException e) {
        // IOExceptions other than ZipException are failures.
        throw new UncheckedIOException("Error snapshotting jar [" + fileDetails.getName() + "]", e);
    } catch (Exception e) {
        // Other Exceptions can be thrown by invalid zips, too. See https://github.com/gradle/gradle/issues/1581.
        return hashMalformedZip(fileDetails, hasher, classpathContentHasher);
    } finally {
        IOUtils.closeQuietly(zipInput);
    }
}
Also used : ZipEntry(java.util.zip.ZipEntry) ZipException(java.util.zip.ZipException) UncheckedIOException(org.gradle.api.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(org.gradle.api.UncheckedIOException) FileInputStream(java.io.FileInputStream) ZipException(java.util.zip.ZipException) IOException(java.io.IOException) UncheckedIOException(org.gradle.api.UncheckedIOException) ZipInputStream(java.util.zip.ZipInputStream) HashCode(com.google.common.hash.HashCode) Collection(java.util.Collection) File(java.io.File)

Example 92 with ZipException

use of java.util.zip.ZipException in project bazel by bazelbuild.

the class ZipWriterTest method testFileDataBeforeEntry.

@Test
public void testFileDataBeforeEntry() throws IOException {
    try (ZipWriter writer = new ZipWriter(new FileOutputStream(test), UTF_8)) {
        writer.write(new byte[] { 0xf, 0xa, 0xb });
        fail("Expected ZipException");
    } catch (ZipException e) {
        assertThat(e.getMessage()).contains("Cannot write zip contents without first setting a" + " ZipEntry or starting a prefix file.");
    }
    try (ZipFile zipFile = new ZipFile(test)) {
        assertThat(zipFile.entries().hasMoreElements()).isFalse();
    }
}
Also used : ZipFile(java.util.zip.ZipFile) FileOutputStream(java.io.FileOutputStream) ZipException(java.util.zip.ZipException) Test(org.junit.Test)

Example 93 with ZipException

use of java.util.zip.ZipException in project bazel by bazelbuild.

the class ZipReader method readCentralDirectory.

/**
   * Finds, reads and parses ZIP file entries from the central directory.
   *
   * @param strictEntries force parsing to use the number of entries recorded in the end of
   *     central directory as the correct value, not as an estimate
   * @throws ZipException if a ZIP format error has occurred
   * @throws IOException if an I/O error has occurred
   */
private void readCentralDirectory(boolean strictEntries) throws IOException {
    long eocdLocation = findEndOfCentralDirectoryRecord();
    InputStream stream = getStreamAt(eocdLocation);
    EndOfCentralDirectoryRecord.read(stream, zipData);
    if (zipData.isMaybeZip64()) {
        try {
            stream = getStreamAt(eocdLocation - Zip64EndOfCentralDirectoryLocator.FIXED_DATA_SIZE);
            Zip64EndOfCentralDirectoryLocator.read(stream, zipData);
            stream = getStreamAt(zipData.getZip64EndOfCentralDirectoryOffset());
            Zip64EndOfCentralDirectory.read(stream, zipData);
        } catch (ZipException e) {
        // expected if not in Zip64 format
        }
    }
    if (zipData.isZip64() || strictEntries) {
        // If in Zip64 format or using strict entry numbers, use the parsed information as is to read
        // the central directory file headers.
        readCentralDirectoryFileHeaders(zipData.getExpectedEntries(), zipData.getCentralDirectoryOffset());
    } else {
        // If not in Zip64 format, compute central directory offset by end of central directory record
        // offset and central directory size to allow reading large non-compliant Zip32 directories.
        long centralDirectoryOffset = eocdLocation - zipData.getCentralDirectorySize();
        // reported offset.
        if ((int) centralDirectoryOffset == (int) zipData.getCentralDirectoryOffset()) {
            readCentralDirectoryFileHeaders(centralDirectoryOffset);
        } else {
            readCentralDirectoryFileHeaders(zipData.getExpectedEntries(), zipData.getCentralDirectoryOffset());
        }
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) ZipException(java.util.zip.ZipException)

Example 94 with ZipException

use of java.util.zip.ZipException in project jetty.project by eclipse.

the class GZIPContentDecoder method decodeChunks.

/**
     * Inflate compressed data.
     * <p>Inflation continues until the compressed block end is reached, there is no 
     * more compressed data or a call to {@link #decodedChunk(ByteBuffer)} returns true.
     * @param compressed Buffer of compressed data to inflate
     */
protected void decodeChunks(ByteBuffer compressed) {
    ByteBuffer buffer = null;
    try {
        while (true) {
            switch(_state) {
                case INITIAL:
                    {
                        _state = State.ID;
                        break;
                    }
                case FLAGS:
                    {
                        if ((_flags & 0x04) == 0x04) {
                            _state = State.EXTRA_LENGTH;
                            _size = 0;
                            _value = 0;
                        } else if ((_flags & 0x08) == 0x08)
                            _state = State.NAME;
                        else if ((_flags & 0x10) == 0x10)
                            _state = State.COMMENT;
                        else if ((_flags & 0x2) == 0x2) {
                            _state = State.HCRC;
                            _size = 0;
                            _value = 0;
                        } else {
                            _state = State.DATA;
                            continue;
                        }
                        break;
                    }
                case DATA:
                    {
                        while (true) {
                            if (buffer == null)
                                buffer = acquire(_bufferSize);
                            try {
                                int length = _inflater.inflate(buffer.array(), buffer.arrayOffset(), buffer.capacity());
                                buffer.limit(length);
                            } catch (DataFormatException x) {
                                throw new ZipException(x.getMessage());
                            }
                            if (buffer.hasRemaining()) {
                                ByteBuffer chunk = buffer;
                                buffer = null;
                                if (decodedChunk(chunk))
                                    return;
                            } else if (_inflater.needsInput()) {
                                if (!compressed.hasRemaining())
                                    return;
                                if (compressed.hasArray()) {
                                    _inflater.setInput(compressed.array(), compressed.arrayOffset() + compressed.position(), compressed.remaining());
                                    compressed.position(compressed.limit());
                                } else {
                                    // TODO use the pool
                                    byte[] input = new byte[compressed.remaining()];
                                    compressed.get(input);
                                    _inflater.setInput(input);
                                }
                            } else if (_inflater.finished()) {
                                int remaining = _inflater.getRemaining();
                                compressed.position(compressed.limit() - remaining);
                                _state = State.CRC;
                                _size = 0;
                                _value = 0;
                                break;
                            }
                        }
                        continue;
                    }
                default:
                    break;
            }
            if (!compressed.hasRemaining())
                break;
            byte currByte = compressed.get();
            switch(_state) {
                case ID:
                    {
                        _value += (currByte & 0xFF) << 8 * _size;
                        ++_size;
                        if (_size == 2) {
                            if (_value != 0x8B1F)
                                throw new ZipException("Invalid gzip bytes");
                            _state = State.CM;
                        }
                        break;
                    }
                case CM:
                    {
                        if ((currByte & 0xFF) != 0x08)
                            throw new ZipException("Invalid gzip compression method");
                        _state = State.FLG;
                        break;
                    }
                case FLG:
                    {
                        _flags = currByte;
                        _state = State.MTIME;
                        _size = 0;
                        _value = 0;
                        break;
                    }
                case MTIME:
                    {
                        // Skip the 4 MTIME bytes
                        ++_size;
                        if (_size == 4)
                            _state = State.XFL;
                        break;
                    }
                case XFL:
                    {
                        // Skip XFL
                        _state = State.OS;
                        break;
                    }
                case OS:
                    {
                        // Skip OS
                        _state = State.FLAGS;
                        break;
                    }
                case EXTRA_LENGTH:
                    {
                        _value += (currByte & 0xFF) << 8 * _size;
                        ++_size;
                        if (_size == 2)
                            _state = State.EXTRA;
                        break;
                    }
                case EXTRA:
                    {
                        // Skip EXTRA bytes
                        --_value;
                        if (_value == 0) {
                            // Clear the EXTRA flag and loop on the flags
                            _flags &= ~0x04;
                            _state = State.FLAGS;
                        }
                        break;
                    }
                case NAME:
                    {
                        // Skip NAME bytes
                        if (currByte == 0) {
                            // Clear the NAME flag and loop on the flags
                            _flags &= ~0x08;
                            _state = State.FLAGS;
                        }
                        break;
                    }
                case COMMENT:
                    {
                        // Skip COMMENT bytes
                        if (currByte == 0) {
                            // Clear the COMMENT flag and loop on the flags
                            _flags &= ~0x10;
                            _state = State.FLAGS;
                        }
                        break;
                    }
                case HCRC:
                    {
                        // Skip HCRC
                        ++_size;
                        if (_size == 2) {
                            // Clear the HCRC flag and loop on the flags
                            _flags &= ~0x02;
                            _state = State.FLAGS;
                        }
                        break;
                    }
                case CRC:
                    {
                        _value += (currByte & 0xFF) << 8 * _size;
                        ++_size;
                        if (_size == 4) {
                            // From RFC 1952, compliant decoders need not to verify the CRC
                            _state = State.ISIZE;
                            _size = 0;
                            _value = 0;
                        }
                        break;
                    }
                case ISIZE:
                    {
                        _value += (currByte & 0xFF) << 8 * _size;
                        ++_size;
                        if (_size == 4) {
                            if (_value != _inflater.getBytesWritten())
                                throw new ZipException("Invalid input size");
                            // TODO ByteBuffer result = output == null ? BufferUtil.EMPTY_BUFFER : ByteBuffer.wrap(output);
                            reset();
                            return;
                        }
                        break;
                    }
                default:
                    throw new ZipException();
            }
        }
    } catch (ZipException x) {
        throw new RuntimeException(x);
    } finally {
        if (buffer != null)
            release(buffer);
    }
}
Also used : DataFormatException(java.util.zip.DataFormatException) ZipException(java.util.zip.ZipException) ByteBuffer(java.nio.ByteBuffer)

Example 95 with ZipException

use of java.util.zip.ZipException in project che by eclipse.

the class JavaModelManager method getZipFile.

/**
     * Returns the open ZipFile at the given path. If the ZipFile
     * does not yet exist, it is created, opened, and added to the cache
     * of open ZipFiles.
     * <p/>
     * The path must be a file system path if representing an external
     * zip/jar, or it must be an absolute workspace relative path if
     * representing a zip/jar inside the workspace.
     *
     * @throws CoreException
     *         If unable to create/open the ZipFile
     */
public ZipFile getZipFile(IPath path) throws CoreException {
    if (isInvalidArchive(path))
        throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.status_IOException, new ZipException()));
    ZipCache zipCache;
    ZipFile zipFile;
    if ((zipCache = (ZipCache) this.zipFiles.get()) != null && (zipFile = zipCache.getCache(path)) != null) {
        return zipFile;
    }
    File localFile = null;
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IResource file = root.findMember(path);
    if (file != null) {
        // internal resource
        URI location;
        if (file.getType() != IResource.FILE || (location = file.getLocationURI()) == null) {
            throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.bind(Messages.file_notFound, path.toString()), null));
        }
        localFile = Util.toLocalFile(location, null);
        if (localFile == null)
            throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.bind(Messages.file_notFound, path.toString()), null));
    } else {
        // external resource -> it is ok to use toFile()
        localFile = path.toFile();
    }
    try {
        if (ZIP_ACCESS_VERBOSE) {
            //$NON-NLS-1$ //$NON-NLS-2$
            System.out.println("(" + Thread.currentThread() + ") [JavaModelManager.getZipFile(IPath)] Creating ZipFile on " + localFile);
        }
        zipFile = new ZipFile(localFile);
        if (zipCache != null) {
            zipCache.setCache(path, zipFile);
        }
        return zipFile;
    } catch (IOException e) {
        addInvalidArchive(path);
        throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.status_IOException, e));
    }
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) IJavaModelStatus(org.eclipse.jdt.core.IJavaModelStatus) CoreException(org.eclipse.core.runtime.CoreException) ZipFile(java.util.zip.ZipFile) IWorkspaceRoot(org.eclipse.core.resources.IWorkspaceRoot) ZipException(java.util.zip.ZipException) IOException(java.io.IOException) IClassFile(org.eclipse.jdt.core.IClassFile) ZipFile(java.util.zip.ZipFile) IFile(org.eclipse.core.resources.IFile) File(java.io.File) URI(java.net.URI) IResource(org.eclipse.core.resources.IResource)

Aggregations

ZipException (java.util.zip.ZipException)197 IOException (java.io.IOException)96 File (java.io.File)74 ZipEntry (java.util.zip.ZipEntry)67 ZipFile (java.util.zip.ZipFile)63 InputStream (java.io.InputStream)50 FileInputStream (java.io.FileInputStream)39 ZipInputStream (java.util.zip.ZipInputStream)26 FileOutputStream (java.io.FileOutputStream)23 BufferedInputStream (java.io.BufferedInputStream)22 JarFile (java.util.jar.JarFile)21 FileNotFoundException (java.io.FileNotFoundException)19 JarEntry (java.util.jar.JarEntry)19 ArrayList (java.util.ArrayList)18 ByteArrayInputStream (java.io.ByteArrayInputStream)15 ZipOutputStream (java.util.zip.ZipOutputStream)15 URL (java.net.URL)14 GZIPInputStream (java.util.zip.GZIPInputStream)12 BufferedOutputStream (java.io.BufferedOutputStream)8 RandomAccessFile (java.io.RandomAccessFile)8