Java Code Examples for java.util.zip.ZipEntry#setCrc()

The following examples show how to use java.util.zip.ZipEntry#setCrc() . 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: SpringBootGenerator.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private ZipEntry createZipEntry(File file, String fullPath) throws IOException {
    ZipEntry entry = new ZipEntry(fullPath);

    byte[] buffer = new byte[8192];
    int bytesRead = -1;
    try (InputStream is = new FileInputStream(file)) {
        CRC32 crc = new CRC32();
        int size = 0;
        while ((bytesRead = is.read(buffer)) != -1) {
            crc.update(buffer, 0, bytesRead);
            size += bytesRead;
        }
        entry.setSize(size);
        entry.setCompressedSize(size);
        entry.setCrc(crc.getValue());
        entry.setMethod(ZipEntry.STORED);
        return entry;
    }
}
 
Example 2
Source File: B7050028.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
    int len = conn.getContentLength();
    byte[] data = new byte[len];
    InputStream is = conn.getInputStream();
    is.read(data);
    is.close();
    conn.setDefaultUseCaches(false);
    File jar = File.createTempFile("B7050028", ".jar");
    jar.deleteOnExit();
    OutputStream os = new FileOutputStream(jar);
    ZipOutputStream zos = new ZipOutputStream(os);
    ZipEntry ze = new ZipEntry("B7050028.class");
    ze.setMethod(ZipEntry.STORED);
    ze.setSize(len);
    CRC32 crc = new CRC32();
    crc.update(data);
    ze.setCrc(crc.getValue());
    zos.putNextEntry(ze);
    zos.write(data, 0, len);
    zos.closeEntry();
    zos.finish();
    zos.close();
    os.close();
    System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
 
Example 3
Source File: B7050028.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
    int len = conn.getContentLength();
    byte[] data = new byte[len];
    InputStream is = conn.getInputStream();
    is.read(data);
    is.close();
    conn.setDefaultUseCaches(false);
    File jar = File.createTempFile("B7050028", ".jar");
    jar.deleteOnExit();
    OutputStream os = new FileOutputStream(jar);
    ZipOutputStream zos = new ZipOutputStream(os);
    ZipEntry ze = new ZipEntry("B7050028.class");
    ze.setMethod(ZipEntry.STORED);
    ze.setSize(len);
    CRC32 crc = new CRC32();
    crc.update(data);
    ze.setCrc(crc.getValue());
    zos.putNextEntry(ze);
    zos.write(data, 0, len);
    zos.closeEntry();
    zos.finish();
    zos.close();
    os.close();
    System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
 
Example 4
Source File: B7050028.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
    int len = conn.getContentLength();
    byte[] data = new byte[len];
    InputStream is = conn.getInputStream();
    is.read(data);
    is.close();
    conn.setDefaultUseCaches(false);
    File jar = File.createTempFile("B7050028", ".jar");
    jar.deleteOnExit();
    OutputStream os = new FileOutputStream(jar);
    ZipOutputStream zos = new ZipOutputStream(os);
    ZipEntry ze = new ZipEntry("B7050028.class");
    ze.setMethod(ZipEntry.STORED);
    ze.setSize(len);
    CRC32 crc = new CRC32();
    crc.update(data);
    ze.setCrc(crc.getValue());
    zos.putNextEntry(ze);
    zos.write(data, 0, len);
    zos.closeEntry();
    zos.finish();
    zos.close();
    os.close();
    System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
 
Example 5
Source File: AutoSTOREDZipOutputStream.java    From dexdiff with Apache License 2.0 6 votes vote down vote up
@Override
public void closeEntry() throws IOException {
    ZipEntry delayedEntry = this.delayedEntry;
    if (delayedEntry != null) {
        AccessBufByteArrayOutputStream delayedOutputStream = this.delayedOutputStream;
        byte[] buf = delayedOutputStream.getBuf();
        int size = delayedOutputStream.size();
        delayedEntry.setSize(size);
        delayedEntry.setCompressedSize(size);
        crc.reset();
        crc.update(buf, 0, size);
        delayedEntry.setCrc(crc.getValue());
        super.putNextEntry(delayedEntry);
        super.write(buf, 0, size);
        this.delayedEntry = null;
        delayedOutputStream.reset();
    }
    super.closeEntry();
}
 
