java.util.zip.ZipException Java Examples

The following examples show how to use java.util.zip.ZipException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GzipDecodingBufferSupplier.java    From monsoon with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private boolean read_trailer_() throws IOException {
    final int crc_value = (int)crc_.getValue();
    final int declared_crc = read_int_();
    LOG.log(Level.FINE, "crc = {0}, expecting {1}", new Object[]{crc_value, declared_crc});
    if (declared_crc != crc_value)
        throw new ZipException("CRC mismatch");

    final int declared_fsize = read_int_();
    LOG.log(Level.FINE, "fsize (modulo int) = {0}, expecting {1}", new Object[]{(int)(inflater_.getBytesWritten() & 0xffffffff), declared_fsize});
    if ((int)(inflater_.getBytesWritten() & 0xffffffff) != declared_fsize)
        throw new ZipException("File size check mismatch");

    if (raw_.atEof()) return true;  // End-of-stream.
    // Not at end of stream, assume gzip concatenation.
    read_header_();
    return false;
}
 
Example #2
Source File: ZipFileIndex.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private byte[] readBytes(Entry entry) throws IOException {
    byte[] header = getHeader(entry);
    int csize = entry.compressedSize;
    byte[] cbuf = new byte[csize];
    zipRandomFile.skipBytes(get2ByteLittleEndian(header, 26) + get2ByteLittleEndian(header, 28));
    zipRandomFile.readFully(cbuf, 0, csize);

    // is this compressed - offset 8 in the ZipEntry header
    if (get2ByteLittleEndian(header, 8) == 0)
        return cbuf;

    int size = entry.size;
    byte[] buf = new byte[size];
    if (inflate(cbuf, buf) != size)
        throw new ZipException("corrupted zip file");

    return buf;
}
 
Example #3
Source File: CentralDirectoryFileHeader.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Generates the raw byte data of the central directory file header for the ZipEntry. Uses the
 * specified {@link ZipFileData} to encode the file name and comment.
 * @throws ZipException 
 */
static byte[] create(ZipFileEntry entry, ZipFileData file, boolean allowZip64)
    throws ZipException {
  if (allowZip64) {
    addZip64Extra(entry);
  } else {
    entry.getExtra().remove((short) 0x0001);
  }
  byte[] name = file.getBytes(entry.getName());
  byte[] extra = entry.getExtra().getBytes();
  byte[] comment = entry.getComment() != null
      ? file.getBytes(entry.getComment()) : new byte[]{};

  byte[] buf = new byte[FIXED_DATA_SIZE + name.length + extra.length + comment.length];

  fillFixedSizeData(buf, entry, name.length, extra.length, comment.length, allowZip64);
  System.arraycopy(name, 0, buf, FIXED_DATA_SIZE, name.length);
  System.arraycopy(extra, 0, buf, FIXED_DATA_SIZE + name.length, extra.length);
  System.arraycopy(comment, 0, buf, FIXED_DATA_SIZE + name.length + extra.length,
      comment.length);

  return buf;
}
 
Example #4
Source File: JarBuilder.java    From big-c with Apache License 2.0 6 votes vote down vote up
/** @param name path in jar for this jar element. Must not start with '/' */
void addNamedStream(JarOutputStream dst, String name, InputStream in) throws IOException {
  if (verbose) {
    System.err.println("JarBuilder.addNamedStream " + name);
  }
  try {
    dst.putNextEntry(new JarEntry(name));
    int bytesRead = 0;
    while ((bytesRead = in.read(buffer, 0, BUFF_SIZE)) != -1) {
      dst.write(buffer, 0, bytesRead);
    }
  } catch (ZipException ze) {
    if (ze.getMessage().indexOf("duplicate entry") >= 0) {
      if (verbose) {
        System.err.println(ze + " Skip duplicate entry " + name);
      }
    } else {
      throw ze;
    }
  } finally {
    in.close();
    dst.flush();
    dst.closeEntry();
  }
}
 
Example #5
Source File: GzipInflatingBuffer.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
private boolean processTrailer() throws ZipException {
  if (inflater != null
      && gzipMetadataReader.readableBytes() <= GZIP_HEADER_MIN_SIZE + GZIP_TRAILER_SIZE) {
    // We don't have enough bytes to begin inflating a concatenated gzip stream, drop context
    inflater.end();
    inflater = null;
  }
  if (gzipMetadataReader.readableBytes() < GZIP_TRAILER_SIZE) {
    return false;
  }
  if (crc.getValue() != gzipMetadataReader.readUnsignedInt()
      || expectedGzipTrailerIsize != gzipMetadataReader.readUnsignedInt()) {
    throw new ZipException("Corrupt GZIP trailer");
  }
  crc.reset();
  state = State.HEADER;
  return true;
}
 
