Esempio n. 1
0
 private void setSizesAndOffsetFromZip64Extra(
     final ZipEntry ze, final OffsetEntry offset, final int diskStart) throws IOException {
   final Zip64ExtendedInformationExtraField z64 =
       (Zip64ExtendedInformationExtraField)
           ze.getExtraField(Zip64ExtendedInformationExtraField.HEADER_ID);
   if (z64 != null) {
     final boolean hasUncompressedSize = ze.getSize() == 4294967295L;
     final boolean hasCompressedSize = ze.getCompressedSize() == 4294967295L;
     final boolean hasRelativeHeaderOffset = offset.headerOffset == 4294967295L;
     z64.reparseCentralDirectoryData(
         hasUncompressedSize, hasCompressedSize, hasRelativeHeaderOffset, diskStart == 65535);
     if (hasUncompressedSize) {
       ze.setSize(z64.getSize().getLongValue());
     } else if (hasCompressedSize) {
       z64.setSize(new ZipEightByteInteger(ze.getSize()));
     }
     if (hasCompressedSize) {
       ze.setCompressedSize(z64.getCompressedSize().getLongValue());
     } else if (hasUncompressedSize) {
       z64.setCompressedSize(new ZipEightByteInteger(ze.getCompressedSize()));
     }
     if (hasRelativeHeaderOffset) {
       offset.headerOffset = z64.getRelativeHeaderOffset().getLongValue();
     }
   }
 }