Example 6
Source File: JarRefactor.java    From atlas with Apache License 2.0 6 votes vote down vote up
private void copyStream(InputStream inputStream, JarOutputStream jos, JarEntry ze, String pathName) {
    try {

        ZipEntry newEntry = new ZipEntry(pathName);
        // Make sure there is date and time set.
        if (ze.getTime() != -1) {
            newEntry.setTime(ze.getTime());
            newEntry.setCrc(ze.getCrc()); // If found set it into output file.
        }
        jos.putNextEntry(newEntry);
        IOUtils.copy(inputStream, jos);
        IOUtils.closeQuietly(inputStream);
    } catch (Exception e) {
        //throw new GradleException("copy stream exception", e);
        //e.printStackTrace();
        logger.error("copy stream exception >>> " + pathName + " >>>" + e.getMessage());
    }
}
 
Example 7
Source File: SpringBootZipOnDemandInputStream.java    From camel-spring-boot with Apache License 2.0 5 votes vote down vote up
protected void putNextEntry(final ZipOutputStream outputStream, final String context, long size, long crc32) throws IOException {

        ZipEntry entry = new ZipEntry(context);
        entry.setMethod(ZipEntry.STORED);
        entry.setSize(size);
        entry.setCrc(crc32);

        outputStream.putNextEntry(entry);
    }
 
Example 8
Source File: ZipOutputStreamTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void canWriteContentToStoredZipsInModeThrow() throws IOException {
  String name = "cheese.txt";
  byte[] input = "I like cheese".getBytes(UTF_8);
  File reference = File.createTempFile("reference", ".zip");

  try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(output, THROW_EXCEPTION);
      ZipOutputStream ref = new ZipOutputStream(new FileOutputStream(reference))) {
    ZipEntry entry = new ZipEntry(name);
    entry.setMethod(ZipEntry.STORED);
    entry.setTime(System.currentTimeMillis());
    entry.setSize(input.length);
    entry.setCompressedSize(input.length);
    entry.setCrc(calcCrc(input));
    out.putNextEntry(entry);
    ref.putNextEntry(entry);
    out.write(input);
    ref.write(input);
  }

  assertEquals(ImmutableList.of(new NameAndContent(name, input)), getExtractedEntries(output));

  // also check against the reference implementation
  byte[] seen = Files.readAllBytes(output);
  byte[] expected = Files.readAllBytes(reference.toPath());
  assertArrayEquals(expected, seen);
}
 
Example 9
Source File: JarSigner.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void writeEntry(ZipFile zf, ZipOutputStream os, ZipEntry ze)
        throws IOException {
    ZipEntry ze2 = new ZipEntry(ze.getName());
    ze2.setMethod(ze.getMethod());
    ze2.setTime(ze.getTime());
    ze2.setComment(ze.getComment());
    ze2.setExtra(ze.getExtra());
    if (ze.getMethod() == ZipEntry.STORED) {
        ze2.setSize(ze.getSize());
        ze2.setCrc(ze.getCrc());
    }
    os.putNextEntry(ze2);
    writeBytes(zf, ze, os);
}
 
Example 10
Source File: AbstractGetDataToSignASiCS.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected DSSDocument createPackageZip(List<DSSDocument> documents, Date signingDate) {
	try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos)) {

		for (int i = 0; i < documents.size(); i++) {
			DSSDocument document = documents.get(i);
			final String documentName = document.getName();
			final String name = documentName != null ? documentName : ZIP_ENTRY_DETACHED_FILE + i;
			final ZipEntry entryDocument = new ZipEntry(name);
			entryDocument.setTime(signingDate.getTime());
			entryDocument.setMethod(ZipEntry.STORED);
			byte[] byteArray = DSSUtils.toByteArray(document);
			entryDocument.setSize(byteArray.length);
			entryDocument.setCompressedSize(byteArray.length);
			final CRC32 crc = new CRC32();
			crc.update(byteArray);
			entryDocument.setCrc(crc.getValue());
			zos.putNextEntry(entryDocument);
			Utils.write(byteArray, zos);
		}

		zos.finish();

		return new InMemoryDocument(baos.toByteArray(), ASiCUtils.PACKAGE_ZIP);
	} catch (IOException e) {
		throw new DSSException("Unable to create package.zip file", e);
	}
}
 
