コード例 #1
0
  protected void unpackComponents() throws IOException, FileNotFoundException {
    File applicationPackage = new File(getApplication().getPackageResourcePath());
    File componentsDir = new File(sGREDir, "components");
    if (componentsDir.lastModified() == applicationPackage.lastModified()) return;

    componentsDir.mkdir();
    componentsDir.setLastModified(applicationPackage.lastModified());

    GeckoAppShell.killAnyZombies();

    ZipFile zip = new ZipFile(applicationPackage);

    byte[] buf = new byte[32768];
    try {
      if (unpackFile(zip, buf, null, "removed-files")) removeFiles();
    } catch (Exception ex) {
      // This file may not be there, so just log any errors and move on
      Log.w(LOG_FILE_NAME, "error removing files", ex);
    }

    // copy any .xpi file into an extensions/ directory
    Enumeration<? extends ZipEntry> zipEntries = zip.entries();
    while (zipEntries.hasMoreElements()) {
      ZipEntry entry = zipEntries.nextElement();
      if (entry.getName().startsWith("extensions/") && entry.getName().endsWith(".xpi")) {
        Log.i("GeckoAppJava", "installing extension : " + entry.getName());
        unpackFile(zip, buf, entry, entry.getName());
      }
    }
  }
コード例 #2
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;
  }
コード例 #3
0
 public InputStream getInputStream(final ZipEntry ze) throws IOException, ZipException {
   if (!(ze instanceof Entry)) {
     return null;
   }
   final OffsetEntry offsetEntry = ((Entry) ze).getOffsetEntry();
   ZipUtil.checkRequestedFeatures(ze);
   final long start = offsetEntry.dataOffset;
   final BoundedInputStream bis = new BoundedInputStream(start, ze.getCompressedSize());
   switch (ze.getMethod()) {
     case 0:
       {
         return bis;
       }
     case 8:
       {
         bis.addDummy();
         final Inflater inflater = new Inflater(true);
         return new InflaterInputStream(bis, inflater) {
           public void close() throws IOException {
             super.close();
             inflater.end();
           }
         };
       }
     default:
       {
         throw new ZipException("Found unsupported compression method " + ze.getMethod());
       }
   }
 }
コード例 #4
0
ファイル: FNArchive.java プロジェクト: Ruritariye/basex
  /**
   * Returns the options of an archive.
   *
   * @param ctx query context
   * @return entries
   * @throws QueryException query exception
   */
  private FElem options(final QueryContext ctx) throws QueryException {
    final B64 archive = (B64) checkType(checkItem(expr[0], ctx), AtomType.B64);
    String format = null;
    int level = -1;

    final ArchiveIn arch = ArchiveIn.get(archive.input(info), info);
    try {
      format = arch.format();
      while (arch.more()) {
        final ZipEntry ze = arch.entry();
        if (ze.isDirectory()) continue;
        level = ze.getMethod();
        break;
      }
    } catch (final IOException ex) {
      Util.debug(ex);
      ARCH_FAIL.thrw(info, ex);
    } finally {
      arch.close();
    }

    // create result element
    final FElem e = new FElem(Q_OPTIONS, NS);
    if (format != null) e.add(new FElem(Q_FORMAT).add(Q_VALUE, format));
    if (level >= 0) {
      final byte[] lvl = level == 8 ? DEFLATE : level == 0 ? STORED : UNKNOWN;
      e.add(new FElem(Q_ALGORITHM).add(Q_VALUE, lvl));
    }
    return e;
  }