Example #6
Source File: NEIServerUtils.java    From NotEnoughItems with MIT License 6 votes vote down vote up
public static NBTTagCompound readNBT(File file) throws IOException {
    if (!file.exists()) {
        return null;
    }
    FileInputStream in = new FileInputStream(file);
    NBTTagCompound tag;
    try {
        tag = CompressedStreamTools.readCompressed(in);
    } catch (ZipException e) {
        if (e.getMessage().equals("Not in GZIP format")) {
            tag = CompressedStreamTools.read(file);
        } else {
            throw e;
        }
    }
    in.close();
    return tag;
}
 
Example #7
Source File: ZipFileIndex.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private byte[] readBytes(Entry entry) throws IOException {
    byte[] header = getHeader(entry);
    int csize = entry.compressedSize;
    byte[] cbuf = new byte[csize];
    zipRandomFile.skipBytes(get2ByteLittleEndian(header, 26) + get2ByteLittleEndian(header, 28));
    zipRandomFile.readFully(cbuf, 0, csize);

    // is this compressed - offset 8 in the ZipEntry header
    if (get2ByteLittleEndian(header, 8) == 0)
        return cbuf;

    int size = entry.size;
    byte[] buf = new byte[size];
    if (inflate(cbuf, buf) != size)
        throw new ZipException("corrupted zip file");

    return buf;
}
 
Example #8
Source File: ZipFileSystem.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public void deleteFile(byte[] path, boolean failIfNotExists)
    throws IOException
{
    checkWritable();

    IndexNode inode = getInode(path);
    if (inode == null) {
        if (path != null && path.length == 0)
            throw new ZipException("root directory </> can't not be delete");
        if (failIfNotExists)
            throw new NoSuchFileException(getString(path));
    } else {
        if (inode.isDir() && inode.child != null)
            throw new DirectoryNotEmptyException(getString(path));
        updateDelete(inode);
    }
}
 
Example #9
Source File: ZipFileSystem.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void write(byte b[], int off, int len) throws IOException {
    if (e.type != Entry.FILECH)    // only from sync
        ensureOpen();
    if (off < 0 || len < 0 || off > b.length - len) {
        throw new IndexOutOfBoundsException();
    } else if (len == 0) {
        return;
    }
    switch (e.method) {
    case METHOD_DEFLATED:
        super.write(b, off, len);
        break;
    case METHOD_STORED:
        written += len;
        out.write(b, off, len);
        break;
    default:
        throw new ZipException("invalid compression method");
    }
    crc.update(b, off, len);
}
 
Example #10
Source File: JarBuilder.java    From RDFS with Apache License 2.0 6 votes vote down vote up
/** @param name path in jar for this jar element. Must not start with '/' */
void addNamedStream(JarOutputStream dst, String name, InputStream in) throws IOException {
  if (verbose) {
    System.err.println("JarBuilder.addNamedStream " + name);
  }
  try {
    dst.putNextEntry(new JarEntry(name));
    int bytesRead = 0;
    while ((bytesRead = in.read(buffer, 0, BUFF_SIZE)) != -1) {
      dst.write(buffer, 0, bytesRead);
    }
  } catch (ZipException ze) {
    if (ze.getMessage().indexOf("duplicate entry") >= 0) {
      if (verbose) {
        System.err.println(ze + " Skip duplicate entry " + name);
      }
    } else {
      throw ze;
    }
  } finally {
    in.close();
    dst.flush();
    dst.closeEntry();
  }
}
 
Example #11
Source File: ZipFileSystem.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public void deleteFile(byte[] path, boolean failIfNotExists)
    throws IOException
{
    checkWritable();

    IndexNode inode = getInode(path);
    if (inode == null) {
        if (path != null && path.length == 0)
            throw new ZipException("root directory </> can't not be delete");
        if (failIfNotExists)
            throw new NoSuchFileException(getString(path));
    } else {
        if (inode.isDir() && inode.child != null)
            throw new DirectoryNotEmptyException(getString(path));
        updateDelete(inode);
    }
}
 
Example #12
Source File: ZipFileSystem.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void write(byte b[], int off, int len) throws IOException {
    if (e.type != Entry.FILECH)    // only from sync
        ensureOpen();
    if (off < 0 || len < 0 || off > b.length - len) {
        throw new IndexOutOfBoundsException();
    } else if (len == 0) {
        return;
    }
    switch (e.method) {
    case METHOD_DEFLATED:
        super.write(b, off, len);
        break;
    case METHOD_STORED:
        written += len;
        out.write(b, off, len);
        break;
    default:
        throw new ZipException("invalid compression method");
    }
    crc.update(b, off, len);
}
 
