Ejemplo n.º 1
0
 public static void main(final String[] args) throws IOException {
   File f = new File("pokus.zip");
   //    ZipFile zf = new ZipFile(f, ZipFile.OPEN_READ);
   //    ZipFile zf = new ZipFile(f, ZipFile.OPEN_READ | ZipFile.OPEN_DELETE);
   ZipFile zf = new ZipFile(f, ZipFile.OPEN_DELETE);
   System.out.println("pocet zapakovanych polozek: " + zf.size());
 }
Ejemplo n.º 2
0
  protected void execute() throws ArchiverException {
    getLogger().info("Expanding: " + getSourceFile() + " into " + getDestDirectory());
    ZipFile zf = null;
    try {
      zf = new ZipFile(getSourceFile(), encoding);
      Enumeration e = zf.getEntries();
      while (e.hasMoreElements()) {
        ZipEntry ze = (ZipEntry) e.nextElement();
        extractFileIfIncluded(
            getSourceFile(),
            getDestDirectory(),
            zf.getInputStream(ze),
            ze.getName(),
            new Date(ze.getTime()),
            ze.isDirectory(),
            null);
      }

      getLogger().debug("expand complete");
    } catch (IOException ioe) {
      throw new ArchiverException(
          "Error while expanding " + getSourceFile().getAbsolutePath(), ioe);
    } finally {
      if (zf != null) {
        try {
          zf.close();
        } catch (IOException e) {
          // ignore
        }
      }
    }
  }
  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());
    }
  }
  protected void load(String filename) {
    Logger.getLogger(getClass()).debug("Starting group in file " + filename);

    ZipFile zipfile = null;
    try {
      zipfile = new ZipFile(filename);

      fireBeginGroup(filename, zipfile.size());

      Logger.getLogger(getClass()).debug("Loading ZipFile " + filename);
      load(zipfile);
      Logger.getLogger(getClass()).debug("Loaded ZipFile " + filename);

      fireEndGroup(filename);
    } catch (IOException ex) {
      Logger.getLogger(getClass()).error("Cannot load Zip file \"" + filename + "\"", ex);
    } finally {
      if (zipfile != null) {
        try {
          zipfile.close();
        } catch (IOException ex) {
          // Ignore
        }
      }
    }
  }
Ejemplo n.º 5
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());
      }
    }
  }
Ejemplo n.º 6
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;
  }
  /**
   * @param garFile GAR file.
   * @param hasDescr Whether GAR file has descriptor.
   * @throws IOException If GAR file is not found.
   * @return Whether GAR file structure is correct.
   */
  private boolean checkStructure(File garFile, boolean hasDescr) throws IOException {
    ZipFile zip = new ZipFile(garFile);

    String descr = "META-INF/ignite.xml";

    ZipEntry entry = zip.getEntry(descr);

    if (entry == null && !hasDescr) {
      if (log().isInfoEnabled()) {
        log()
            .info(
                "Process deployment without descriptor file [path="
                    + descr
                    + ", file="
                    + garFile.getAbsolutePath()
                    + ']');
      }

      return true;
    } else if (entry != null && hasDescr) {
      InputStream in = null;

      try {
        in = new BufferedInputStream(zip.getInputStream(entry));

        return true;
      } finally {
        U.close(in, log());
      }
    } else return false;
  }
Ejemplo n.º 8
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();
    }
  }
Ejemplo n.º 9
0
  private void parseJars(String[] files) throws IOException {
    if (files == null) {
      return;
    }

    String currentJar = null;

    for (String file : files) {
      currentJar = file;

      try (ZipFile zrf = new ZipFile(currentJar.replace('/', File.separatorChar))) {
        Enumeration<? extends ZipEntry> entries = zrf.entries();

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

          String fileName = entry.getName();

          if (fileName.equals("META-INF/")
              || fileName.equals(INDEX_NAME)
              || fileName.equals(JarFile.MANIFEST_NAME)) {
            continue;
          }

          if (!metaInfFilenames || !fileName.startsWith("META-INF/")) {
            add(fileName, currentJar);
          } else if (!entry.isDirectory()) {
            addMapping(fileName, currentJar);
          }
        }
      }
    }
  }
Ejemplo n.º 10
0
  protected void execute(String path, File outputDirectory) throws ArchiverException {
    ZipFile zipFile = null;

    try {
      zipFile = new ZipFile(getSourceFile(), encoding);

      Enumeration e = zipFile.getEntries();

      while (e.hasMoreElements()) {
        ZipEntry ze = (ZipEntry) e.nextElement();

        if (ze.getName().startsWith(path)) {
          extractFileIfIncluded(
              getSourceFile(),
              outputDirectory,
              zipFile.getInputStream(ze),
              ze.getName(),
              new Date(ze.getTime()),
              ze.isDirectory(),
              null);
        }
      }
    } catch (IOException ioe) {
      throw new ArchiverException(
          "Error while expanding " + getSourceFile().getAbsolutePath(), ioe);
    } finally {
      if (zipFile != null) {
        try {
          zipFile.close();
        } catch (IOException e) {
          // ignore
        }
      }
    }
  }