コード例 #5
0
ファイル: FNArchive.java プロジェクト: Ruritariye/basex
  /**
   * Extracts entries from the archive.
   *
   * @param ctx query context
   * @return text entries
   * @throws QueryException query exception
   */
  private TokenList extract(final QueryContext ctx) throws QueryException {
    final B64 archive = (B64) checkType(checkItem(expr[0], ctx), AtomType.B64);
    TokenSet hs = null;
    if (expr.length > 1) {
      // filter result to specified entries
      hs = new TokenSet();
      final Iter names = ctx.iter(expr[1]);
      for (Item en; (en = names.next()) != null; ) {
        hs.add(checkElmStr(en).string(info));
      }
    }

    final TokenList tl = new TokenList();
    final ArchiveIn in = ArchiveIn.get(archive.input(info), info);
    try {
      while (in.more()) {
        final ZipEntry ze = in.entry();
        if (ze.isDirectory()) continue;
        if (hs == null || hs.delete(token(ze.getName())) != 0) tl.add(in.read());
      }
    } catch (final IOException ex) {
      Util.debug(ex);
      ARCH_FAIL.thrw(info, ex);
    } finally {
      in.close();
    }
    return tl;
  }
コード例 #6
0
ファイル: FNZipTest.java プロジェクト: godmar/basex
  /**
   * 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();
    }
  }
コード例 #7
0
ファイル: RepositoryImpl.java プロジェクト: snambi/bindex
  /**
   * Parse a repository document.
   *
   * @param url
   * @throws IOException
   * @throws XmlPullParserException
   * @throws Exception
   */
  void parseDocument(URL url) throws IOException, XmlPullParserException, Exception {
    if (!visited.contains(url)) {
      visited.add(url);
      try {
        System.out.println("Visiting: " + url);
        InputStream in = null;

        if (url.getPath().endsWith(".zip")) {
          ZipInputStream zin = new ZipInputStream(url.openStream());
          ZipEntry entry = zin.getNextEntry();
          while (entry != null) {
            if (entry.getName().equals("repository.xml")) {
              in = zin;
              break;
            }
            entry = zin.getNextEntry();
          }
        } else {
          in = url.openStream();
        }
        Reader reader = new InputStreamReader(in);
        XmlPullParser parser = new KXmlParser();
        parser.setInput(reader);
        parseRepository(parser);
      } catch (MalformedURLException e) {
        System.out.println("Cannot create connection to url");
      }
    }
  }
コード例 #8
0
ファイル: ArchiveExtractTo.java プロジェクト: BaseXdb/basex
  @Override
  public Item item(final QueryContext qc, final InputInfo ii) throws QueryException {
    checkCreate(qc);

    final Path path = toPath(0, qc);
    final B64 archive = toB64(exprs[1], qc, false);
    final TokenSet hs = entries(2, qc);

    try (ArchiveIn in = ArchiveIn.get(archive.input(info), info)) {
      while (in.more()) {
        final ZipEntry ze = in.entry();
        final String name = ze.getName();
        if (hs == null || hs.delete(token(name)) != 0) {
          final Path file = path.resolve(name);
          if (ze.isDirectory()) {
            Files.createDirectories(file);
          } else {
            Files.createDirectories(file.getParent());
            Files.write(file, in.read());
          }
        }
      }
    } catch (final IOException ex) {
      throw ARCH_FAIL_X.get(info, ex);
    }
    return null;
  }
コード例 #9
0
ファイル: Main.java プロジェクト: karianna/jdk8_tl
  /** Extracts specified entries from JAR file. */
  void extract(InputStream in, String files[]) throws IOException {
    ZipInputStream zis = new ZipInputStream(in);
    ZipEntry e;
    // Set of all directory entries specified in archive.  Disallows
    // null entries.  Disallows all entries if using pre-6.0 behavior.
    Set<ZipEntry> dirs = newDirSet();
    while ((e = zis.getNextEntry()) != null) {
      if (files == null) {
        dirs.add(extractFile(zis, e));
      } else {
        String name = e.getName();
        for (String file : files) {
          if (name.startsWith(file)) {
            dirs.add(extractFile(zis, e));
            break;
          }
        }
      }
    }

    // Update timestamps of directories specified in archive with their
    // timestamps as given in the archive.  We do this after extraction,
    // instead of during, because creating a file in a directory changes
    // that directory's timestamp.
    updateLastModifiedTime(dirs);
  }