Example 11
Source File: Androlib.java    From ratel with Apache License 2.0 5 votes vote down vote up
private void copyUnknownFiles(File appDir, ZipOutputStream outputFile, Map<String, String> files)
        throws BrutException, IOException {
    File unknownFileDir = new File(appDir, UNK_DIRNAME);

    // loop through unknown files
    for (Map.Entry<String,String> unknownFileInfo : files.entrySet()) {
        File inputFile = new File(unknownFileDir, BrutIO.sanitizeUnknownFile(unknownFileDir, unknownFileInfo.getKey()));
        if (inputFile.isDirectory()) {
            continue;
        }

        ZipEntry newEntry = new ZipEntry(unknownFileInfo.getKey());
        int method = Integer.parseInt(unknownFileInfo.getValue());
        LOGGER.fine(String.format("Copying unknown file %s with method %d", unknownFileInfo.getKey(), method));
        if (method == ZipEntry.STORED) {
            newEntry.setMethod(ZipEntry.STORED);
            newEntry.setSize(inputFile.length());
            newEntry.setCompressedSize(-1);
            BufferedInputStream unknownFile = new BufferedInputStream(new FileInputStream(inputFile));
            CRC32 crc = BrutIO.calculateCrc(unknownFile);
            newEntry.setCrc(crc.getValue());
        } else {
            newEntry.setMethod(ZipEntry.DEFLATED);
        }
        outputFile.putNextEntry(newEntry);

        BrutIO.copy(inputFile, outputFile);
        outputFile.closeEntry();
    }
}
 
Example 12
Source File: UpdateableZipTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void appendEntry(ZipOutputStream zos, String name, byte[] content) throws Exception{
  ZipEntry e = new ZipEntry(name);
  e.setMethod(ZipEntry.STORED);
  e.setSize(content.length);
  CRC32 crc = new CRC32();
  crc.update(content);
  e.setCrc(crc.getValue());
  zos.putNextEntry(e);
  zos.write(content, 0, content.length);
  zos.closeEntry();
}
 
Example 13
Source File: FileOperation.java    From AndResGuard with Apache License 2.0 5 votes vote down vote up
private static void zipFile(
    File resFile, ZipOutputStream zipout, String rootpath, HashMap<String, Integer> compressData) throws IOException {
  rootpath = rootpath + (rootpath.trim().length() == 0 ? "" : File.separator) + resFile.getName();
  if (resFile.isDirectory()) {
    File[] fileList = resFile.listFiles();
    for (File file : fileList) {
      zipFile(file, zipout, rootpath, compressData);
    }
  } else {
    final byte[] fileContents = readContents(resFile);
    //这里需要强转成linux格式,果然坑!!
    if (rootpath.contains("\\")) {
      rootpath = rootpath.replace("\\", "/");
    }
    if (!compressData.containsKey(rootpath)) {
      System.err.printf(String.format("do not have the compress data path =%s in resource.asrc\n", rootpath));
      //throw new IOException(String.format("do not have the compress data path=%s", rootpath));
      return;
    }
    int compressMethod = compressData.get(rootpath);
    ZipEntry entry = new ZipEntry(rootpath);

    if (compressMethod == ZipEntry.DEFLATED) {
      entry.setMethod(ZipEntry.DEFLATED);
    } else {
      entry.setMethod(ZipEntry.STORED);
      entry.setSize(fileContents.length);
      final CRC32 checksumCalculator = new CRC32();
      checksumCalculator.update(fileContents);
      entry.setCrc(checksumCalculator.getValue());
    }
    zipout.putNextEntry(entry);
    zipout.write(fileContents);
    zipout.flush();
    zipout.closeEntry();
  }
}
 
Example 14
Source File: GradlePackageTask.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
private void writeDependencies(JarOutputStream zOs)
  throws IOException
{
  Configuration targetConfig;
  
  targetConfig = _project.getConfigurations().getByName("runtime");
  
  for (File lib : targetConfig.resolve()) {
    if (isBootJar(lib)) {
      copyBootJar(zOs, lib);
    }
    
    String name = lib.getName();
    
    zOs.setLevel(0);
    
    ZipEntry entry = new ZipEntry("lib/" + name);
    
    entry.setMethod(ZipEntry.STORED);
    entry.setSize(lib.length());
    entry.setCrc(calculateCrc(lib.toPath()));
    
    zOs.putNextEntry(entry);
    
    Files.copy(lib.toPath(), zOs);
  }
}
 
Example 15
Source File: UnoPkg.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Copies a JAR file in the given ZIP file, but without compression for the files
 * in {@code SIS_DATA} directory.
 *
 * @param  file    the JAR file to copy.
 * @param  bundle  destination where to copy the JAR file.
 */