Example #13
Source File: ZipWriterTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test public void testPrefixFileAfterZip() throws IOException {
  try (ZipWriter writer = new ZipWriter(new FileOutputStream(test), UTF_8)) {
    byte[] content = "content".getBytes(UTF_8);
    crc.update(content);
    ZipFileEntry entry = new ZipFileEntry("foo");
    entry.setSize(content.length);
    entry.setCompressedSize(content.length);
    entry.setCrc(crc.getValue());
    entry.setTime(cal.getTimeInMillis());

    writer.putNextEntry(entry);
    thrown.expect(ZipException.class);
    thrown.expectMessage("Cannot add a prefix file after the zip contents have been started.");
    writer.startPrefixFile();
  }
}
 
Example #14
Source File: Mojo.java    From capsule-maven-plugin with MIT License 6 votes vote down vote up
String addDirectoryToJar(final JarOutputStream jar, final String outputDirectory) throws IOException {

		// format the output directory
		String formattedOutputDirectory = "";
		if (outputDirectory != null && !outputDirectory.isEmpty()) {
			if (!outputDirectory.endsWith("/")) {
				formattedOutputDirectory = outputDirectory + File.separatorChar;
			} else {
				formattedOutputDirectory = outputDirectory;
			}
		}

		if (!formattedOutputDirectory.isEmpty()) {
			try {
				jar.putNextEntry(new ZipEntry(formattedOutputDirectory));
				jar.closeEntry();
			} catch (final ZipException ignore) {} // ignore duplicate entries and other errors
		}
		return formattedOutputDirectory;
	}
 
Example #15
Source File: BootstrapJarLoader.java    From Concurnas with MIT License 6 votes vote down vote up
private void loadJarsToLocations() throws ZipException, IOException{
	for(File zfa : this.jdkjars){
		ZipFile zf = new ZipFile(zfa);
		Enumeration<?> entries = zf.entries();
		while(entries.hasMoreElements()){
			ZipEntry ze = (ZipEntry)entries.nextElement();
			if(!ze.isDirectory()){
				String name = ze.getName();
				if(name.endsWith(".class")){
					name = name.substring(0, name.length()-6);
					
					nameToLocation.put(name, new FileAndZipEntry(zf, ze));
				}
			}
		}
	}
}
 
Example #16
Source File: JarBuilder.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/** @param name path in jar for this jar element. Must not start with '/' */
void addNamedStream(JarOutputStream dst, String name, InputStream in) throws IOException {
  if (verbose) {
    System.err.println("JarBuilder.addNamedStream " + name);
  }
  try {
    dst.putNextEntry(new JarEntry(name));
    int bytesRead = 0;
    while ((bytesRead = in.read(buffer, 0, BUFF_SIZE)) != -1) {
      dst.write(buffer, 0, bytesRead);
    }
  } catch (ZipException ze) {
    if (ze.getMessage().indexOf("duplicate entry") >= 0) {
      if (verbose) {
        System.err.println(ze + " Skip duplicate entry " + name);
      }
    } else {
      throw ze;
    }
  } finally {
    in.close();
    dst.flush();
    dst.closeEntry();
  }
}
 
Example #17
Source File: ZipFileSystem.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public void deleteFile(byte[] path, boolean failIfNotExists)
    throws IOException
{
    checkWritable();

    IndexNode inode = getInode(path);
    if (inode == null) {
        if (path != null && path.length == 0)
            throw new ZipException("root directory </> can't not be delete");
        if (failIfNotExists)
            throw new NoSuchFileException(getString(path));
    } else {
        if (inode.isDir() && inode.child != null)
            throw new DirectoryNotEmptyException(getString(path));
        updateDelete(inode);
    }
}
 
Example #18
Source File: JarBuilder.java    From hadoop-gpu with Apache License 2.0 6 votes vote down vote up
/** @param name path in jar for this jar element. Must not start with '/' */
void addNamedStream(JarOutputStream dst, String name, InputStream in) throws IOException {
  if (verbose) {
    System.err.println("JarBuilder.addNamedStream " + name);
  }
  try {
    dst.putNextEntry(new JarEntry(name));
    int bytesRead = 0;
    while ((bytesRead = in.read(buffer, 0, BUFF_SIZE)) != -1) {
      dst.write(buffer, 0, bytesRead);
    }
  } catch (ZipException ze) {
    if (ze.getMessage().indexOf("duplicate entry") >= 0) {
      if (verbose) {
        System.err.println(ze + " Skip duplicate entry " + name);
      }
    } else {
      throw ze;
    }
  } finally {
    in.close();
    dst.flush();
    dst.closeEntry();
  }
}
 