コード例 #10
0
ファイル: Main.java プロジェクト: karianna/jdk8_tl
 /** Creates a new JAR file. */
 void create(OutputStream out, Manifest manifest) throws IOException {
   ZipOutputStream zos = new JarOutputStream(out);
   if (flag0) {
     zos.setMethod(ZipOutputStream.STORED);
   }
   if (manifest != null) {
     if (vflag) {
       output(getMsg("out.added.manifest"));
     }
     ZipEntry e = new ZipEntry(MANIFEST_DIR);
     e.setTime(System.currentTimeMillis());
     e.setSize(0);
     e.setCrc(0);
     zos.putNextEntry(e);
     e = new ZipEntry(MANIFEST_NAME);
     e.setTime(System.currentTimeMillis());
     if (flag0) {
       crc32Manifest(e, manifest);
     }
     zos.putNextEntry(e);
     manifest.write(zos);
     zos.closeEntry();
   }
   for (File file : entries) {
     addFile(zos, file);
   }
   zos.close();
 }
コード例 #11
0
ファイル: Main.java プロジェクト: karianna/jdk8_tl
 void updateLastModifiedTime(Set<ZipEntry> zes) throws IOException {
   for (ZipEntry ze : zes) {
     long lastModified = ze.getTime();
     if (lastModified != -1) {
       File f = new File(ze.getName().replace('/', File.separatorChar));
       f.setLastModified(lastModified);
     }
   }
 }
コード例 #12
0
  public void installFramework(File frameFile, String tag) throws AndrolibException {
    InputStream in = null;
    ZipOutputStream out = null;
    try {
      ZipFile zip = new ZipFile(frameFile);
      ZipEntry entry = zip.getEntry("resources.arsc");

      if (entry == null) {
        throw new AndrolibException("Can't find resources.arsc file");
      }

      in = zip.getInputStream(entry);
      byte[] data = IOUtils.toByteArray(in);

      ARSCData arsc = ARSCDecoder.decode(new ByteArrayInputStream(data), true, true);
      publicizeResources(data, arsc.getFlagsOffsets());

      File outFile =
          new File(
              getFrameworkDir(),
              String.valueOf(arsc.getOnePackage().getId())
                  + (tag == null ? "" : '-' + tag)
                  + ".apk");

      out = new ZipOutputStream(new FileOutputStream(outFile));
      out.setMethod(ZipOutputStream.STORED);
      CRC32 crc = new CRC32();
      crc.update(data);
      entry = new ZipEntry("resources.arsc");
      entry.setSize(data.length);
      entry.setCrc(crc.getValue());
      out.putNextEntry(entry);
      out.write(data);

      LOGGER.info("Framework installed to: " + outFile);
    } catch (ZipException ex) {
      throw new AndrolibException(ex);
    } catch (IOException ex) {
      throw new AndrolibException(ex);
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException ex) {
        }
      }
      if (out != null) {
        try {
          out.close();
        } catch (IOException ex) {
        }
      }
    }
  }
コード例 #13
0
  /**
   * Loop through the ZIP file, copying its entries into a new, temporary ZIP file, skipping the
   * entry to be deleted. Then replace the original file with the new one.
   */
  protected Integer deleteEntry() throws XMLDataStoreException {
    try {
      ZipInputStream inStream = this.buildZipInputStream();
      File outFile = this.buildTempFile();
      ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(outFile));

      byte[] buffer = new byte[32768];
      int inCount = 0;
      int outCount = 0;

      // copy all the entries except the one to be deleted
      ZipEntry entry = inStream.getNextEntry();
      while (entry != null) {
        inCount++;
        if (!this.getZipEntryName().equals(entry.getName())) {
          outCount++;
          outStream.putNextEntry(entry);
          int byteCount;
          while ((byteCount = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, byteCount);
          }
          outStream.closeEntry();
        }
        entry = inStream.getNextEntry();
      }
      inStream.close();
      if (outCount == 0) {
        // add a dummy record to an empty file so we can close it
        // this is required by ZipOutputStream
        outStream.putNextEntry(new ZipEntry("delete.txt"));
        outStream.write(
            "This file is a place-holder. The containing ZIP file should be deleted.".getBytes());
        outStream.closeEntry();
      }
      outStream.close();
      if (outCount == inCount) {
        // no entries were removed - just delete the temp file
        outFile.delete();
      } else {
        // at least one entry removed - delete the original file
        this.getFile().delete();
        if (outCount == 0) {
          // NO entries remain - just delete the temp file too
          outFile.delete();
        } else {
          // entries remain - replace original file with temp file
          outFile.renameTo(this.getFile());
        }
      }
      return new Integer(inCount - outCount); // should be 0 or 1
    } catch (IOException ex) {
      throw XMLDataStoreException.ioException(ex);
    }
  }