Ejemplo n.º 11
0
 private void deflate(String tmpDir, String path) {
   String tmpFile = "tmp-" + Utils.timestamp() + ".zip";
   try {
     ZipFile zipFile = new ZipFile(tmpFile);
     ZipParameters parameters = new ZipParameters();
     parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
     parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
     parameters.setIncludeRootFolder(false);
     zipFile.addFolder(tmpDir, parameters);
   } catch (Exception e) {
     e.printStackTrace();
     return;
   }
   File from = null;
   File to = null;
   try {
     File target = new File(path);
     if (target.exists()) FileUtils.forceDelete(target);
     from = new File(tmpFile);
     to = new File(path);
     FileUtils.moveFile(from, to);
   } catch (IOException e) {
     Utils.onError(new Error.FileMove(tmpFile, path));
   }
   try {
     FileUtils.deleteDirectory(new File(tmpDir));
   } catch (IOException e) {
     Utils.log("can't delete temporary folder");
   }
 }
Ejemplo n.º 12
0
 /** Lists contents of JAR file, via ZipFile. */
 void list(String fname, String files[]) throws IOException {
   ZipFile zf = new ZipFile(fname);
   Enumeration<? extends ZipEntry> zes = zf.entries();
   while (zes.hasMoreElements()) {
     printEntry(zes.nextElement(), files);
   }
   zf.close();
 }
Ejemplo n.º 13
0
  public static void main(String[] args) throws Exception {
    Reader trainingFile = null;

    // Process arguments
    int restArgs = commandOptions.processOptions(args);

    // Check arguments
    if (restArgs != args.length) {
      commandOptions.printUsage(true);
      throw new IllegalArgumentException("Unexpected arg " + args[restArgs]);
    }
    if (trainFileOption.value == null) {
      commandOptions.printUsage(true);
      throw new IllegalArgumentException("Expected --train-file FILE");
    }
    if (modelFileOption.value == null) {
      commandOptions.printUsage(true);
      throw new IllegalArgumentException("Expected --model-file FILE");
    }

    // Get the CRF structure specification.
    ZipFile zipFile = new ZipFile(modelFileOption.value);
    ZipEntry zipEntry = zipFile.getEntry("crf-info.xml");
    CRFInfo crfInfo = new CRFInfo(zipFile.getInputStream(zipEntry));

    StringBuffer crfInfoBuffer = new StringBuffer();
    BufferedReader reader =
        new BufferedReader(new InputStreamReader(zipFile.getInputStream(zipEntry)));
    String line;
    while ((line = reader.readLine()) != null) {
      crfInfoBuffer.append(line).append('\n');
    }
    reader.close();

    // Create the CRF, and train it.
    CRF4 crf = createCRF(trainFileOption.value, crfInfo);

    // Create a new zip file for our output.  This will overwrite
    // the file we used for input.
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(modelFileOption.value));

    // Copy the CRF info xml to the output zip file.
    zos.putNextEntry(new ZipEntry("crf-info.xml"));
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(zos));
    writer.write(crfInfoBuffer.toString());
    writer.flush();
    zos.closeEntry();

    // Save the CRF classifier model to the output zip file.
    zos.putNextEntry(new ZipEntry("crf-model.ser"));
    ObjectOutputStream oos = new ObjectOutputStream(zos);
    oos.writeObject(crf);
    oos.flush();
    zos.closeEntry();
    zos.close();
  }
Ejemplo n.º 14
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) {
        }
      }
    }
  }
Ejemplo n.º 15
0
  public static void main(String[] args) {
    try {
      ZipFile zipFile = new ZipFile(testDirName + zipFileName);
      ZipEntry ze = zipFile.getEntry(zipEntryName);
      byte[] digest1 = getZipDigest(zipFile, ze, true);
      System.out.println("Digest1: " + Base64Util.encode(digest1));
      byte[] digest2 = getZipDigest(zipFile, ze, false);
      System.out.println("Digest2: " + Base64Util.encode(digest2));

    } catch (Exception ex) {
      System.out.println("Error: " + ex.toString());
      ex.printStackTrace(System.out);
    }
  }
 public static void main(String[] args) throws Exception {
   int iterations = 0;
   File zFile1 = new File(System.getProperty("test.src", "."), "pkware123456789012345.zip");
   while (iterations < 2500) {
     ZipFile zipFile = new ZipFile(zFile1);
     List entries = Collections.list(zipFile.entries());
     for (Iterator it = entries.iterator(); it.hasNext(); ) {
       ZipEntry zipEntry = (ZipEntry) it.next();
       InputStream in = zipFile.getInputStream(zipEntry);
       in.close();
     }
     iterations++;
   }
 }
