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

The following examples show how to use java.util.zip.ZipEntry#setComment() . 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: ZIPCompressionOutputStream.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
@Override
public void addEntry( String filename, String extension ) throws IOException {
  // remove folder hierarchy
  int index = filename.lastIndexOf( Const.FILE_SEPARATOR );
  String entryPath;
  if ( index != -1 ) {
    entryPath = filename.substring( index + 1 );
  } else {
    entryPath = filename;
  }

  // remove ZIP extension
  index = entryPath.toLowerCase().lastIndexOf( ".zip" );
  if ( index != -1 ) {
    entryPath = entryPath.substring( 0, index ) + entryPath.substring( index + ".zip".length() );
  }

  // add real extension if needed
  if ( !Utils.isEmpty( extension ) ) {
    entryPath += "." + extension;
  }

  ZipEntry zipentry = new ZipEntry( entryPath );
  zipentry.setComment( "Compressed by Kettle" );
  ( (ZipOutputStream) delegate ).putNextEntry( zipentry );
}
 
Example 2
Source File: OldAndroidZipFileTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
static void createCompressedZip(OutputStream bytesOut) throws IOException {
    ZipOutputStream out = new ZipOutputStream(bytesOut);
    try {
        int i;

        for (i = 0; i < 3; i++) {
            byte[] input = makeSampleFile(i);
            ZipEntry newEntry = new ZipEntry("file-" + i);

            if (i != 1) {
                newEntry.setComment("this is file " + i);
            }
            out.putNextEntry(newEntry);
            out.write(input, 0, input.length);
            out.closeEntry();
        }

        out.setComment("This is a lovely compressed archive!");
    } finally {
        out.close();
    }
}
 
Example 3
Source File: ZipReaderTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test public void testZipEntryInvalidTime() throws IOException {
  long date = 312796800000L; // 11/30/1979 00:00:00, which is also 0 in DOS format
  byte[] extra = new ExtraData((short) 0xaa, new byte[] { (byte) 0xbb, (byte) 0xcd }).getBytes();
  try (ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(test))) {
    ZipEntry foo = new ZipEntry("foo");
    foo.setComment("foo comment.");
    foo.setMethod(ZipEntry.DEFLATED);
    foo.setTime(date);
    foo.setExtra(extra);
    zout.putNextEntry(foo);
    zout.write("foo".getBytes(UTF_8));
    zout.closeEntry();
  }

  try (ZipReader reader = new ZipReader(test, UTF_8)) {
    ZipFileEntry fooEntry = reader.getEntry("foo");
    assertThat(fooEntry.getTime()).isEqualTo(ZipUtil.DOS_EPOCH);
  }
}
 
Example 4
Source File: ZipUtils.java    From hasor with Apache License 2.0 6 votes vote down vote up
public static void writeEntry(ZipOutputStream zipStream, String scriptBody, String entryName, String comment) throws IOException {
    ZipEntry entry = new ZipEntry(entryName);
    entry.setComment(comment);
    zipStream.putNextEntry(entry);
    {
        OutputStreamWriter writer = new OutputStreamWriter(zipStream, Settings.DefaultCharset);
        BufferedWriter bfwriter = new BufferedWriter(writer);
        if (StringUtils.isBlank(scriptBody)) {
            bfwriter.write("");
        } else {
            bfwriter.write(scriptBody);
        }
        bfwriter.flush();
        writer.flush();
    }
    zipStream.closeEntry();
}
 
Example 5
Source File: ZipEntryTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testMaxLengthComment() throws Exception {
  String maxLengthComment = makeString(65535, "z");

  File f = createTemporaryZipFile();
  ZipOutputStream out = createZipOutputStream(f);
  ZipEntry ze = new ZipEntry("x");
  ze.setComment(maxLengthComment);
  out.putNextEntry(ze);
  out.closeEntry();
  out.close();

  // Read it back, and check that we see the entry.
  ZipFile zipFile = new ZipFile(f);
  assertEquals(maxLengthComment, zipFile.getEntry("x").getComment());
  zipFile.close();
}
 
Example 6
Source File: AndroidResourceOutputs.java    From bazel with Apache License 2.0 6 votes vote down vote up
protected void addEntry(
    String rawName, byte[] content, int storageMethod, @Nullable String comment)
    throws IOException {
  // Fix the path for windows.
  String relativeName = rawName.replace('\\', '/');
  // Make sure the zip entry is not absolute.
  Preconditions.checkArgument(
      !relativeName.startsWith("/"), "Cannot add absolute resources %s", relativeName);
  ZipEntry entry = new ZipEntry(relativeName);
  entry.setMethod(storageMethod);
  entry.setTime(normalizeTime(relativeName));
  entry.setSize(content.length);
  CRC32 crc32 = new CRC32();
  crc32.update(content);
  entry.setCrc(crc32.getValue());
  if (!Strings.isNullOrEmpty(comment)) {
    entry.setComment(comment);
  }

  zip.putNextEntry(entry);
  zip.write(content);
  zip.closeEntry();
}
 
Example 7
Source File: ArchiveBleach.java    From DocBleach with MIT License 6 votes vote down vote up
private ZipEntry cloneEntry(ZipEntry entry) {
  ZipEntry newEntry = new ZipEntry(entry.getName());

  newEntry.setTime(entry.getTime());
  if (entry.getCreationTime() != null) {
    newEntry.setCreationTime(entry.getCreationTime());
  }
  if (entry.getLastModifiedTime() != null) {
    newEntry.setLastModifiedTime(entry.getLastModifiedTime());
  }
  if (entry.getLastAccessTime() != null) {
    newEntry.setLastAccessTime(entry.getLastAccessTime());
  }
  newEntry.setComment(entry.getComment());
  newEntry.setExtra(entry.getExtra());

  return newEntry;
}
 
Example 8
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 9
Source File: ZipReaderTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test public void testSimultaneousReads() throws IOException {
  byte[] expectedFooData = "This is file foo. It contains a foo.".getBytes(UTF_8);
  byte[] expectedBarData = "This is a different file bar. It contains only a bar."
      .getBytes(UTF_8);
  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(expectedFooData);
    zout.closeEntry();

    ZipEntry bar = new ZipEntry("bar");
    bar.setComment("bar comment.");
    bar.setMethod(ZipEntry.DEFLATED);
    zout.putNextEntry(bar);
    zout.write(expectedBarData);
    zout.closeEntry();
  }

  try (ZipReader reader = new ZipReader(test, UTF_8)) {
    ZipFileEntry fooEntry = reader.getEntry("foo");
    ZipFileEntry barEntry = reader.getEntry("bar");
    InputStream fooIn = reader.getInputStream(fooEntry);
    InputStream barIn = reader.getInputStream(barEntry);
    byte[] fooData = new byte[expectedFooData.length];
    byte[] barData = new byte[expectedBarData.length];
    fooIn.read(fooData, 0, 10);
    barIn.read(barData, 0, 10);
    fooIn.read(fooData, 10, 10);
    barIn.read(barData, 10, 10);
    fooIn.read(fooData, 20, fooData.length - 20);
    barIn.read(barData, 20, barData.length - 20);
    assertThat(fooData).isEqualTo(expectedFooData);
    assertThat(barData).isEqualTo(expectedBarData);
  }
}
 
Example 10
Source File: BugReport.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void write(String name, String comment, String string, ZipOutputStream out) throws IOException {
	ZipEntry entry = new ZipEntry(name);
	entry.setComment(comment);
	out.putNextEntry(entry);

	PrintStream print = new PrintStream(out);
	print.println(string);
	print.flush();

	out.closeEntry();
}
 
Example 11
Source File: UnitTestZipArchive.java    From archive-patcher with Apache License 2.0 5 votes vote down vote up
/**
 * Make an arbitrary zip archive in memory using the specified entries.
 * @param entriesInFileOrder the entries
 * @return the zip file described above, as a byte array
 */
public static byte[] makeTestZip(List<UnitTestZipEntry> entriesInFileOrder) {
  try {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    ZipOutputStream zipOut = new ZipOutputStream(buffer);
    for (UnitTestZipEntry unitTestEntry : entriesInFileOrder) {
      ZipEntry zipEntry = new ZipEntry(unitTestEntry.path);
      zipOut.setLevel(unitTestEntry.level);
      CRC32 crc32 = new CRC32();
      byte[] uncompressedContent = unitTestEntry.getUncompressedBinaryContent();
      crc32.update(uncompressedContent);
      zipEntry.setCrc(crc32.getValue());
      zipEntry.setSize(uncompressedContent.length);
      if (unitTestEntry.level == 0) {
        zipOut.setMethod(ZipOutputStream.STORED);
        zipEntry.setCompressedSize(uncompressedContent.length);
      } else {
        zipOut.setMethod(ZipOutputStream.DEFLATED);
      }
      // Normalize MSDOS date/time fields to zero for reproducibility.
      zipEntry.setTime(0);
      if (unitTestEntry.comment != null) {
        zipEntry.setComment(unitTestEntry.comment);
      }
      zipOut.putNextEntry(zipEntry);
      zipOut.write(unitTestEntry.getUncompressedBinaryContent());
      zipOut.closeEntry();
    }
    zipOut.close();
    return buffer.toByteArray();
  } catch (IOException e) {
    // Should not happen as this is all in memory
    throw new RuntimeException("Unable to generate test zip!", e);
  }
}
 
Example 12
Source File: CompressJob.java    From ToGoZip with GNU General Public License v3.0 5 votes vote down vote up
/**
 * local helper to generate a ZipEntry.
 */
private ZipEntry createZipEntry(String renamedFile, long time,
                                String comment) {
    ZipEntry result = new ZipEntry(renamedFile);
    if (time != 0)
        result.setTime(time);
    if (comment != null)
        result.setComment(comment);

    return result;
}
 
Example 13
Source File: ZipEntryTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * java.util.zip.ZipEntry#getComment()
 */
public void test_getComment() {
    // Test for method java.lang.String java.util.zip.ZipEntry.getComment()
    ZipEntry zipEntry = new ZipEntry("zippy.zip");
    assertNull("Incorrect Comment Returned.", zipEntry.getComment());
    zipEntry.setComment("This Is A Comment");
    assertEquals("Incorrect Comment Returned.",
            "This Is A Comment", zipEntry.getComment());
}
 
Example 14
Source File: ZipEntryTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testTooLongComment() throws Exception {
  String tooLongComment = makeString(65536, "z");
  ZipEntry ze = new ZipEntry("x");
  try {
    ze.setComment(tooLongComment);
    fail();
  } catch (IllegalArgumentException expected) {
  }
}
 
Example 15
Source File: ZipUtils.java    From Stark with Apache License 2.0 5 votes vote down vote up
public static 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 16
Source File: AbstractZipFileTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_getComment_unset() throws Exception {
    File file = createTemporaryZipFile();
    ZipOutputStream out = createZipOutputStream(file);
    ZipEntry ze = new ZipEntry("test entry");
    ze.setComment("per-entry comment");
    out.putNextEntry(ze);
    out.close();

    try (ZipFile zipFile = new ZipFile(file)) {
        assertEquals(null, zipFile.getComment());
    }
}
 
Example 17
Source File: AbstractTransformTask.java    From cglib with Apache License 2.0 4 votes vote down vote up
protected void processJarFile(File file) throws Exception {

        if (verbose) {
            log("processing " + file.toURI());
        }
        
        File tempFile = File.createTempFile(file.getName(), null, new File(file
                .getAbsoluteFile().getParent()));
        try{
            
            ZipInputStream zip = new ZipInputStream(new FileInputStream(file));
            try {
                FileOutputStream fout = new FileOutputStream(tempFile);
                try{
                 ZipOutputStream out = new ZipOutputStream(fout);
                                
                    ZipEntry entry;
                    while ((entry = zip.getNextEntry()) != null) {
                        
                        
                        byte bytes[] = getBytes(zip);
                        
                        if (!entry.isDirectory()) {
                            
                            DataInputStream din = new DataInputStream(
                                              new ByteArrayInputStream(bytes)
                                            );
                            
                            if (din.readInt() == CLASS_MAGIC) {
                                
                                bytes = process(bytes);
                                                        
                            } else {
                                if (verbose) {
                                 log("ignoring " + entry.toString());
                                }
                            }
                        }
                       
                        ZipEntry outEntry = new ZipEntry(entry.getName());
                        outEntry.setMethod(entry.getMethod());
                        outEntry.setComment(entry.getComment());
                        outEntry.setSize(bytes.length);
                        
                        
                        if(outEntry.getMethod() == ZipEntry.STORED){
                            CRC32 crc = new CRC32();
                            crc.update(bytes);
                            outEntry.setCrc( crc.getValue() );
                            outEntry.setCompressedSize(bytes.length);
                        }
                        out.putNextEntry(outEntry);
                        out.write(bytes);
                        out.closeEntry();
                        zip.closeEntry();
                        
                    }
                    out.close(); 
                }finally{
                 fout.close();    
                } 
            } finally {
                zip.close();
            }
            
            
            if(file.delete()){
                
                File newFile = new File(tempFile.getAbsolutePath());
                
                if(!newFile.renameTo(file)){
                    throw new IOException("can not rename " + tempFile + " to " + file);   
                }
                
            }else{
                throw new IOException("can not delete " + file);
            }
            
        }finally{
            
            tempFile.delete();
            
        }
        
    }
 