コード例 #14
0
  /**
   * Rename the ZIP file to a temporary file, then copy its entries back into the original ZIP file,
   * leaving the stream open and returning it.
   */
  protected Writer buildWriteStream(boolean entryShouldExist) throws XMLDataStoreException {
    try {
      File inFile = this.buildTempFile();
      inFile.delete(); // the file actually gets created - delete it
      boolean renameSucceeded = this.getFile().renameTo(inFile);
      ZipInputStream inStream = this.buildZipInputStream(inFile);
      ZipOutputStream outStream = this.buildZipOutputStream();

      boolean entryActuallyExists = false;
      byte[] buffer = new byte[32768];
      ZipEntry entry = inStream.getNextEntry();
      while (entry != null) {
        boolean weWantToWriteTheEntry = true;
        if (this.getZipEntryName().equals(entry.getName())) {
          entryActuallyExists = true;

          // if we were expecting the entry, skip it;
          // if we were NOT expecting the entry, allow it to be rewritten
          // so the file is restored to its original condition
          if (entryShouldExist) {
            weWantToWriteTheEntry = false;
          }
        }
        if (weWantToWriteTheEntry) {
          outStream.putNextEntry(entry);
          int byteCount;
          while ((byteCount = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, byteCount);
          }
          outStream.closeEntry();
        }
        entry = inStream.getNextEntry();
      }

      // close and delete the temporary file
      inStream.close();
      inFile.delete();
      // check for invalid state
      if (entryShouldExist != entryActuallyExists) {
        outStream.close(); // close it since we will not be returning it
        // need more helpful exceptions here
        if (entryActuallyExists) {
          throw XMLDataStoreException.fileAlreadyExists(new File(this.getZipEntryName()));
        } else {
          throw XMLDataStoreException.fileNotFound(new File(this.getZipEntryName()), null);
        }
      }
      outStream.putNextEntry(new ZipEntry(this.getZipEntryName()));
      return new OutputStreamWriter(outStream);
    } catch (IOException ex) {
      throw XMLDataStoreException.ioException(ex);
    }
  }
コード例 #15
0
ファイル: Main.java プロジェクト: karianna/jdk8_tl
 private void addIndex(JarIndex index, ZipOutputStream zos) throws IOException {
   ZipEntry e = new ZipEntry(INDEX_NAME);
   e.setTime(System.currentTimeMillis());
   if (flag0) {
     CRC32OutputStream os = new CRC32OutputStream();
     index.write(os);
     os.updateEntry(e);
   }
   zos.putNextEntry(e);
   index.write(zos);
   zos.closeEntry();
 }