Ejemplo n.º 17
0
 // 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;
 }
    /**
     * Get an input stream for a resource contained in the jar file
     *
     * @param name file name of the resource within the jar file
     * @return an input stream representing the resouce if it exists or null
     */
    public InputStream getResourceAsStream(String name) {

      if (zfile == null || hasChanged()) {
        update();
      }
      try {
        if (zfile == null) return null;
        ZipEntry e = zfile.getEntry(name);
        if (e != null) return zfile.getInputStream(e);
      } catch (Exception e) {
        if (verbose)
          System.err.println("RJavaClassLoader$UnixJarFile: exception: " + e.getMessage());
      }
      return null;
    }
Ejemplo n.º 19
0
  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()]);
  }
Ejemplo n.º 20
0
 private String inflate(String path) {
   if (!new File(path).canRead()) {
     Utils.onError(new Error.FileRead(path));
     return null;
   }
   String tmpDir = "tmp-" + Utils.timestamp();
   try {
     ZipFile zipFile = new ZipFile(path);
     zipFile.extractAll(tmpDir);
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   }
   return tmpDir;
 }
  /*
   * Internal constructor.  Creates a new ZipEntry by reading the
   * Central Directory Entry (CDE) from "in", which must be positioned
   * at the CDE signature.
   *
   * On exit, "in" will be positioned at the start of the next entry
   * in the Central Directory.
   */
  ZipEntry(byte[] cdeHdrBuf, InputStream cdStream) throws IOException {
    Streams.readFully(cdStream, cdeHdrBuf, 0, cdeHdrBuf.length);

    BufferIterator it =
        HeapBufferIterator.iterator(cdeHdrBuf, 0, cdeHdrBuf.length, ByteOrder.LITTLE_ENDIAN);

    int sig = it.readInt();
    if (sig != CENSIG) {
      ZipFile.throwZipException("Central Directory Entry", sig);
    }

    it.seek(8);
    int gpbf = it.readShort() & 0xffff;

    if ((gpbf & ZipFile.GPBF_UNSUPPORTED_MASK) != 0) {
      throw new ZipException("Invalid General Purpose Bit Flag: " + gpbf);
    }

    compressionMethod = it.readShort() & 0xffff;
    time = it.readShort() & 0xffff;
    modDate = it.readShort() & 0xffff;

    // These are 32-bit values in the file, but 64-bit fields in this object.
    crc = ((long) it.readInt()) & 0xffffffffL;
    compressedSize = ((long) it.readInt()) & 0xffffffffL;
    size = ((long) it.readInt()) & 0xffffffffL;

    nameLength = it.readShort() & 0xffff;
    int extraLength = it.readShort() & 0xffff;
    int commentByteCount = it.readShort() & 0xffff;

    // This is a 32-bit value in the file, but a 64-bit field in this object.
    it.seek(42);
    localHeaderRelOffset = ((long) it.readInt()) & 0xffffffffL;

    byte[] nameBytes = new byte[nameLength];
    Streams.readFully(cdStream, nameBytes, 0, nameBytes.length);
    if (containsNulByte(nameBytes)) {
      throw new ZipException("Filename contains NUL byte: " + Arrays.toString(nameBytes));
    }
    name = new String(nameBytes, 0, nameBytes.length, StandardCharsets.UTF_8);

    if (extraLength > 0) {
      extra = new byte[extraLength];
      Streams.readFully(cdStream, extra, 0, extraLength);
    }

    // The RI has always assumed UTF-8. (If GPBF_UTF8_FLAG isn't set, the encoding is
    // actually IBM-437.)
    if (commentByteCount > 0) {
      byte[] commentBytes = new byte[commentByteCount];
      Streams.readFully(cdStream, commentBytes, 0, commentByteCount);
      comment = new String(commentBytes, 0, commentBytes.length, StandardCharsets.UTF_8);
    }
  }
Ejemplo n.º 22
0
  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);
      }
    }
  }
    /* @Override */
    public void update() {
      try {
        if (zfile != null) {
          zfile.close();
        }
        zfile = new ZipFile(this);
      } catch (Exception tryCloseX) {
      }

      /* time stamp */
      super.update();
    }
Ejemplo n.º 24
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();
      }
    }