private static void copyInflated(final File file, final ZipOutputStream bundle) throws IOException {
    final ZipEntry entry = new ZipEntry(file.getName());
    bundle.putNextEntry(entry);
    final ZipOutputStream out = new ZipOutputStream(bundle);
    out.setLevel(9);
    try (ZipFile in = new ZipFile(file)) {
        final Enumeration<? extends ZipEntry> entries = in.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry   inEntry  = entries.nextElement();
            final String     name     = inEntry.getName();
            final ZipEntry   outEntry = new ZipEntry(name);
            if (name.startsWith("SIS_DATA")) {
                final long size = inEntry.getSize();
                outEntry.setMethod(ZipOutputStream.STORED);
                outEntry.setSize(size);
                outEntry.setCompressedSize(size);
                outEntry.setCrc(inEntry.getCrc());
            }
            try (InputStream inStream = in.getInputStream(inEntry)) {
                out.putNextEntry(outEntry);
                inStream.transferTo(out);
                out.closeEntry();
            }
        }
    }
    out.finish();
    bundle.closeEntry();
}
 
Example 16
Source File: ZipArchivePackagingElement.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void addDirectory(@Nonnull ZipOutputStream zipOutputStream, @Nonnull String relativePath) throws IOException {
  ZipEntry e = new ZipEntry(relativePath);
  e.setMethod(ZipEntry.STORED);
  e.setSize(0);
  e.setCrc(0);

  zipOutputStream.putNextEntry(e);
  zipOutputStream.closeEntry();
}
 
Example 17
Source File: ZipReaderTest.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Test public void testFileData() throws IOException {
  CRC32 crc = new CRC32();
  try (ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(test))) {
    ZipEntry foo = new ZipEntry("foo");
    foo.setComment("foo comment.");
    foo.setMethod(ZipEntry.DEFLATED);
    zout.putNextEntry(foo);
    zout.write("foo".getBytes(UTF_8));
    zout.closeEntry();

    ZipEntry bar = new ZipEntry("bar");
    bar.setComment("bar comment.");
    bar.setMethod(ZipEntry.STORED);
    bar.setSize("bar".length());
    bar.setCompressedSize("bar".length());
    crc.reset();
    crc.update("bar".getBytes(UTF_8));
    bar.setCrc(crc.getValue());
    zout.putNextEntry(bar);
    zout.write("bar".getBytes(UTF_8));
    zout.closeEntry();
  }

  try (ZipReader reader = new ZipReader(test, UTF_8)) {
    ZipFileEntry fooEntry = reader.getEntry("foo");
    InputStream fooIn = reader.getInputStream(fooEntry);
    byte[] fooData = new byte[3];
    fooIn.read(fooData);
    byte[] expectedFooData = "foo".getBytes(UTF_8);
    assertThat(fooData).isEqualTo(expectedFooData);

    assertThat(fooIn.read()).isEqualTo(-1);
    assertThat(fooIn.read(fooData)).isEqualTo(-1);
    assertThat(fooIn.read(fooData, 0, 3)).isEqualTo(-1);

    ZipFileEntry barEntry = reader.getEntry("bar");
    InputStream barIn = reader.getInputStream(barEntry);
    byte[] barData = new byte[3];
    barIn.read(barData);
    byte[] expectedBarData = "bar".getBytes(UTF_8);
    assertThat(barData).isEqualTo(expectedBarData);

    assertThat(barIn.read()).isEqualTo(-1);
    assertThat(barIn.read(barData)).isEqualTo(-1);
    assertThat(barIn.read(barData, 0, 3)).isEqualTo(-1);

    thrown.expect(IOException.class);
    thrown.expectMessage("Reset is not supported on this type of stream.");
    barIn.reset();
  }
}
 
Example 18
Source File: NativeUnpack.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
private void writeEntry(JarOutputStream j, String name,
                        long mtime, long lsize, boolean deflateHint,
                        ByteBuffer data0, ByteBuffer data1) throws IOException {
    int size = (int)lsize;
    if (size != lsize)
        throw new IOException("file too large: "+lsize);

    CRC32 crc32 = _crc32;

    if (_verbose > 1)
        Utils.log.fine("Writing entry: "+name+" size="+size
                         +(deflateHint?" deflated":""));

    if (_buf.length < size) {
        int newSize = size;
        while (newSize < _buf.length) {
            newSize <<= 1;
            if (newSize <= 0) {
                newSize = size;
                break;
            }
        }
        _buf = new byte[newSize];
    }
    assert(_buf.length >= size);

    int fillp = 0;
    if (data0 != null) {
        int size0 = data0.capacity();
        data0.get(_buf, fillp, size0);
        fillp += size0;
    }
    if (data1 != null) {
        int size1 = data1.capacity();
        data1.get(_buf, fillp, size1);
        fillp += size1;
    }
    while (fillp < size) {
        // Fill in rest of data from the stream itself.
        int nr = in.read(_buf, fillp, size - fillp);
        if (nr <= 0)  throw new IOException("EOF at end of archive");
        fillp += nr;
    }

    ZipEntry z = new ZipEntry(name);
    z.setTime(mtime * 1000);

    if (size == 0) {
        z.setMethod(ZipOutputStream.STORED);
        z.setSize(0);
        z.setCrc(0);
        z.setCompressedSize(0);
    } else if (!deflateHint) {
        z.setMethod(ZipOutputStream.STORED);
        z.setSize(size);
        z.setCompressedSize(size);
        crc32.reset();
        crc32.update(_buf, 0, size);
        z.setCrc(crc32.getValue());
    } else {
        z.setMethod(Deflater.DEFLATED);
        z.setSize(size);
    }

    j.putNextEntry(z);

    if (size > 0)
        j.write(_buf, 0, size);

    j.closeEntry();
    if (_verbose > 0) Utils.log.info("Writing " + Utils.zeString(z));
}
 