コード例 #16
0
  /**
   * Puts the uninstaller.
   *
   * @exception Exception Description of the Exception
   */
  private void putUninstaller() throws Exception {
    // Me make the .uninstaller directory
    String dest = translatePath("$INSTALL_PATH") + File.separator + "Uninstaller";
    String jar = dest + File.separator + "uninstaller.jar";
    File pathMaker = new File(dest);
    pathMaker.mkdirs();

    // We log the uninstaller deletion information
    UninstallData udata = UninstallData.getInstance();
    udata.setUninstallerJarFilename(jar);
    udata.setUninstallerPath(dest);

    // We open our final jar file
    FileOutputStream out = new FileOutputStream(jar);
    ZipOutputStream outJar = new ZipOutputStream(out);
    idata.uninstallOutJar = outJar;
    outJar.setLevel(9);
    udata.addFile(jar);

    // We copy the uninstaller
    InputStream in = getClass().getResourceAsStream("/res/IzPack.uninstaller");
    ZipInputStream inRes = new ZipInputStream(in);
    ZipEntry zentry = inRes.getNextEntry();
    while (zentry != null) {
      // Puts a new entry
      outJar.putNextEntry(new ZipEntry(zentry.getName()));

      // Byte to byte copy
      int unc = inRes.read();
      while (unc != -1) {
        outJar.write(unc);
        unc = inRes.read();
      }

      // Next one please
      inRes.closeEntry();
      outJar.closeEntry();
      zentry = inRes.getNextEntry();
    }
    inRes.close();

    // We put the langpack
    in = getClass().getResourceAsStream("/langpacks/" + idata.localeISO3 + ".xml");
    outJar.putNextEntry(new ZipEntry("langpack.xml"));
    int read = in.read();
    while (read != -1) {
      outJar.write(read);
      read = in.read();
    }
    outJar.closeEntry();
  }
コード例 #17
0
ファイル: Main.java プロジェクト: karianna/jdk8_tl
 /** Prints entry information. */
 void printEntry(ZipEntry e) throws IOException {
   if (vflag) {
     StringBuilder sb = new StringBuilder();
     String s = Long.toString(e.getSize());
     for (int i = 6 - s.length(); i > 0; --i) {
       sb.append(' ');
     }
     sb.append(s).append(' ').append(new Date(e.getTime()).toString());
     sb.append(' ').append(e.getName());
     output(sb.toString());
   } else {
     output(e.getName());
   }
 }
コード例 #18
0
ファイル: Installer.java プロジェクト: suever/CTP
 // Take a tree of files starting in a directory in a zip file
 // and copy them to a disk directory, recreating the tree.
 private int unpackZipFile(
     File inZipFile, String directory, String parent, boolean suppressFirstPathElement) {
   int count = 0;
   if (!inZipFile.exists()) return count;
   parent = parent.trim();
   if (!parent.endsWith(File.separator)) parent += File.separator;
   if (!directory.endsWith(File.separator)) directory += File.separator;
   File outFile = null;
   try {
     ZipFile zipFile = new ZipFile(inZipFile);
     Enumeration zipEntries = zipFile.entries();
     while (zipEntries.hasMoreElements()) {
       ZipEntry entry = (ZipEntry) zipEntries.nextElement();
       String name = entry.getName().replace('/', File.separatorChar);
       if (name.startsWith(directory)) {
         if (suppressFirstPathElement) name = name.substring(directory.length());
         outFile = new File(parent + name);
         // Create the directory, just in case
         if (name.indexOf(File.separatorChar) >= 0) {
           String p = name.substring(0, name.lastIndexOf(File.separatorChar) + 1);
           File dirFile = new File(parent + p);
           dirFile.mkdirs();
         }
         if (!entry.isDirectory()) {
           System.out.println("Installing " + outFile);
           // Copy the file
           BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFile));
           BufferedInputStream in = new BufferedInputStream(zipFile.getInputStream(entry));
           int size = 1024;
           int n = 0;
           byte[] b = new byte[size];
           while ((n = in.read(b, 0, size)) != -1) out.write(b, 0, n);
           in.close();
           out.flush();
           out.close();
           // Count the file
           count++;
         }
       }
     }
     zipFile.close();
   } catch (Exception e) {
     System.err.println("...an error occured while installing " + outFile);
     e.printStackTrace();
     System.err.println("Error copying " + outFile.getName() + "\n" + e.getMessage());
     return -count;
   }
   System.out.println(count + " files were installed.");
   return count;
 }