Ejemplo n.º 25
0
 /** Extracts specified entries from JAR file, via ZipFile. */
 void extract(String fname, String files[]) throws IOException {
   ZipFile zf = new ZipFile(fname);
   Set<ZipEntry> dirs = newDirSet();
   Enumeration<? extends ZipEntry> zes = zf.entries();
   while (zes.hasMoreElements()) {
     ZipEntry e = zes.nextElement();
     InputStream is;
     if (files == null) {
       dirs.add(extractFile(zf.getInputStream(e), e));
     } else {
       String name = e.getName();
       for (String file : files) {
         if (name.startsWith(file)) {
           dirs.add(extractFile(zf.getInputStream(e), e));
           break;
         }
       }
     }
   }
   zf.close();
   updateLastModifiedTime(dirs);
 }
Ejemplo n.º 26
0
 /**
  * Unzips the transferred file. Returns <code>true</code> if the unzip was successful, and <code>
  * false</code> otherwise. In case of failure, this method handles setting an appropriate
  * response.
  */
 private boolean completeUnzip(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException {
   IPath destPath = new Path(getPath());
   try {
     ZipFile source = new ZipFile(new File(getStorageDirectory(), FILE_DATA));
     IFileStore destinationRoot = NewFileServlet.getFileStore(destPath);
     Enumeration<? extends ZipEntry> entries = source.entries();
     while (entries.hasMoreElements()) {
       ZipEntry entry = entries.nextElement();
       IFileStore destination = destinationRoot.getChild(entry.getName());
       if (entry.isDirectory()) destination.mkdir(EFS.NONE, null);
       else {
         destination.getParent().mkdir(EFS.NONE, null);
         IOUtilities.pipe(
             source.getInputStream(entry),
             destination.openOutputStream(EFS.NONE, null),
             false,
             true);
       }
     }
     source.close();
   } catch (ZipException e) {
     // zip exception implies client sent us invalid input
     String msg = NLS.bind("Failed to complete file transfer on {0}", destPath.toString());
     statusHandler.handleRequest(
         req, resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, e));
     return false;
   } catch (Exception e) {
     // other failures should be considered server errors
     String msg = NLS.bind("Failed to complete file transfer on {0}", destPath.toString());
     statusHandler.handleRequest(
         req,
         resp,
         new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
     return false;
   }
   return true;
 }
 /** @see "https://issues.apache.org/jira/browse/COMPRESS-189" */
 @Test
 public void properUseOfInflater() throws Exception {
   ZipFile zf = null;
   ZipArchiveInputStream in = null;
   try {
     zf = new ZipFile(getFile("COMPRESS-189.zip"));
     ZipArchiveEntry zae = zf.getEntry("USD0558682-20080101.ZIP");
     in = new ZipArchiveInputStream(new BufferedInputStream(zf.getInputStream(zae)));
     ZipArchiveEntry innerEntry;
     while ((innerEntry = in.getNextZipEntry()) != null) {
       if (innerEntry.getName().endsWith("XML")) {
         assertTrue(0 < in.read());
       }
     }
   } finally {
     if (zf != null) {
       zf.close();
     }
     if (in != null) {
       in.close();
     }
   }
 }
Ejemplo n.º 28
0
  public static String ExtractZip(String zipName, String outFolder) {
    try {
      File sourceZipFile = new File(zipName);
      File outDirectory = new File(outFolder);
      ZipFile zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);

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

        String currentEntry = entry.getName();
        for (int X = currentEntry.length() - 1; X >= 0; X--) {
          if (currentEntry.charAt(X) == '\\' || currentEntry.charAt(X) == '/') {
            currentEntry = currentEntry.substring(X + 1);
            break;
          }
        }
        File destFile = new File(outDirectory, currentEntry);
        if (destFile.getParentFile() != null) destFile.getParentFile().mkdirs();
        if (!entry.isDirectory()) {
          BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry));
          int currentByte;
          byte data[] = new byte[BUFFER];
          FileOutputStream fos = new FileOutputStream(destFile);
          BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
          while ((currentByte = is.read(data, 0, BUFFER)) != -1) dest.write(data, 0, currentByte);
          dest.flush();
          dest.close();
          is.close();
        }
      }
      zipFile.close();
      return "success";
    } catch (IOException e) {
      return "Failed to extract zip: " + e.toString();
    }
  }
Ejemplo n.º 29
0
 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();
 }
    public URL getResource(String name) {
      if (zfile == null || zfile.getEntry(name) == null) {
        return null;
      }

      URL u = null;
      if (urlPrefix == null) {
        try {
          urlPrefix = "jar:" + toURL().toString() + "!";
        } catch (java.net.MalformedURLException ex) {
        } catch (java.io.IOException ex) {
        }
      }

      try {
        u = new URL(urlPrefix + name);
      } catch (java.net.MalformedURLException ex) {
        /* not to worry */
      }
      return u;
    }