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

The following examples show how to use java.util.zip.ZipEntry#getSize() . 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: ZipContentLocation.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
public ZipContentLocation( ZipRepository repository, ZipContentLocation parent, ZipEntry zipEntry ) {
  if ( repository == null ) {
    throw new NullPointerException();
  }
  if ( parent == null ) {
    throw new NullPointerException();
  }
  if ( zipEntry == null ) {
    throw new NullPointerException();
  }

  this.repository = repository;
  this.parent = parent;
  this.entryName = IOUtils.getInstance().getFileName( zipEntry.getName() );
  this.comment = zipEntry.getComment();
  this.size = zipEntry.getSize();
  this.time = zipEntry.getTime();
  this.entries = new HashMap();
  this.name = RepositoryUtilities.buildName( this, "/" ) + '/';
}
 
Example 2
Source File: ZipFilesTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsByteSource() throws Exception {
  File zipDir = new File(tmpDir, "zip");
  assertTrue(zipDir.mkdirs());
  createFileWithContents(zipDir, "myTextFile.txt", "Simple Text");

  ZipFiles.zipDirectory(tmpDir, zipFile);

  try (ZipFile zip = new ZipFile(zipFile)) {
    ZipEntry entry = zip.getEntry("zip/myTextFile.txt");
    ByteSource byteSource = ZipFiles.asByteSource(zip, entry);
    if (entry.getSize() != -1) {
      assertEquals(entry.getSize(), byteSource.size());
    }
    assertArrayEquals("Simple Text".getBytes(StandardCharsets.UTF_8), byteSource.read());
  }
}
 
Example 3
Source File: JarWithStream.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
private ZipEntry getZipEntryImpl(String path)
  throws IOException
{
  if (path.startsWith("/")) {
    path = path.substring(1);
  }
  
  try (InputStream is = getBacking().openRead()) {
    try (ZipInputStream zIn = new ZipInputStream(is)) {
      ZipEntry entry;

      while ((entry = zIn.getNextEntry()) != null) {
        if (entry.getName().equals(path)) {
          ZipEntry entryResult = new ZipEntry(entry);
          
          if (entry.getSize() < 0 && ! entry.isDirectory()) {
            long size = 0;
            TempBuffer tBuf = TempBuffer.create();
            byte []buffer = tBuf.buffer();
            
            int sublen;
            while ((sublen = zIn.read(buffer, 0, buffer.length)) > 0) {
              size += sublen;
            }
            
            tBuf.free();
            
            entryResult.setSize(size);
          }
          
          return entryResult;
        }
      }
    }
  }
  
  return null;
}
 
Example 4
Source File: JarClassLoader.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] resource(String path) throws IOException {
    if (nonexistentResources.contains(path)) {
        return null;
    }
    JarFile jf;
    try {
        jf = getJarFile(path);
    } catch (ZipException ex) {
        if (warnedFiles.add(file)) {
            LOGGER.log(Level.INFO, "Cannot open " + file, ex);
            dumpFiles(file, -1);
        }
        return null;
    }
    try {
        ZipEntry ze = jf.getEntry(path);
        if (ze == null) {
            nonexistentResources.add(path);
            return null;
        }

        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.log(Level.FINER, "Loading {0} from {1}", new Object[] {path, file.getPath()});
        }
    
        int len = (int)ze.getSize();
        byte[] data = new byte[len];
        InputStream is = jf.getInputStream(ze);
        int count = 0;
        while (count < len) {
            count += is.read(data, count, len-count);
        }
        return data;
    } finally {
        releaseJarFile();
    }
}
 
Example 5
Source File: ZipSplitterTest.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
private void checkContent(ZipInputStream zipInputStream,
                          ZipEntry zipEntry,
                          String unzippedContent) throws Exception {

    byte[] originalFileBytes = new byte[(int) zipEntry.getSize()];
    zipInputStream.read(originalFileBytes, 0, originalFileBytes.length);
    String originalFileContent = new String(originalFileBytes);
    assertEquals(unzippedContent, originalFileContent);
}
 
Example 6
Source File: ZippedEntry.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
public ZippedEntry(ZipEntry e, InputStream is) {
    this.name = e.getName();
    this.time = e.getTime();
    // this.mtime = e.getLastModifiedTime();
    // this.atime = e.getLastAccessTime();
    // this.ctime = e.getCreationTime();
    this.crc = e.getCrc();
    this.size = e.getSize();
    this.csize = e.getCompressedSize();
    this.method = e.getMethod();
    this.extra = e.getExtra();
    this.comment = e.getComment();
    this.is = is;
}
 
Example 7
Source File: JarWithFile.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the length of the entry in the jar file.
 *
 * @param path full path to the jar entry
 * @return the length of the entry
 */
public long getLength(String path)
{
  try {
    ZipEntry entry = getZipEntry(path);

    long length = entry != null ? entry.getSize() : -1;
    
    return length;
  } catch (IOException e) {
    log.log(Level.FINE, e.toString(), e);
    
    return -1;
  }
}
 
Example 8
Source File: Utils.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
static String zeString(ZipEntry ze) {
    int store = (ze.getCompressedSize() > 0) ?
        (int)( (1.0 - ((double)ze.getCompressedSize()/(double)ze.getSize()))*100 )
        : 0 ;
    // Follow unzip -lv output
    return ze.getSize() + "\t" + ze.getMethod()
        + "\t" + ze.getCompressedSize() + "\t"
        + store + "%\t"
        + new Date(ze.getTime()) + "\t"
        + Long.toHexString(ze.getCrc()) + "\t"
        + ze.getName() ;
}
 
Example 9
Source File: DexFileSplitter.java    From bazel with Apache License 2.0 5 votes vote down vote up
private void processDexEntry(ZipFile zip, ZipEntry entry) throws IOException {
  String filename = entry.getName();
  checkState(filename.endsWith(".class.dex"),
      "%s isn't a dex archive: %s", zip.getName(), filename);
  checkState(entry.getMethod() == ZipEntry.STORED, "Expect to process STORED: %s", filename);
  if (inCoreLib == null) {
    inCoreLib = filename.startsWith("j$/");
  } else if (inCoreLib != filename.startsWith("j$/")) {
    // Put j$.xxx classes in separate file.  This shouldn't normally happen (b/134705306).
    nextShard();
    inCoreLib = !inCoreLib;
  }
  if (inCoreLib) {
    System.err.printf(
        "WARNING: Unexpected file %s found. Please ensure this only happens in test APKs.%n",
        filename);
  }

  try (InputStream entryStream = zip.getInputStream(entry)) {
    // We don't want to use the Dex(InputStream) constructor because it closes the stream,
    // which will break the for loop, and it has its own bespoke way of reading the file into
    // a byte buffer before effectively calling Dex(byte[]) anyway.
    // TODO(kmb) since entry is stored, mmap content and give to Dex(ByteBuffer) and output zip
    byte[] content = new byte[(int) entry.getSize()];
    ByteStreams.readFully(entryStream, content); // throws if file is smaller than expected
    checkState(entryStream.read() == -1,
        "Too many bytes in jar entry %s, expected %s", entry, entry.getSize());

    Dex dexFile = new Dex(content);
    if (tracker.track(dexFile)) {
      nextShard();
      tracker.track(dexFile);
    }
    curOut.writeAsync(entry, content);
  }
}
 
Example 10
Source File: JapURLConnection.java    From jolie with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void connect()
	throws IOException {
	if( !connected ) {
		final String urlPath = url.getPath();
		final Matcher matcher = URL_PATTERN.matcher( urlPath );
		if( matcher.matches() ) {
			final String path = matcher.group( 1 );
			final String subPath = matcher.group( 2 );
			final JarURLConnection jarURLConnection = (JarURLConnection) new URL( "jar:" + path ).openConnection();
			inputStream = jarURLConnection.getInputStream();
			if( subPath.isEmpty() == false ) {
				JarFile jar = retrieve( new URL( path ), inputStream );
				final String[] nodes = NESTING_SEPARATION_PATTERN.split( subPath );
				int i;
				final StringBuilder builder = new StringBuilder( path.length() + subPath.length() );
				builder.append( path );
				for( i = 0; i < nodes.length - 1; i++ ) {
					builder.append( "!/" ).append( nodes[ i ] );
					jar = retrieve( new URL( builder.toString() ), inputStream );
				}
				final ZipEntry entry = jar.getEntry( nodes[ i ] );
				entrySize = entry.getSize();
				inputStream = jar.getInputStream( entry );
			}
		} else {
			throw new MalformedURLException( "Invalid JAP URL path: " + urlPath );
		}

		connected = true;
	}
}
 
Example 11
Source File: Utils.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
static String zeString(ZipEntry ze) {
    int store = (ze.getCompressedSize() > 0) ?
        (int)( (1.0 - ((double)ze.getCompressedSize()/(double)ze.getSize()))*100 )
        : 0 ;
    // Follow unzip -lv output
    return ze.getSize() + "\t" + ze.getMethod()
        + "\t" + ze.getCompressedSize() + "\t"
        + store + "%\t"
        + new Date(ze.getTime()) + "\t"
        + Long.toHexString(ze.getCrc()) + "\t"
        + ze.getName() ;
}
 
Example 12
Source File: ZippedEntry.java    From rxjava2-extras with Apache License 2.0 5 votes vote down vote up
public ZippedEntry(ZipEntry e, InputStream is) {
    this.name = e.getName();
    this.time = e.getTime();
    // this.mtime = e.getLastModifiedTime();
    // this.atime = e.getLastAccessTime();
    // this.ctime = e.getCreationTime();
    this.crc = e.getCrc();
    this.size = e.getSize();
    this.csize = e.getCompressedSize();
    this.method = e.getMethod();
    this.extra = e.getExtra();
    this.comment = e.getComment();
    this.is = is;
}
 
Example 13
Source File: StrictJarFile.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private InputStream getZipInputStream(ZipEntry ze) {
    if (ze.getMethod() == ZipEntry.STORED) {
        return new FDStream(fd, ze.getDataOffset(),
                ze.getDataOffset() + ze.getSize());
    } else {
        final FDStream wrapped = new FDStream(
                fd, ze.getDataOffset(), ze.getDataOffset() + ze.getCompressedSize());

        int bufSize = Math.max(1024, (int) Math.min(ze.getSize(), 65535L));
        return new ZipInflaterInputStream(wrapped, new Inflater(true), bufSize, ze);
    }
}
 
Example 14
Source File: FileObjects.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected long getSize () throws IOException {
    ZipFile zf = new ZipFile (archiveFile);
    try {
        ZipEntry ze = zf.getEntry(this.resName);
        return ze == null ? 0L : ze.getSize();
    } finally {
        zf.close();
    }
}
 
Example 15
Source File: ZipSecurity.java    From Box with Apache License 2.0 5 votes vote down vote up
public static boolean isZipBomb(ZipEntry entry) {
	long compressedSize = entry.getCompressedSize();
	long uncompressedSize = entry.getSize();
	if (compressedSize < 0 || uncompressedSize < 0) {
		LOG.error("Zip bomb attack detected, invalid sizes: compressed {}, uncompressed {}, name {}",
				compressedSize, uncompressedSize, entry.getName());
		return true;
	}
	if (compressedSize * MAX_SIZE_DIFF < uncompressedSize) {
		LOG.error("Zip bomb attack detected, invalid sizes: compressed {}, uncompressed {}, name {}",
				compressedSize, uncompressedSize, entry.getName());
		return true;
	}
	return false;
}
 
Example 16
Source File: ClassFileCache.java    From visualvm with GNU General Public License v2.0 4 votes vote down vote up
private byte[] readClassFile(String name, String classFileLocation)
                      throws IOException {
    String classFileName = name + ".class"; // NOI18N
    File location = new File(classFileLocation);

    if (location.isDirectory()) {
        return MiscUtils.readFileIntoBuffer(new FileOrZipEntry(classFileLocation, classFileName));
    } else { // Should be .jar file
             // The following code may be used at different stages of JFluid work, with different initialization states, so
             // it's coded defensively. If it can use an available open ZipFile, it will use it, otherwise it will open its own.

        ZipFile zip = null;

        if (classPath == null) {
            classPath = ClassRepository.getClassPath();
        }

        if (classPath != null) {
            try {
                zip = classPath.getZipFileForName(classFileLocation);
            } catch (ZipException e2) {
                throw new IOException("Could not open archive " + classFileLocation); // NOI18N
            }
        } else {
            throw new IOException("Could not get classpath for " + classFileName + " in " + classFileLocation); // NOI18N
        }

        ZipEntry entry = zip.getEntry(classFileName);

        if (entry == null) {
            throw new IOException("Could not find entry for " + classFileName + " in " + classFileLocation); // NOI18N
        }

        int len = (int) entry.getSize();
        byte[] buf = new byte[len];
        InputStream in = zip.getInputStream(entry);
        int readBytes;
        int ofs = 0;
        int remBytes = len;

        do {
            readBytes = in.read(buf, ofs, remBytes);
            ofs += readBytes;
            remBytes -= readBytes;
        } while (ofs < len);

        in.close();

        return buf;
    }
}
 
Example 17
Source File: BloggerBlogServiceImpl.java    From BlogSystem with Apache License 2.0 4 votes vote down vote up
private BlogTitleIdDTO analysisAndInsertMdFile(Parser parser, HtmlRenderer renderer, ZipEntry entry,
                                               InputStreamReader reader, int bloggerId, Long cateId) throws IOException {
    String name = entry.getName();

    if (!name.endsWith(".md")) return null;

    StringBuilder b = new StringBuilder((int) entry.getSize());
    int len = 0;
    char[] buff = new char[1024];
    while ((len = reader.read(buff)) > 0) {
        b.append(buff, 0, len);
    }

    // reader.close();
    // zip 文件关闭由 370行:zipFile.close() 统一关闭

    // 内容
    String mdContent = b.toString();

    // 对应的 html 内容
    Document document = parser.parse(mdContent);
    String htmlContent = renderer.render(document);

    // 摘要
    String firReg = htmlContent.replaceAll("<.*?>", ""); // 避免 subString 使有遗留的 html 标签,前端显示时会出错
    String tmpStr = firReg.length() > 500 ? firReg.substring(0, 500) : firReg;
    String aftReg = tmpStr.replaceAll("\\n", "");
    String summary = aftReg.length() > 200 ? aftReg.substring(0, 200) : aftReg;

    // UPDATE: 2018/4/4 更新 图片引用

    // 文件名作为标题
    String title = cateId == -1 ? name.replace(".md", "") :
            name.substring(name.lastIndexOf("/") + 1).replace(".md", "");

    int[] cts = {Math.toIntExact(cateId)};
    int id = insertBlog(bloggerId,
            cts,
            null,
            PUBLIC,
            title,
            htmlContent,
            mdContent,
            summary,
            null,
            false);
    if (id < 0) return null;

    BlogTitleIdDTO node = new BlogTitleIdDTO();
    node.setTitle(title);
    node.setId(id);

    return node;
}
 
Example 18
Source File: ProguardSuggester.java    From size-analyzer with Apache License 2.0 4 votes vote down vote up
@Override
public ImmutableList<Suggestion> processBundle(
    BundleContext context, AppBundle bundle, ZipFile bundleZip) {
  // Some old bundles contain multidex code in a way not compatible with the new AppBundle
  // representation, so the extraction of ZIP entries results in null pointers. Hence, entries are
  // wrapped in optionals to precisely capture the nulls.
  ImmutableList<Optional<ZipEntry>> dexFileEntries =
      bundle.getModules().values().stream()
          .flatMap(
              module ->
                  module
                      .findEntriesUnderPath(BundleModule.DEX_DIRECTORY)
                      .map(ModuleEntry::getPath)
                      .map(ZipPath.create(module.getName().toString())::resolve))
          .map(ZipPath::toString)
          .map(bundleZip::getEntry)
          .map(Optional::ofNullable)
          .collect(toImmutableList());

  OptionalLong totalDex =
      dexFileEntries.stream().anyMatch(not(Optional::isPresent))
          ? OptionalLong.empty()
          : OptionalLong.of(
              dexFileEntries.stream().map(Optional::get).mapToLong(ZipEntry::getSize).sum());

  ZipEntry proguardEntry = bundleZip.getEntry(PROGUARD_MAP);

  if (proguardEntry == null) {
    return ImmutableList.of(
        Suggestion.create(
            IssueType.PROGUARD_NO_MAP,
            Category.PROGUARD,
            totalDexPayload(totalDex),
            NO_MAP_SUGGESTION_MESSAGE,
            /* estimatedBytesSaved= */ null,
            /* autoFix= */ null));
  }

  // Deobfuscation map present.
  if (proguardEntry.getSize() == 0) {
    // Empty deobfuscation map.
    return ImmutableList.of(
        Suggestion.create(
            IssueType.PROGUARD_EMPTY_MAP,
            Category.PROGUARD,
            totalDexPayload(totalDex),
            EMPTY_MAP_SUGGESTION_MESSAGE,
            /* estimatedBytesSaved= */ null,
            /* autoFix= */ null));
  }

  // Everything is fine with the map, no suggestions.
  return ImmutableList.of();
}
 
Example 19
Source File: ZipRODirectory.java    From ratel with Apache License 2.0 4 votes vote down vote up
@Override
public long getSize(String fileName)
        throws DirectoryException {
    ZipEntry entry = getZipFileEntry(fileName);
    return entry.getSize();
}
 
Example 20
Source File: ArchiveRecordReader.java    From marklogic-contentpump with Apache License 2.0 4 votes vote down vote up
@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
    if (zipIn == null) {
        hasNext = false;
        return false;
    }

    ZipEntry zipEntry;
    ZipInputStream zis = (ZipInputStream) zipIn;
    if (value == null) {
        value = new DatabaseDocumentWithMeta();
    }
    while ((zipEntry = zis.getNextEntry()) != null) {
        subId = zipEntry.getName();
        long length = zipEntry.getSize();
        if (subId.endsWith(DocumentMetadata.NAKED)) {
            ((DatabaseDocumentWithMeta) value)
                .setMeta(getMetadataFromStream(length));
            String uri = subId.substring(0, subId.length()
                    - DocumentMetadata.NAKED.length());
            setKey(uri, 0, 0, false);
            value.setContent(null);
            count++;
            return true;
        }
        if (count % 2 == 0 && subId.endsWith(DocumentMetadata.EXTENSION)) {
            ((DatabaseDocumentWithMeta) value)
                .setMeta(getMetadataFromStream(length));
            count++;
            continue;
        }
        // no meta data
        if (count % 2 == 0 && !allowEmptyMeta) {
            setSkipKey(0, 0, "Missing metadata");
            return true;
        } else {
            setKey(subId, 0, 0, false);
            readDocFromStream(length, (DatabaseDocument) value);
            count++;
            return true;
        }
    }
    //end of a zip
    if (iterator != null && iterator.hasNext()) {
        close();
        initStream(iterator.next());
        return nextKeyValue();
    } else {
        hasNext = false;
        return false;
    }
}