コード例 #19
0
ファイル: Main.java プロジェクト: karianna/jdk8_tl
  /**
   * Extracts next entry from JAR file, creating directories as needed. If the entry is for a
   * directory which doesn't exist prior to this invocation, returns that entry, otherwise returns
   * null.
   */
  ZipEntry extractFile(InputStream is, ZipEntry e) throws IOException {
    ZipEntry rc = null;
    String name = e.getName();
    File f = new File(e.getName().replace('/', File.separatorChar));
    if (e.isDirectory()) {
      if (f.exists()) {
        if (!f.isDirectory()) {
          throw new IOException(formatMsg("error.create.dir", f.getPath()));
        }
      } else {
        if (!f.mkdirs()) {
          throw new IOException(formatMsg("error.create.dir", f.getPath()));
        } else {
          rc = e;
        }
      }

      if (vflag) {
        output(formatMsg("out.create", name));
      }
    } else {
      if (f.getParent() != null) {
        File d = new File(f.getParent());
        if (!d.exists() && !d.mkdirs() || !d.isDirectory()) {
          throw new IOException(formatMsg("error.create.dir", d.getPath()));
        }
      }
      try {
        copy(is, f);
      } finally {
        if (is instanceof ZipInputStream) ((ZipInputStream) is).closeEntry();
        else is.close();
      }
      if (vflag) {
        if (e.getMethod() == ZipEntry.DEFLATED) {
          output(formatMsg("out.inflated", name));
        } else {
          output(formatMsg("out.extracted", name));
        }
      }
    }
    if (!useExtractionTime) {
      long lastModified = e.getTime();
      if (lastModified != -1) {
        f.setLastModified(lastModified);
      }
    }
    return rc;
  }
コード例 #20
0
ファイル: Utils.java プロジェクト: Rongmario/asielauncher
  public static String[] getZipList(String zipFile) throws ZipException, IOException {
    File file = new File(zipFile);
    ZipFile zip = new ZipFile(file);
    Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();
    ArrayList<String> files = new ArrayList<String>();

    // Process each entry
    while (zipFileEntries.hasMoreElements()) {
      // grab a zip file entry
      ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
      String currentEntry = entry.getName();
      files.add(currentEntry);
    }
    return files.toArray(new String[files.size()]);
  }
コード例 #21
0
 /** Return the specified ZIP file entry wrapped in a stream. */
 protected Reader buildReadStream(String readZipEntryName) throws XMLDataStoreException {
   try {
     ZipInputStream inStream = this.buildZipInputStream();
     ZipEntry entry = inStream.getNextEntry();
     while (entry != null) {
       if (readZipEntryName.equals(entry.getName())) {
         return new InputStreamReader(inStream);
       }
       entry = inStream.getNextEntry();
     }
     inStream.close();
   } catch (IOException ex) {
     throw XMLDataStoreException.ioException(ex);
   }
   return null;
 }
コード例 #22
0
ファイル: Test3.java プロジェクト: Krabi/idkaart_public
 private static byte[] getZipDigest(ZipFile zipFile, ZipEntry ze, boolean zip)
     throws ZipException, IOException, Exception {
   System.out.println("z2e: " + ze.toString());
   InputStream is = null;
   if (zip) is = zipFile.getInputStream(ze);
   else is = new FileInputStream(testDirName + ze.toString());
   MessageDigest sha = MessageDigest.getInstance("SHA-1");
   byte[] buf = new byte[1024];
   int count;
   while ((count = is.read(buf)) != -1) {
     System.out.println("Count: " + count);
     sha.update(buf, 0, count);
   }
   is.close();
   return sha.digest();
 }