Example 18
Source File: ZipEntryOutputStream.java    From pentaho-reporting with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void close()
  throws IOException {
  if ( closed ) {
    // A duplicate close is just a NO-OP as with all other output streams.
    return;
  }

  deflaterOutputStream.close();
  deflater.finish();
  deflater.end();

  final byte[] data = outputStream.toByteArray();
  final ByteArrayInputStream bin = new ByteArrayInputStream( data );
  final InflaterInputStream infi = new InflaterInputStream( bin );

  final ZipRepository repository = (ZipRepository) item.getRepository();

  final String contentId = (String) item.getContentId();
  final ZipEntry zipEntry = new ZipEntry( contentId );

  final Object comment = item.getAttribute( LibRepositoryBoot.ZIP_DOMAIN, LibRepositoryBoot.ZIP_COMMENT_ATTRIBUTE );
  if ( comment != null ) {
    zipEntry.setComment( String.valueOf( comment ) );
  }
  final Object version =
    item.getAttribute( LibRepositoryBoot.REPOSITORY_DOMAIN, LibRepositoryBoot.VERSION_ATTRIBUTE );
  if ( version instanceof Date ) {
    final Date date = (Date) version;
    zipEntry.setTime( date.getTime() );
  }

  final int zipMethod = RepositoryUtilities.getZipMethod( item );
  zipEntry.setCrc( crc32.getValue() );
  if ( zipMethod == Deflater.NO_COMPRESSION ) {
    zipEntry.setCompressedSize( size );
    zipEntry.setSize( size );
  } else {
    zipEntry.setSize( size );
  }
  repository.writeContent( zipEntry, infi, zipMethod, RepositoryUtilities.getZipLevel( item ) );
  infi.close();

  closed = true;
  outputStream = null;
  deflaterOutputStream = null;
}
 
Example 19
Source File: TransferServiceImpl.java    From packagedrone with Eclipse Public License 1.0 4 votes vote down vote up
private void putArtifacts ( final ZipOutputStream zos, final String baseName, final ReadableChannel channel, final Collection<? extends ArtifactInformation> inputArtifacts, final boolean onlyRoot ) throws IOException
{
    final List<ArtifactInformation> artifacts = new ArrayList<> ( inputArtifacts ); // make new instance in order to sort them
    Collections.sort ( artifacts, Comparator.comparing ( ArtifactInformation::getId ) );

    for ( final ArtifactInformation art : artifacts )
    {
        if ( !art.is ( "stored" ) )
        {
            continue;
        }

        if ( onlyRoot && art.getParentId () != null )
        {
            // only root artifacts in this run
            continue;
        }

        final String name = String.format ( "%s%s/", baseName, art.getId () );

        // make a dir entry

        {
            final ZipEntry ze = new ZipEntry ( name );
            ze.setComment ( art.getName () );

            final FileTime timestamp = FileTime.fromMillis ( art.getCreationTimestamp ().getTime () );

            ze.setLastModifiedTime ( timestamp );
            ze.setCreationTime ( timestamp );
            ze.setLastAccessTime ( timestamp );

            zos.putNextEntry ( ze );
            zos.closeEntry ();
        }

        // put the provided properties

        putProperties ( zos, name + "properties.xml", art.getProvidedMetaData () );
        putDataEntry ( zos, name + "name", art.getName () );

        if ( art.is ( "generator" ) )
        {
            putDataEntry ( zos, name + "generator", art.getVirtualizerAspectId () );
        }

        // put the blob

        try
        {
            channel.getContext ().stream ( art.getId (), in -> {
                zos.putNextEntry ( new ZipEntry ( name + "data" ) );
                ByteStreams.copy ( in, zos );
                zos.closeEntry ();
            } );
        }
        catch ( final Exception e )
        {
            throw new IOException ( "Failed to export artifact", e );
        }

        // further calls will process all artifacts but only get a filtered list

        final List<? extends ArtifactInformation> childs = art.getChildIds ().stream ().map ( id -> channel.getArtifact ( id ) ).filter ( opt -> opt.isPresent () ).map ( opt -> opt.get () ).collect ( Collectors.toList () );

        // put children of this entry

        putArtifacts ( zos, name, channel, childs, false );
    }
}
 
Example 20
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();
  }
}