Example 19
Source File: AbstractZipFileTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Make sure the size used for stored zip entires is the uncompressed size.
 * b/10227498
 */
public void testStoredEntrySize() throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream out = createZipOutputStream(baos);

    // Set up a single stored entry.
    String name = "test_file";
    int expectedLength = 5;
    ZipEntry outEntry = new ZipEntry(name);
    byte[] buffer = new byte[expectedLength];
    outEntry.setMethod(ZipEntry.STORED);
    CRC32 crc = new CRC32();
    crc.update(buffer);
    outEntry.setCrc(crc.getValue());
    outEntry.setSize(buffer.length);

    out.putNextEntry(outEntry);
    out.write(buffer);
    out.closeEntry();
    out.close();

    // Write the result to a file.
    byte[] outBuffer = baos.toByteArray();
    File zipFile = createTemporaryZipFile();
    writeBytes(zipFile, outBuffer);

    ZipFile zip = new ZipFile(zipFile);
    // Set up the zip entry to have different compressed/uncompressed sizes.
    ZipEntry ze = zip.getEntry(name);
    ze.setCompressedSize(expectedLength - 1);
    // Read the contents of the stream and verify uncompressed size was used.
    InputStream stream = zip.getInputStream(ze);
    int count = 0;
    int read;
    while ((read = stream.read(buffer)) != -1) {
        count += read;
    }

    assertEquals(expectedLength, count);
    zip.close();
}
 
Example 20
Source File: NativeUnpack.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
private void writeEntry(JarOutputStream j, String name,
                        long mtime, long lsize, boolean deflateHint,
                        ByteBuffer data0, ByteBuffer data1) throws IOException {
    int size = (int)lsize;
    if (size != lsize)
        throw new IOException("file too large: "+lsize);

    CRC32 crc32 = _crc32;

    if (_verbose > 1)
        Utils.log.fine("Writing entry: "+name+" size="+size
                         +(deflateHint?" deflated":""));

    if (_buf.length < size) {
        int newSize = size;
        while (newSize < _buf.length) {
            newSize <<= 1;
            if (newSize <= 0) {
                newSize = size;
                break;
            }
        }
        _buf = new byte[newSize];
    }
    assert(_buf.length >= size);

    int fillp = 0;
    if (data0 != null) {
        int size0 = data0.capacity();
        data0.get(_buf, fillp, size0);
        fillp += size0;
    }
    if (data1 != null) {
        int size1 = data1.capacity();
        data1.get(_buf, fillp, size1);
        fillp += size1;
    }
    while (fillp < size) {
        // Fill in rest of data from the stream itself.
        int nr = in.read(_buf, fillp, size - fillp);
        if (nr <= 0)  throw new IOException("EOF at end of archive");
        fillp += nr;
    }

    ZipEntry z = new ZipEntry(name);
    z.setTime(mtime * 1000);

    if (size == 0) {
        z.setMethod(ZipOutputStream.STORED);
        z.setSize(0);
        z.setCrc(0);
        z.setCompressedSize(0);
    } else if (!deflateHint) {
        z.setMethod(ZipOutputStream.STORED);
        z.setSize(size);
        z.setCompressedSize(size);
        crc32.reset();
        crc32.update(_buf, 0, size);
        z.setCrc(crc32.getValue());
    } else {
        z.setMethod(Deflater.DEFLATED);
        z.setSize(size);
    }

    j.putNextEntry(z);

    if (size > 0)
        j.write(_buf, 0, size);

    j.closeEntry();
    if (_verbose > 0) Utils.log.info("Writing " + Utils.zeString(z));
}