コード例 #23
0
ファイル: Utils.java プロジェクト: raghavendrabhat/h2o
 public static byte [] unzipBytes(byte [] bs, Compression cmp) {
   InputStream is = null;
   int off = 0;
   try {
     switch(cmp) {
     case NONE: // No compression
       return bs;
     case ZIP: {
       ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(bs));
       ZipEntry ze = zis.getNextEntry(); // Get the *FIRST* entry
       // There is at least one entry in zip file and it is not a directory.
       if( ze != null && !ze.isDirectory() ) {
         is = zis;
         break;
       }
       zis.close();
       return bs; // Don't crash, ignore file if cannot unzip
     }
     case GZIP:
       is = new GZIPInputStream(new ByteArrayInputStream(bs));
       break;
     default:
       assert false:"cmp = " + cmp;
     }
     // If reading from a compressed stream, estimate we can read 2x uncompressed
     assert( is != null ):"is is NULL, cmp = " + cmp;
     bs = new byte[bs.length * 2];
     // Now read from the (possibly compressed) stream
     while( off < bs.length ) {
       int len = is.read(bs, off, bs.length - off);
       if( len < 0 )
         break;
       off += len;
       if( off == bs.length ) { // Dataset is uncompressing alot! Need more space...
         if( bs.length >= ValueArray.CHUNK_SZ )
           break; // Already got enough
         bs = Arrays.copyOf(bs, bs.length * 2);
       }
     }
   } catch( IOException ioe ) { // Stop at any io error
     Log.err(ioe);
   } finally {
     Utils.close(is);
   }
   return bs;
 }
コード例 #24
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();
     }
   }
 }
コード例 #25
0
  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());
    }
  }
コード例 #26
0
ファイル: FNArchive.java プロジェクト: Ruritariye/basex
  /**
   * Adds the specified entry to the output stream.
   *
   * @param entry entry descriptor
   * @param con contents
   * @param out output archive
   * @param level default compression level
   * @throws QueryException query exception
   * @throws IOException I/O exception
   */
  private void add(final Item entry, final Item con, final ArchiveOut out, final int level)
      throws QueryException, IOException {

    // create new zip entry
    final String name = string(entry.string(info));
    if (name.isEmpty()) ARCH_EMPTY.thrw(info);
    final ZipEntry ze = new ZipEntry(name);
    String en = null;

    // compression level
    byte[] lvl = null;
    if (entry instanceof ANode) {
      final ANode el = (ANode) entry;
      lvl = el.attribute(Q_LEVEL);

      // last modified
      final byte[] mod = el.attribute(Q_LAST_MOD);
      if (mod != null) {
        try {
          ze.setTime(new Int(new Dtm(mod, info)).itr());
        } catch (final QueryException qe) {
          ARCH_DATETIME.thrw(info, mod);
        }
      }

      // encoding
      final byte[] enc = el.attribute(Q_ENCODING);
      if (enc != null) {
        en = string(enc);
        if (!Charset.isSupported(en)) ARCH_ENCODING.thrw(info, enc);
      }
    }

    // data to be compressed
    byte[] val = checkStrBin(con);
    if (con instanceof AStr && en != null && en != Token.UTF8) val = encode(val, en);

    try {
      out.level(lvl == null ? level : toInt(lvl));
    } catch (final IllegalArgumentException ex) {
      ARCH_LEVEL.thrw(info, lvl);
    }
    out.write(ze, val);
  }
コード例 #27
0
  /**
   * Zips byte array.
   *
   * @param input Input bytes.
   * @param initBufSize Initial buffer size.
   * @return Zipped byte array.
   * @throws IOException If failed.
   */
  public static byte[] zipBytes(byte[] input, int initBufSize) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream(initBufSize);

    try (ZipOutputStream zos = new ZipOutputStream(bos)) {
      ZipEntry entry = new ZipEntry("");

      try {
        entry.setSize(input.length);

        zos.putNextEntry(entry);

        zos.write(input);
      } finally {
        zos.closeEntry();
      }
    }

    return bos.toByteArray();
  }