Esempio n. 2
0
  static Hashtable<String, PkgEntry> readJarFile(InputStream in) {
    Hashtable<String, PkgEntry> tbl = new Hashtable<String, PkgEntry>();
    try {
      ZipInputStream zis = new ZipInputStream(in);
      ZipEntry ze = zis.getNextEntry();
      while (ze != null) {
        String zname = ze.getName();
        if (zname.endsWith(".class")) {
          String pkgname = getPackageName(zname);
          if (!tbl.containsKey(pkgname)) {
            long csize = getCompressedSize(zis);
            tbl.put(pkgname, new PkgEntry(ze.getSize(), csize));
          } else {
            PkgEntry pe = tbl.get(pkgname);
            long csize = getCompressedSize(zis);
            pe.addSizes(ze.getSize(), csize);

            tbl.put(pkgname, pe);
          }
        }
        ze = zis.getNextEntry();
      }
    } catch (ZipException ex) {
      Logger.getLogger(JarAnalyzer.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
      Logger.getLogger(JarAnalyzer.class.getName()).log(Level.SEVERE, null, ex);
    }
    return tbl;
  }
Esempio n. 3
0
  /** initializes internal hash tables with Jar file resources. */
  private void init() {
    try {
      // extracts just sizes only.
      ZipFile zf = new ZipFile(jarFileName);
      Enumeration e = zf.entries();
      while (e.hasMoreElements()) {
        ZipEntry ze = (ZipEntry) e.nextElement();
        if (debugOn) {
          System.out.println(dumpZipEntry(ze));
        }
        htSizes.put(ze.getName(), new Integer((int) ze.getSize()));
      }
      zf.close();

      // extract resources and put them into the hashtable.
      FileInputStream fis = new FileInputStream(jarFileName);
      BufferedInputStream bis = new BufferedInputStream(fis);
      ZipInputStream zis = new ZipInputStream(bis);
      ZipEntry ze = null;
      while ((ze = zis.getNextEntry()) != null) {
        if (ze.isDirectory()) {
          continue;
        }
        if (debugOn) {
          System.out.println("ze.getName()=" + ze.getName() + "," + "getSize()=" + ze.getSize());
        }
        int size = (int) ze.getSize();
        // -1 means unknown size.
        if (size == -1) {
          size = ((Integer) htSizes.get(ze.getName())).intValue();
        }
        byte[] b = new byte[(int) size];
        int rb = 0;
        int chunk = 0;
        while (((int) size - rb) > 0) {
          chunk = zis.read(b, rb, (int) size - rb);
          if (chunk == -1) {
            break;
          }
          rb += chunk;
        }
        // add to internal resource hashtable
        htJarContents.put(ze.getName(), b);
        if (debugOn) {
          System.out.println(
              ze.getName() + "  rb=" + rb + ",size=" + size + ",csize=" + ze.getCompressedSize());
        }
      }
    } catch (NullPointerException e) {
      System.out.println("done.");
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Esempio n. 4
0
  @NotNull
  protected Map<String, EntryInfo> initEntries() {
    synchronized (lock) {
      Map<String, EntryInfo> map = myRelPathsToEntries.get();
      if (map == null) {
        final ZipInputStream zip = getZip();

        map = new HashMap<String, EntryInfo>();
        if (zip != null) {
          map.put("", new EntryInfo("", null, true, new byte[0]));
          try {
            ZipEntry entry = zip.getNextEntry();
            while (entry != null) {
              final String name = entry.getName();
              final boolean isDirectory = name.endsWith("/");
              if (entry.getExtra() == null) {
                byte[] cont = new byte[(int) entry.getSize()];
                ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
                InputStream stream = getZip();
                if (stream != null) {
                  int tmp;
                  if ((tmp = stream.read(cont)) == entry.getSize()) {
                    byteArray.write(cont, 0, tmp);
                    entry.setExtra(byteArray.toByteArray());
                  } else {
                    int readFromIS = tmp;
                    if (tmp < entry.getSize()) {
                      byteArray.write(cont, 0, tmp);
                      while (((tmp = stream.read(cont)) != -1)
                          && (tmp + readFromIS <= entry.getSize())) {
                        byteArray.write(cont, 0, tmp);
                        readFromIS += tmp;
                      }
                      entry.setExtra(byteArray.toByteArray());
                    }
                  }
                }
              }
              getOrCreate(
                  isDirectory ? name.substring(0, name.length() - 1) : name,
                  isDirectory,
                  map,
                  entry.getExtra());

              entry = zip.getNextEntry();
            }
          } catch (IOException e) {
            e.printStackTrace();
          }
          myRelPathsToEntries = new SoftReference<Map<String, EntryInfo>>(map);
        }
      }
      return map;
    }
  }
Esempio n. 5
0
 /**
  * Return an {@code InputStream} for reading the decompressed contents of ZIP entry.
  *
  * @param ze the ZIP entry to be read.
  * @return the input stream to read from.
  * @throws IOException if an error occurred while creating the input stream.
  */
 @Override
 public InputStream getInputStream(ZipEntry ze) throws IOException {
   if (manifestEntry != null) {
     getManifest();
   }
   if (verifier != null) {
     verifier.setManifest(getManifest());
     if (manifest != null) {
       verifier.mainAttributesEnd = manifest.getMainAttributesEnd();
     }
     if (verifier.readCertificates()) {
       verifier.removeMetaEntries();
       if (manifest != null) {
         manifest.removeChunks();
       }
       if (!verifier.isSignedJar()) {
         verifier = null;
       }
     }
   }
   InputStream in = super.getInputStream(ze);
   if (in == null) {
     return null;
   }
   if (verifier == null || ze.getSize() == -1) {
     return in;
   }
   JarVerifier.VerifierEntry entry = verifier.initEntry(ze.getName());
   if (entry == null) {
     return in;
   }
   return new JarFileInputStream(in, ze, entry);
 }
Esempio n. 6
0
  /**
   * Returns the entries of an archive.
   *
   * @param ctx query context
   * @return entries
   * @throws QueryException query exception
   */
  private Iter entries(final QueryContext ctx) throws QueryException {
    final B64 archive = (B64) checkType(checkItem(expr[0], ctx), AtomType.B64);

    final ValueBuilder vb = new ValueBuilder();
    final ArchiveIn in = ArchiveIn.get(archive.input(info), info);
    try {
      while (in.more()) {
        final ZipEntry ze = in.entry();
        if (ze.isDirectory()) continue;
        final FElem e = new FElem(Q_ENTRY, NS);
        long s = ze.getSize();
        if (s != -1) e.add(Q_SIZE, token(s));
        s = ze.getTime();
        if (s != -1) e.add(Q_LAST_MOD, new Dtm(s, info).string(info));
        s = ze.getCompressedSize();
        if (s != -1) e.add(Q_COMP_SIZE, token(s));
        e.add(ze.getName());
        vb.add(e);
      }
      return vb;
    } catch (final IOException ex) {
      Util.debug(ex);
      throw ARCH_FAIL.thrw(info, ex);
    } finally {
      in.close();
    }
  }
Esempio n. 7
0
  @NotNull
  @Override
  public byte[] contentsToByteArray(@NotNull String relativePath) throws IOException {
    FileAccessorCache.Handle<ZipFile> zipRef;

    try {
      zipRef = getZipFileHandle();
    } catch (RuntimeException ex) {
      Throwable cause = ex.getCause();
      if (cause instanceof IOException) throw (IOException) cause;
      throw ex;
    }

    try {
      ZipFile zip = zipRef.get();
      ZipEntry entry = zip.getEntry(relativePath);
      if (entry != null) {
        InputStream stream = zip.getInputStream(entry);
        if (stream != null) {
          // ZipFile.c#Java_java_util_zip_ZipFile_read reads data in 8K (stack allocated) blocks -
          // no sense to create BufferedInputStream
          try {
            return FileUtil.loadBytes(stream, (int) entry.getSize());
          } finally {
            stream.close();
          }
        }
      }
    } finally {
      zipRef.release();
    }

    throw new FileNotFoundException(getFile() + "!/" + relativePath);
  }
Esempio n. 8
0
  private void _dovV() throws IOException {
    if (z_aString.endsWith(".jar")) {
      try {
        JarFile jarfile = new JarFile(z_aString, false);
        for (Enumeration enumeration = jarfile.entries(); enumeration.hasMoreElements(); ) {
          ZipEntry zipentry = (ZipEntry) enumeration.nextElement();
          String s = zipentry.getName();
          if (s.endsWith(".class")) {
            InputStream inputstream = jarfile.getInputStream(zipentry);
            _aInputStreamStringV(inputstream, (int) zipentry.getSize(), s);
            inputstream.close();
          }
        }

        jarfile.close();
        z_newZ = true;
      } catch (IOException ioexception) {
        throw new IOException(ioexception.getMessage() + ": " + z_aString);
      }
    } else {
      File file = new File(z_aString);
      FileInputStream fileinputstream = new FileInputStream(file);
      _aInputStreamStringV(fileinputstream, (int) file.length(), z_aString);
      fileinputstream.close();
    }
  }
Esempio n. 9
0
  private boolean unpackFile(ZipFile zip, byte[] buf, ZipEntry fileEntry, String name)
      throws IOException, FileNotFoundException {
    if (fileEntry == null) fileEntry = zip.getEntry(name);
    if (fileEntry == null)
      throw new FileNotFoundException("Can't find " + name + " in " + zip.getName());

    File outFile = new File(sGREDir, name);
    if (outFile.lastModified() == fileEntry.getTime() && outFile.length() == fileEntry.getSize())
      return false;

    File dir = outFile.getParentFile();
    if (!dir.exists()) dir.mkdirs();

    InputStream fileStream;
    fileStream = zip.getInputStream(fileEntry);

    OutputStream outStream = new FileOutputStream(outFile);

    while (fileStream.available() > 0) {
      int read = fileStream.read(buf, 0, buf.length);
      outStream.write(buf, 0, read);
    }

    fileStream.close();
    outStream.close();
    outFile.setLastModified(fileEntry.getTime());
    return true;
  }
Esempio n. 10
0
  public void connect() throws IOException {
    if (!connected) {
      String path = url.getPath();
      Matcher matcher = urlPattern.matcher(path);
      if (matcher.matches()) {
        path = matcher.group(1);
        String subPath = matcher.group(2);
        JarURLConnection jarURLConnection =
            (JarURLConnection) new URL("jar:" + path).openConnection();
        inputStream = jarURLConnection.getInputStream();
        if (subPath.isEmpty() == false) {
          JarFile jar = retrieve(new URL(path), inputStream);
          String[] nodes = nestingSeparatorPattern.split(subPath);
          int i;
          for (i = 0; i < nodes.length - 1; i++) {
            path += "!/" + nodes[i];
            jar = retrieve(new URL(path), inputStream);
          }
          ZipEntry entry = jar.getEntry(nodes[i]);
          entrySize = entry.getSize();
          inputStream = jar.getInputStream(entry);
        }
      } else {
        throw new MalformedURLException("Invalid JAP URL path: " + path);
      }

      connected = true;
    }
  }
Esempio n. 11
0
    InMemorySourceRepository(@WillClose ZipInputStream in) throws IOException {
      try {
        while (true) {

          ZipEntry e = in.getNextEntry();
          if (e == null) break;
          if (!e.isDirectory()) {
            String name = e.getName();
            long size = e.getSize();

            if (size > Integer.MAX_VALUE)
              throw new IOException(name + " is too big at " + size + " bytes");
            ByteArrayOutputStream out;
            if (size <= 0) out = new ByteArrayOutputStream();
            else out = new ByteArrayOutputStream((int) size);
            GZIPOutputStream gOut = new GZIPOutputStream(out);
            IO.copy(in, gOut);
            gOut.close();
            byte data[] = out.toByteArray();
            contents.put(name, data);
            lastModified.put(name, e.getTime());
          }
          in.closeEntry();
        }
      } finally {
        Util.closeSilently(in);
      }
    }
  /**
   * Unzip an archive
   *
   * @param zipname the archive name, stored in the temp directory
   * @return boolean state indicating the unzip success
   */
  private boolean UnzipLangArchive(String zipname) {
    ZipFile zipFile;

    // reset the statuses, thus we will be able to get the progress[%] status
    m_lMaxDownloadSz = GetZipSize(zipname);
    m_lCurrentDownloadSz = 0;

    try {
      zipFile = new ZipFile(zipname);

      Enumeration entries = zipFile.entries();
      while (entries.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) entries.nextElement();

        String filename = entry.getName();
        Log.v(TAG, "Extracting file: " + filename);

        if (!CopyInputStream(zipFile.getInputStream(entry), entry.getSize(), entry.getName()))
          return false;
        m_ParentProgressDialog.setProgress(GetDownloadStatus());
      }

      zipFile.close();
    } catch (IOException ioe) {
      Log.v(TAG, "exception:" + ioe.toString());
      return false;
    }

    return true;
  }
Esempio n. 13
0
  /**
   * @return a mutable list
   * @throws IOException
   */
  public static List<JSSourceFile> getDefaultExterns() throws IOException {
    InputStream input = CommandLineRunner.class.getResourceAsStream("/externs.zip");
    ZipInputStream zip = new ZipInputStream(input);
    Map<String, JSSourceFile> externsMap = Maps.newHashMap();
    for (ZipEntry entry = null; (entry = zip.getNextEntry()) != null; ) {
      LimitInputStream entryStream = new LimitInputStream(zip, entry.getSize());
      externsMap.put(
          entry.getName(),
          JSSourceFile.fromInputStream(
              // Give the files an odd prefix, so that they do not conflict
              // with the user's files.
              "externs.zip//" + entry.getName(), entryStream));
    }

    Preconditions.checkState(
        externsMap.keySet().equals(Sets.newHashSet(DEFAULT_EXTERNS_NAMES)),
        "Externs zip must match our hard-coded list of externs.");

    // Order matters, so the resources must be added to the result list
    // in the expected order.
    List<JSSourceFile> externs = Lists.newArrayList();
    for (String key : DEFAULT_EXTERNS_NAMES) {
      externs.add(externsMap.get(key));
    }

    return externs;
  }
  protected void load(ZipFile zipfile) throws IOException {
    Enumeration entries = zipfile.entries();
    while (entries.hasMoreElements()) {
      ZipEntry entry = (ZipEntry) entries.nextElement();

      fireBeginFile(entry.getName());

      Logger.getLogger(getClass())
          .debug("Starting file " + entry.getName() + " (" + entry.getSize() + " bytes)");

      byte[] bytes = null;
      InputStream in = null;
      try {
        in = zipfile.getInputStream(entry);
        bytes = readBytes(in);
      } finally {
        if (in != null) {
          try {
            in.close();
          } catch (IOException ex) {
            // Ignore
          }
        }
      }

      Logger.getLogger(getClass())
          .debug("Passing up file " + entry.getName() + " (" + bytes.length + " bytes)");
      getLoader().load(entry.getName(), new ByteArrayInputStream(bytes));

      fireEndFile(entry.getName());
    }
  }
Esempio n. 15
0
 public byte[] patchClassInJar(String name, byte[] bytes, String ObfName, File location) {
   try {
     // open the jar as zip
     ZipFile zip = new ZipFile(location);
     // find the file inside the zip that is called te.class or
     // net.minecraft.entity.monster.EntityCreeper.class
     // replacing the . to / so it would look for net/minecraft/entity/monster/EntityCreeper.class
     ZipEntry entry = zip.getEntry(name.replace('.', '/') + ".class");
     if (entry == null) {
       System.out.println(name + " not found in " + location.getName());
     } else {
       // serialize the class file into the bytes array
       InputStream zin = zip.getInputStream(entry);
       bytes = new byte[(int) entry.getSize()];
       zin.read(bytes);
       zin.close();
       System.out.println("[" + "ExtraFood-patcher" + "]: " + "Class " + name + " patched!");
     }
     zip.close();
   } catch (Exception e) {
     throw new RuntimeException("Error overriding " + name + " from " + location.getName(), e);
   }
   // return the new bytes
   return bytes;
 }
Esempio n. 16
0
  /**
   * Checks the contents of the specified zip entry.
   *
   * @param file file to be checked
   * @param data expected file contents
   * @throws IOException I/O exception
   */
  private static void checkEntry(final String file, final byte[] data) throws IOException {

    ZipFile zf = null;
    try {
      zf = new ZipFile(TMPZIP);
      final ZipEntry ze = zf.getEntry(file);
      assertNotNull("File not found: " + file, ze);
      final DataInputStream is = new DataInputStream(zf.getInputStream(ze));
      final byte[] dt = new byte[(int) ze.getSize()];
      is.readFully(dt);
      assertTrue(
          "Wrong contents in file \""
              + file
              + "\":"
              + Prop.NL
              + "Expected: "
              + string(data)
              + Prop.NL
              + "Found: "
              + string(dt),
          eq(data, dt));
    } finally {
      if (zf != null) zf.close();
    }
  }
Esempio n. 17
0
  /**
   * 获得制定zip名称的输入流
   *
   * @param is zip的输入流
   * @param reportName 要获得的zip输入流名称
   * @return 流
   */
  @SuppressWarnings("unchecked")
  public static void getZipReportInputStreamMap(InputStream is, Map<Object, Object> parameters) {

    ZipInputStream zis = new ZipInputStream(is);
    BufferedOutputStream dest = null;
    ZipEntry entry = null;

    ByteArrayOutputStream fos = null;

    try {
      while ((entry = zis.getNextEntry()) != null) {
        int count;
        byte data[] = new byte[BUFFER];

        // write the files to the disk
        fos = new ByteArrayOutputStream((int) entry.getSize());
        dest = new BufferedOutputStream(fos, BUFFER);
        while ((count = zis.read(data, 0, BUFFER)) != -1) {
          dest.write(data, 0, count);
        }

        dest.flush();
        dest.close();

        parameters.put(entry.getName(), new ByteArrayInputStream(fos.toByteArray()));
      }
      zis.close();
    } catch (Exception e) {
      throw new ApplicationRuntimeException(e);
    }
  }
  /*
   * Load a class from a file in an archive.  We currently assume that
   * the file is a Zip archive.
   *
   * Returns null if the class wasn't found.
   */
  private byte[] loadFromArchive(ZipFile zip, String name) {
    ZipEntry entry;

    entry = zip.getEntry(name);
    if (entry == null) return null;

    ByteArrayOutputStream byteStream;
    InputStream stream;
    int count;

    /*
     * Copy the data out of the stream.  Because we got the ZipEntry
     * from a ZipFile, the uncompressed size is known, and we can set
     * the initial size of the ByteArrayOutputStream appropriately.
     */
    try {
      stream = zip.getInputStream(entry);
      byteStream = new ByteArrayOutputStream((int) entry.getSize());
      byte[] buf = new byte[4096];
      while ((count = stream.read(buf)) > 0) byteStream.write(buf, 0, count);

      stream.close();
    } catch (IOException ioex) {
      // System.out.println("Failed extracting '" + archive + "': " +ioex);
      return null;
    }

    // System.out.println("  loaded from Zip");
    return byteStream.toByteArray();
  }
  // TODO - zipEntry might use extended local header
  protected void add(ZipEntry zipEntry, ZipFileEntryInputStream zipData, String password)
      throws IOException, UnsupportedEncodingException {
    AESEncrypter aesEncrypter = new AESEncrypterBC(password.getBytes("iso-8859-1"));

    ExtZipEntry entry = new ExtZipEntry(zipEntry.getName());
    entry.setMethod(zipEntry.getMethod());
    entry.setSize(zipEntry.getSize());
    entry.setCompressedSize(zipEntry.getCompressedSize() + 28);
    entry.setTime(zipEntry.getTime());
    entry.initEncryptedEntry();

    zipOS.putNextEntry(entry);
    // ZIP-file data contains: 1. salt 2. pwVerification 3. encryptedContent 4. authenticationCode
    zipOS.writeBytes(aesEncrypter.getSalt());
    zipOS.writeBytes(aesEncrypter.getPwVerification());

    byte[] data = new byte[1024];
    int read = zipData.read(data);
    while (read != -1) {
      aesEncrypter.encrypt(data, read);
      zipOS.writeBytes(data, 0, read);
      read = zipData.read(data);
    }

    byte[] finalAuthentication = aesEncrypter.getFinalAuthentication();
    if (LOG.isLoggable(Level.FINE)) {
      LOG.fine(
          "finalAuthentication="
              + Arrays.toString(finalAuthentication)
              + " at pos="
              + zipOS.getWritten());
    }

    zipOS.writeBytes(finalAuthentication);
  }
Esempio n. 20
0
    @Override
    protected Collection<cgCache> doImport() throws IOException, ParserException {
      Log.i(Settings.tag, "Import GPX zip file: " + cacheFile.getAbsolutePath());
      ZipFile zipFile = new ZipFile(cacheFile);
      try {
        final String gpxName = getGpxFileNameForZipFileName(cacheFile.getName());
        if (gpxName == null) {
          throw new ParserException(cacheFile.getName() + " is not a GPX zip file");
        }
        final ZipEntry gpxEntry = zipFile.getEntry(gpxName);
        if (gpxEntry == null) {
          throw new ParserException(cacheFile.getName() + " is not a GPX zip file");
        }
        importStepHandler.sendMessage(
            importStepHandler.obtainMessage(
                IMPORT_STEP_READ_FILE,
                R.string.gpx_import_loading_caches,
                (int) gpxEntry.getSize()));

        Collection<cgCache> caches;
        GPXParser parser;
        try {
          // try to parse cache file as GPX 10
          parser = new GPX10Parser(listId);
          caches = parser.parse(zipFile.getInputStream(gpxEntry), progressHandler);
        } catch (ParserException pe) {
          // didn't work -> lets try GPX11
          parser = new GPX11Parser(listId);
          caches = parser.parse(zipFile.getInputStream(gpxEntry), progressHandler);
        }

        final ZipEntry gpxWptsEntry = zipFile.getEntry(getWaypointsFileNameForGpxFileName(gpxName));
        if (gpxWptsEntry != null) {
          Log.i(Settings.tag, "Import GPX waypoint file: " + gpxWptsEntry.getName());
          importStepHandler.sendMessage(
              importStepHandler.obtainMessage(
                  IMPORT_STEP_READ_WPT_FILE,
                  R.string.gpx_import_loading_waypoints,
                  (int) gpxWptsEntry.getSize()));
          caches = parser.parse(zipFile.getInputStream(gpxWptsEntry), progressHandler);
        }

        return caches;
      } finally {
        zipFile.close();
      }
    }
Esempio n. 21
0
  @Test
  public void compressionCanBeSetOnAPerFileBasisAndIsHonoured() throws IOException {
    // Create some input that can be compressed.
    String packageName = getClass().getPackage().getName().replace(".", "/");
    URL sample = Resources.getResource(packageName + "/sample-bytes.properties");
    byte[] input = Resources.toByteArray(sample);

    try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(output)) {
      CustomZipEntry entry = new CustomZipEntry("default");
      // Don't set the compression level. Should be the default.
      out.putNextEntry(entry);
      out.write(input);

      entry = new CustomZipEntry("stored");
      entry.setCompressionLevel(NO_COMPRESSION);
      byte[] bytes = "stored".getBytes();
      entry.setSize(bytes.length);
      entry.setCrc(Hashing.crc32().hashBytes(bytes).padToLong());
      out.putNextEntry(entry);

      out.write(bytes);

      entry = new CustomZipEntry("best");
      entry.setCompressionLevel(BEST_COMPRESSION);
      out.putNextEntry(entry);
      out.write(input);
    }

    try (ZipInputStream in = new ZipInputStream(Files.newInputStream(output))) {
      ZipEntry entry = in.getNextEntry();
      assertEquals("default", entry.getName());
      ByteStreams.copy(in, ByteStreams.nullOutputStream());
      long defaultCompressedSize = entry.getCompressedSize();
      assertNotEquals(entry.getCompressedSize(), entry.getSize());

      entry = in.getNextEntry();
      ByteStreams.copy(in, ByteStreams.nullOutputStream());
      assertEquals("stored", entry.getName());
      assertEquals(entry.getCompressedSize(), entry.getSize());

      entry = in.getNextEntry();
      ByteStreams.copy(in, ByteStreams.nullOutputStream());
      assertEquals("best", entry.getName());
      ByteStreams.copy(in, ByteStreams.nullOutputStream());
      assertThat(entry.getCompressedSize(), lessThan(defaultCompressedSize));
    }
  }
 public PackerItem(final ZipEntry zipEntry) {
   this.isDirectory = zipEntry.isDirectory();
   this.name = zipEntry.getName();
   this.compressedSize = zipEntry.getCompressedSize();
   this.size = zipEntry.getSize();
   this.time = zipEntry.getTime();
   this.compression = Integer.MIN_VALUE;
 }
Esempio n. 23
0
 public long UnpackSize() {
   long size = 0;
   for (String path : paths) {
     ZipEntry entry = zipfile.getEntry(path);
     if (entry != null) size += entry.getSize();
   }
   return size;
 }
Esempio n. 24
0
  /**
   * Finds and loads all classes that derive from a given set of super classes.
   *
   * <p>As a side-effect this will load and cache most, if not all, classes in the input JAR file.
   *
   * @param packageFilter Base name of package of classes to find. Use an empty string to find
   *     everyting.
   * @param superClasses The super classes of all the classes to find.
   * @return An hash map which keys are the super classes looked for and which values are ArrayList
   *     of the classes found. The array lists are always created for all the valid keys, they are
   *     simply empty if no deriving class is found for a given super class.
   * @throws IOException
   * @throws InvalidAttributeValueException
   * @throws ClassFormatError
   */
  @Override
  public HashMap<String, ArrayList<IClassDescriptor>> findClassesDerivingFrom(
      String packageFilter, String[] superClasses)
      throws IOException, InvalidAttributeValueException, ClassFormatError {

    packageFilter = packageFilter.replaceAll("\\.", "/"); // $NON-NLS-1$ //$NON-NLS-2$

    HashMap<String, ArrayList<IClassDescriptor>> mClassesFound =
        new HashMap<String, ArrayList<IClassDescriptor>>();

    for (String className : superClasses) {
      mClassesFound.put(className, new ArrayList<IClassDescriptor>());
    }

    // create streams to read the intermediary archive
    FileInputStream fis = new FileInputStream(mOsFrameworkLocation);
    ZipInputStream zis = new ZipInputStream(fis);
    ZipEntry entry;
    while ((entry = zis.getNextEntry()) != null) {
      // get the name of the entry and convert to a class binary name
      String entryPath = entry.getName();
      if (!entryPath.endsWith(AdtConstants.DOT_CLASS)) {
        // only accept class files
        continue;
      }
      if (packageFilter.length() > 0 && !entryPath.startsWith(packageFilter)) {
        // only accept stuff from the requested root package.
        continue;
      }
      String className = entryPathToClassName(entryPath);

      Class<?> loaded_class = mClassCache.get(className);
      if (loaded_class == null) {
        byte[] data = mEntryCache.get(className);
        if (data == null) {
          // Get the class and cache it
          long entrySize = entry.getSize();
          if (entrySize > Integer.MAX_VALUE) {
            throw new InvalidAttributeValueException();
          }
          data = readZipData(zis, (int) entrySize);
        }
        loaded_class = defineAndCacheClass(className, data);
      }

      for (Class<?> superClass = loaded_class.getSuperclass();
          superClass != null;
          superClass = superClass.getSuperclass()) {
        String superName = superClass.getCanonicalName();
        if (mClassesFound.containsKey(superName)) {
          mClassesFound.get(superName).add(new ClassWrapper(loaded_class));
          break;
        }
      }
    }

    return mClassesFound;
  }
Esempio n. 25
0
 private void useFileName() {
   try {
     ZipFile zf = new ZipFile(jarFileName);
     Enumeration e = zf.entries();
     while (e.hasMoreElements()) {
       ZipEntry ze = (ZipEntry) e.nextElement();
       dump(ze);
       htSizes.put(ze.getName(), new Integer((int) ze.getSize()));
     }
     zf.close();
     FileInputStream fis = new FileInputStream(jarFileName);
     BufferedInputStream bis = new BufferedInputStream(fis);
     ZipInputStream zis = new ZipInputStream(bis);
     ZipEntry ze = null;
     while ((ze = zis.getNextEntry()) != null) {
       if (ze.isDirectory()) {
         continue;
       }
       dump(ze);
       int size = (int) ze.getSize();
       if (size == -1) {
         size = ((Integer) htSizes.get(ze.getName())).intValue();
       }
       byte[] b = new byte[(int) size];
       int rb = 0;
       int chunk = 0;
       while (((int) size - rb) > 0) {
         chunk = zis.read(b, rb, (int) size - rb);
         if (chunk == -1) {
           break;
         }
         rb += chunk;
       }
       htJarContents.put(ze.getName(), b);
       dump(ze, rb, size);
     }
     zis.close();
   } catch (NullPointerException e) {
     e.printStackTrace();
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Esempio n. 26
0
 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();
   }
 }
Esempio n. 27
0
  public static File unzipByteArrayIntoDirectory(byte[] input, File directory, boolean overwrite) {
    try {
      if (!directory.exists()) {
        directory.mkdirs();
        directory.mkdir();
        if (!directory.exists()) {
          throw new IllegalStateException("could not create directory " + directory);
        }
      } else {
        if (!overwrite) {
          throw new IllegalStateException(
              "overwrite is false and file " + directory + " does exist");
        } else if (!directory.isDirectory()) {
          throw new IllegalArgumentException("file " + directory + " is NOT an directory");
        }
      }

      long start = System.currentTimeMillis();
      ByteArrayInputStream bos = new ByteArrayInputStream(input);
      ZipInputStream in = new ZipInputStream(bos);
      ZipEntry entry = null;
      while ((entry = in.getNextEntry()) != null) {

        String oriName = entry.getName();
        String filename = directory.getAbsolutePath() + File.separator + oriName;

        if (entry.isDirectory()) {
          if (log.isDebugEnabled()) log.debug("creating directory " + oriName);

          File f = new File(filename);
          f.mkdirs();
          f.mkdir();

        } else {
          int uncompressedSize = (int) entry.getSize();

          if (uncompressedSize > -1) {
            byte[] b = new byte[uncompressedSize];
            in.read(b);
            FileOutputStream fis = new FileOutputStream(filename);
            fis.write(b);
            fis.flush();
            fis.close();

            if (log.isDebugEnabled()) log.debug("unzipped entry " + filename);
          }
        }
        long end1 = System.currentTimeMillis();
      }
      long end = System.currentTimeMillis();
      if (log.isDebugEnabled()) log.debug("whole decompression took " + (end - start));
      return directory;
    } catch (IOException e) {
      return null;
    }
  }
Esempio n. 28
0
 /** 通过流的方法暂时不可用---此处只作保留 */
 private void useStream() {
   try {
     ZipInputStream ztop = new ZipInputStream(stream1);
     ZipEntry ztmp = null;
     while ((ztmp = ztop.getNextEntry()) != null) {
       dump(ztmp);
       htSizes.put(ztmp.getName(), new Integer((int) ztmp.getSize()));
     }
     ztop.close();
     BufferedInputStream bis = new BufferedInputStream(stream2);
     ZipInputStream zis = new ZipInputStream(bis);
     ZipEntry ze = null;
     while ((ze = zis.getNextEntry()) != null) {
       if (ze.isDirectory()) {
         continue;
       }
       dump(ze);
       int size = (int) ze.getSize();
       if (size == -1) {
         size = ((Integer) htSizes.get(ze.getName())).intValue();
       }
       System.out.println("size--->" + size);
       byte[] b = new byte[(int) size];
       int rb = 0;
       int chunk = 0;
       while (((int) size - rb) > 0) {
         chunk = zis.read(b, rb, (int) size - rb);
         if (chunk == -1) {
           break;
         }
         rb += chunk;
       }
       htJarContents.put(ze.getName(), b);
       dump(ze);
     }
   } catch (NullPointerException e) {
     e.printStackTrace();
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Esempio n. 29
0
  public AesZipEntry(ZipEntry zipEntry) {
    super(zipEntry.getName());
    super.setMethod(zipEntry.getMethod());
    super.setSize(zipEntry.getSize());
    super.setCompressedSize(zipEntry.getCompressedSize() + 28);
    super.setTime(zipEntry.getTime());

    flag |= 1; // bit0 - encrypted
    // flag |= 8;  // bit3 - use data descriptor
  }
Esempio n. 30
0
 /** @see java.net.URLConnection#getContentLength() */
 @Override
 public int getContentLength() {
   if (connected) {
     if (directAccess != null) return (int) directAccess.length();
     if (zipFile != null && nameEntries != null && nameEntries.size() == 1) {
       ZipEntry entry = zipFile.getEntry(nameEntries.get(0));
       if (entry != null) return (int) entry.getSize();
     }
   }
   return -1;
 }