Example #19
Source File: GzipInflatingBuffer.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private boolean processTrailer() throws ZipException {
  if (inflater != null
      && gzipMetadataReader.readableBytes() <= GZIP_HEADER_MIN_SIZE + GZIP_TRAILER_SIZE) {
    // We don't have enough bytes to begin inflating a concatenated gzip stream, drop context
    inflater.end();
    inflater = null;
  }
  if (gzipMetadataReader.readableBytes() < GZIP_TRAILER_SIZE) {
    return false;
  }
  if (crc.getValue() != gzipMetadataReader.readUnsignedInt()
      || expectedGzipTrailerIsize != gzipMetadataReader.readUnsignedInt()) {
    throw new ZipException("Corrupt GZIP trailer");
  }
  crc.reset();
  state = State.HEADER;
  return true;
}
 
Example #20
Source File: ZipFileSystem.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public void deleteFile(byte[] path, boolean failIfNotExists)
    throws IOException
{
    checkWritable();

    IndexNode inode = getInode(path);
    if (inode == null) {
        if (path != null && path.length == 0)
            throw new ZipException("root directory </> can't not be delete");
        if (failIfNotExists)
            throw new NoSuchFileException(getString(path));
    } else {
        if (inode.isDir() && inode.child != null)
            throw new DirectoryNotEmptyException(getString(path));
        updateDelete(inode);
    }
}
 
Example #21
Source File: EndOfCentralDirectoryRecord.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Generates the raw byte data of the end of central directory record for the specified
 * {@link ZipFileData}.
 * @throws ZipException if the file comment is too long
 */
static byte[] create(ZipFileData file, boolean allowZip64) throws ZipException {
  byte[] comment = file.getBytes(file.getComment());

  byte[] buf = new byte[FIXED_DATA_SIZE + comment.length];

  // Allow writing of Zip file without Zip64 extensions for large archives as a special case
  // since many reading implementations can handle this.
  short numEntries = (short) (file.getNumEntries() > 0xffff && allowZip64
      ? -1 : file.getNumEntries());
  int cdSize = (int) (file.getCentralDirectorySize() > 0xffffffffL && allowZip64
      ? -1 : file.getCentralDirectorySize());
  int cdOffset = (int) (file.getCentralDirectoryOffset() > 0xffffffffL && allowZip64
      ? -1 : file.getCentralDirectoryOffset());
  ZipUtil.intToLittleEndian(buf, SIGNATURE_OFFSET, SIGNATURE);
  ZipUtil.shortToLittleEndian(buf, DISK_NUMBER_OFFSET, (short) 0);
  ZipUtil.shortToLittleEndian(buf, CD_DISK_OFFSET, (short) 0);
  ZipUtil.shortToLittleEndian(buf, DISK_ENTRIES_OFFSET, numEntries);
  ZipUtil.shortToLittleEndian(buf, TOTAL_ENTRIES_OFFSET, numEntries);
  ZipUtil.intToLittleEndian(buf, CD_SIZE_OFFSET, cdSize);
  ZipUtil.intToLittleEndian(buf, CD_OFFSET_OFFSET, cdOffset);
  ZipUtil.shortToLittleEndian(buf, COMMENT_LENGTH_OFFSET, (short) comment.length);
  System.arraycopy(comment, 0, buf, FIXED_DATA_SIZE, comment.length);

  return buf;
}
 
Example #22
Source File: ZipFileSystem.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public void deleteFile(byte[] path, boolean failIfNotExists)
    throws IOException
{
    checkWritable();

    IndexNode inode = getInode(path);
    if (inode == null) {
        if (path != null && path.length == 0)
            throw new ZipException("root directory </> can't not be delete");
        if (failIfNotExists)
            throw new NoSuchFileException(getString(path));
    } else {
        if (inode.isDir() && inode.child != null)
            throw new DirectoryNotEmptyException(getString(path));
        updateDelete(inode);
    }
}
 
Example #23
Source File: BootstrapClassLoader.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private List<URL> handleZipFile(File file) throws IOException
{
   File tempDir = OperatingSystemUtils.createTempDir();
   List<URL> result = new ArrayList<>();
   try
   {
      ZipFile zip = new ZipFile(file);
      Enumeration<? extends ZipEntry> entries = zip.entries();
      while (entries.hasMoreElements())
      {
         ZipEntry entry = entries.nextElement();
         String name = entry.getName();
         if (name.matches(path + "/.*\\.jar"))
         {
            log.log(Level.FINE, String.format("ZipEntry detected: %s len %d added %TD",
                     file.getAbsolutePath() + "/" + entry.getName(), entry.getSize(),
                     new Date(entry.getTime())));

            result.add(copy(tempDir, entry.getName(),
                     JarLocator.class.getClassLoader().getResource(name).openStream()
                     ).toURL());
         }
      }
      zip.close();
   }
   catch (ZipException e)
   {
      throw new RuntimeException("Error handling file " + file, e);
   }
   return result;
}
 
Example #24
Source File: ZipFileIndex.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private byte[] getHeader(Entry entry) throws IOException {
    zipRandomFile.seek(entry.offset);
    byte[] header = new byte[30];
    zipRandomFile.readFully(header);
    if (get4ByteLittleEndian(header, 0) != 0x04034b50)
        throw new ZipException("corrupted zip file");
    if ((get2ByteLittleEndian(header, 6) & 1) != 0)
        throw new ZipException("encrypted zip file"); // offset 6 in the header of the ZipFileEntry
    return header;
}
 
Example #25
Source File: FileIEngineImpl.java    From ramus with GNU General Public License v3.0 5 votes vote down vote up
public FileIEngineImpl(int id, JDBCTemplate template, PluginFactory factory)
        throws ClassNotFoundException, ZipException, IOException {
    super(id, template, "ramus_", factory);
    String sessions = getSessionsPath();
    tmpPath = sessions + File.separator + System.currentTimeMillis()
            + Math.round(Math.random() * 1000);
    new File(tmpPath).mkdirs();
    lockSession();
    fileTmpPath = tmpPath + File.separator + "cache";
}
 
Example #26
Source File: DataImportServiceImpl.java    From axelor-open-suite with GNU Affero General Public License v3.0 5 votes vote down vote up
private void processAttachments(MetaFile attachments) throws ZipException, IOException {

    if (dataDir.isDirectory() && dataDir.list().length == 0) {
      return;
    }

    File attachmentFile = MetaFiles.getPath(attachments).toFile();
    try (ZipInputStream zis = new ZipInputStream(new FileInputStream(attachmentFile))) {
      ZipEntry ze;
      byte[] buffer = new byte[1024];

      while ((ze = zis.getNextEntry()) != null) {
        String fileName = ze.getName();
        File extractFile = new File(dataDir, fileName);

        if (ze.isDirectory()) {
          extractFile.mkdirs();
          continue;
        } else {
          extractFile.getParentFile().mkdirs();
          extractFile.createNewFile();
        }

        try (FileOutputStream fos = new FileOutputStream(extractFile)) {
          int len;
          while ((len = zis.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
          }
        }
        zis.closeEntry();
      }
    }
  }
 
Example #27
Source File: GzipDecodingBufferSupplierTest.java    From monsoon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test(expected = ZipException.class)
public void corrupt_file_len() throws Exception {
    zero_byte_compressed[zero_byte_compressed.length - 4] = 0x01;
    final GzipDecodingBufferSupplier decoder = new GzipDecodingBufferSupplier(new ByteArrayBufferSupplier(zero_byte_compressed));
    final ByteBuffer buf = ByteBuffer.allocate(32);
    decoder.load(buf);
}
 
Example #28
Source File: ZipFileSystem.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private long getDataPos(Entry e) throws IOException {
    if (e.locoff == -1) {
        Entry e2 = getEntry0(e.name);
        if (e2 == null)
            throw new ZipException("invalid loc for entry <" + e.name + ">");
        e.locoff = e2.locoff;
    }
    byte[] buf = new byte[LOCHDR];
    if (readFullyAt(buf, 0, buf.length, e.locoff) != buf.length)
        throw new ZipException("invalid loc for entry <" + e.name + ">");
    return locpos + e.locoff + LOCHDR + LOCNAM(buf) + LOCEXT(buf);
}
 
Example #29
Source File: ZipFileSystem.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
int version() throws ZipException {
    if (method == METHOD_DEFLATED)
        return 20;
    else if (method == METHOD_STORED)
        return 10;
    throw new ZipException("unsupported compression method");
}
 
Example #30
Source File: ClassFinderlTest.java    From Ak47 with Apache License 2.0 5 votes vote down vote up
@Test
public void testme() throws ZipException, IOException{
    List<Class<?>> list1 = ClassFinder.findClassesInJars("", 
        new ClassFinderFilter(){
            @Override
            public boolean accept(Class<?> clazz) {
                return clazz.getName().endsWith("Handler");
            }
    });
    Assert.assertTrue(list1.isEmpty());
    
}