コード例 #28
0
ファイル: Main.java プロジェクト: karianna/jdk8_tl
  /** Adds a new file entry to the ZIP output stream. */
  void addFile(ZipOutputStream zos, File file) throws IOException {
    String name = file.getPath();
    boolean isDir = file.isDirectory();
    if (isDir) {
      name = name.endsWith(File.separator) ? name : (name + File.separator);
    }
    name = entryName(name);

    if (name.equals("") || name.equals(".") || name.equals(zname)) {
      return;
    } else if ((name.equals(MANIFEST_DIR) || name.equals(MANIFEST_NAME)) && !Mflag) {
      if (vflag) {
        output(formatMsg("out.ignore.entry", name));
      }
      return;
    }

    long size = isDir ? 0 : file.length();

    if (vflag) {
      out.print(formatMsg("out.adding", name));
    }
    ZipEntry e = new ZipEntry(name);
    e.setTime(file.lastModified());
    if (size == 0) {
      e.setMethod(ZipEntry.STORED);
      e.setSize(0);
      e.setCrc(0);
    } else if (flag0) {
      crc32File(e, file);
    }
    zos.putNextEntry(e);
    if (!isDir) {
      copy(file, zos);
    }
    zos.closeEntry();
    /* report how much compression occurred. */
    if (vflag) {
      size = e.getSize();
      long csize = e.getCompressedSize();
      out.print(formatMsg2("out.size", String.valueOf(size), String.valueOf(csize)));
      if (e.getMethod() == ZipEntry.DEFLATED) {
        long ratio = 0;
        if (size != 0) {
          ratio = ((size - csize) * 100) / size;
        }
        output(formatMsg("out.deflated", String.valueOf(ratio)));
      } else {
        output(getMsg("out.stored"));
      }
    }
  }
コード例 #29
0
ファイル: Utils.java プロジェクト: Rongmario/asielauncher
  public static void extract(String zipFile, String newPath, boolean overwrite)
      throws ZipException, IOException {
    File file = new File(zipFile);

    ZipFile zip = new ZipFile(file);

    new File(newPath).mkdir();
    Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();

    // Process each entry
    while (zipFileEntries.hasMoreElements()) {
      // grab a zip file entry
      ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
      String currentEntry = entry.getName();
      File destFile = new File(newPath, currentEntry);
      // destFile = new File(newPath, destFile.getName());
      File destinationParent = destFile.getParentFile();

      // create the parent directory structure if needed
      destinationParent.mkdirs();

      if (!entry.isDirectory()) {
        if (!overwrite && destFile.exists()) continue;
        BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
        int currentByte;
        // establish buffer for writing file
        byte data[] = new byte[BUFFER];

        // write the current file to disk
        FileOutputStream fos = new FileOutputStream(destFile);
        BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);

        // read and write until last byte is encountered
        while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
          dest.write(data, 0, currentByte);
        }
        close(dest);
        close(is);
      }
    }
  }
コード例 #30
0
    protected void loadAirspacesFromPath(String path, Collection<Airspace> airspaces) {
      File file = ExampleUtil.saveResourceToTempFile(path, ".zip");
      if (file == null) return;

      try {
        ZipFile zipFile = new ZipFile(file);

        ZipEntry entry = null;
        for (Enumeration<? extends ZipEntry> e = zipFile.entries();
            e.hasMoreElements();
            entry = e.nextElement()) {
          if (entry == null) continue;

          String name = WWIO.getFilename(entry.getName());

          if (!(name.startsWith("gov.nasa.worldwind.render.airspaces") && name.endsWith(".xml")))
            continue;

          String[] tokens = name.split("-");

          try {
            Class c = Class.forName(tokens[0]);
            Airspace airspace = (Airspace) c.newInstance();
            BufferedReader input =
                new BufferedReader(new InputStreamReader(zipFile.getInputStream(entry)));
            String s = input.readLine();
            airspace.restoreState(s);
            airspaces.add(airspace);

            if (tokens.length >= 2) {
              airspace.setValue(AVKey.DISPLAY_NAME, tokens[1]);
            }
          } catch (Exception ex) {
            ex.printStackTrace();
          }
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }