protected void handleArchive(
     File file, String paResourceRootPath, Map<String, byte[]> resourceMap) {
   try {
     ZipFile zipFile = new ZipFile(file);
     Enumeration<? extends ZipEntry> entries = zipFile.entries();
     while (entries.hasMoreElements()) {
       ZipEntry zipEntry = (ZipEntry) entries.nextElement();
       String processFileName = zipEntry.getName();
       if (ProcessApplicationScanningUtil.isDeployable(processFileName)
           && isBelowPath(processFileName, paResourceRootPath)) {
         addResource(
             zipFile.getInputStream(zipEntry), resourceMap, file.getName() + "!", processFileName);
         // find diagram(s) for process
         Enumeration<? extends ZipEntry> entries2 = zipFile.entries();
         while (entries2.hasMoreElements()) {
           ZipEntry zipEntry2 = (ZipEntry) entries2.nextElement();
           String diagramFileName = zipEntry2.getName();
           if (ProcessApplicationScanningUtil.isDiagramForProcess(
               diagramFileName, processFileName)) {
             addResource(
                 zipFile.getInputStream(zipEntry),
                 resourceMap,
                 file.getName() + "!",
                 diagramFileName);
           }
         }
       }
     }
     zipFile.close();
   } catch (IOException e) {
     throw new ProcessEngineException("IOException while scanning archive '" + file + "'.", e);
   }
 }
예제 #2
0
 /**
  * Helper for unzipping downloaded zips
  *
  * @param environment
  * @throws IOException
  */
 private void unzip(Environment environment, ZipFile zipFile, File targetFile, String targetPath)
     throws IOException {
   String baseDirSuffix = null;
   try {
     Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
     if (!zipEntries.hasMoreElements()) {
       logger.error("the zip archive has no entries");
     }
     ZipEntry firstEntry = zipEntries.nextElement();
     if (firstEntry.isDirectory()) {
       baseDirSuffix = firstEntry.getName();
     } else {
       zipEntries = zipFile.entries();
     }
     while (zipEntries.hasMoreElements()) {
       ZipEntry zipEntry = zipEntries.nextElement();
       if (zipEntry.isDirectory()) {
         continue;
       }
       String zipEntryName = zipEntry.getName();
       zipEntryName = zipEntryName.replace('\\', '/');
       if (baseDirSuffix != null && zipEntryName.startsWith(baseDirSuffix)) {
         zipEntryName = zipEntryName.substring(baseDirSuffix.length());
       }
       File target = new File(targetFile, zipEntryName);
       FileSystemUtils.mkdirs(target.getParentFile());
       Streams.copy(zipFile.getInputStream(zipEntry), new FileOutputStream(target));
     }
   } catch (IOException e) {
     logger.error(
         "failed to extract zip ["
             + zipFile.getName()
             + "]: "
             + ExceptionsHelper.detailedMessage(e));
     return;
   } finally {
     try {
       zipFile.close();
     } catch (IOException e) {
       // ignore
     }
   }
   File binFile = new File(targetFile, "bin");
   if (binFile.exists() && binFile.isDirectory()) {
     File toLocation = new File(new File(environment.homeFile(), "bin"), targetPath);
     logger.info("found bin, moving to " + toLocation.getAbsolutePath());
     FileSystemUtils.deleteRecursively(toLocation);
     binFile.renameTo(toLocation);
   }
   if (!new File(targetFile, "_site").exists()) {
     if (!FileSystemUtils.hasExtensions(targetFile, ".class", ".jar")) {
       logger.info("identified as a _site plugin, moving to _site structure ...");
       File site = new File(targetFile, "_site");
       File tmpLocation = new File(environment.pluginsFile(), targetPath + ".tmp");
       targetFile.renameTo(tmpLocation);
       FileSystemUtils.mkdirs(targetFile);
       tmpLocation.renameTo(site);
     }
   }
 }
  /**
   * This method uses puts the new content of the differenceFile into the Jar targetFile, replacing
   * the files as necessary.
   *
   * @param targetFile
   * @param differenceFile - zip containing the files you want to add into the targetFile. This
   *     differenceFile must exsit and have at least 1 entry, or a ZipException will be thrown.
   * @throws ZipException - if a ZIP error has occurred
   * @throws IOException - if an I/O error has occurred
   */
  public static void putDifsInJar(File targetFile, File differenceFile)
      throws ZipException, IOException {
    File temp = new File(targetFile.getAbsolutePath() + ".temp");
    ZipFile sourceZipFile = new ZipFile(targetFile);
    ZipFile diffZipFile = new ZipFile(differenceFile);

    HashMap<String, ZipEntry> map = new HashMap<String, ZipEntry>();
    Enumeration diffEntries = diffZipFile.entries();
    while (diffEntries.hasMoreElements()) {
      ZipEntry entry = (ZipEntry) diffEntries.nextElement();
      map.put(entry.getName(), entry);
    }

    Enumeration sourceEntries = sourceZipFile.entries();
    while (sourceEntries.hasMoreElements()) {
      ZipEntry entry = (ZipEntry) sourceEntries.nextElement();
      if (map.get(entry.getName()) == null) {
        map.put(entry.getName(), entry);
      }
    }

    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(temp));

    Set<Entry<String, ZipEntry>> set = map.entrySet();
    Iterator<Entry<String, ZipEntry>> it = set.iterator();
    while (it.hasNext()) {
      Entry<String, ZipEntry> entry = it.next();
      zos.putNextEntry(entry.getValue());
      InputStream is = null;
      if (diffZipFile.getEntry(entry.getKey()) != null) {
        is = diffZipFile.getInputStream(entry.getValue());
      } else {
        is = sourceZipFile.getInputStream(entry.getValue());
      }
      copyInputStream(is, zos);
      is.close();
    }

    zos.close();
    zos.flush();

    sourceZipFile.close();
    diffZipFile.close();

    FileOutputStream fos = new FileOutputStream(targetFile);
    FileInputStream fis = new FileInputStream(temp);

    copyInputStream(fis, fos);

    fis.close();
    fos.close();

    temp.delete();
    temp.deleteOnExit();
  }
예제 #4
0
  @SuppressWarnings("unchecked")
  public static void unzipArchive(
      Activity activity,
      File archive,
      String outputDir,
      Dialog mDialog,
      final TextView accion,
      final ProgressBar descomprimidos) {

    try {

      ZipFile zipfile = new ZipFile(archive);
      int total_elementos = 0;

      for (Enumeration e = zipfile.entries(); e.hasMoreElements(); ) {
        total_elementos = total_elementos + 1;
        ZipEntry entry = (ZipEntry) e.nextElement();
      }

      descomprimidos.setMax(total_elementos);

      int numero_elemento = 0;
      for (Enumeration e = zipfile.entries(); e.hasMoreElements(); ) {

        class OneShotTask implements Runnable {
          int finalnum;

          OneShotTask(int f) {
            finalnum = f;
          }

          public void run() {
            descomprimidos.setProgress(Integer.valueOf(finalnum));
          }
        }

        new Thread(new OneShotTask(numero_elemento)).start();

        ZipEntry entry = (ZipEntry) e.nextElement();
        numero_elemento = numero_elemento + 1;
        unzipEntry(zipfile, entry, outputDir);
      }

      mDialog.dismiss();

    } catch (Exception e) {
      Log.e("unzipper", "Error while extracting file " + archive);
      Toast.makeText(
              activity, "Error al extraer los datos. Reinicie la aplicaci—n.", Toast.LENGTH_LONG)
          .show();
      archive.delete();
      mDialog.dismiss();
    }
  }
  /**
   * This method calculates the differences between the files inside a Jar file and generates an
   * output file. The output only contains the files that have difference in their CRC.
   *
   * @param olderVersionJar - file to be compared to.
   * @param newerVersionJar - source file of the comparisson.
   * @param outputDestination - path to the file that will contain the differences in those Jars.
   * @throws ZipException - if a ZIP error has occurred
   * @throws IOException - if an I/O error has occurred
   * @return true if the output file was generated AND has at least one entry inside it, false
   *     otherwise.
   */
  private static boolean calculate(
      File olderVersionJar, File newerVersionJar, String outputDestination)
      throws ZipException, IOException {
    ZipFile oldZip = new ZipFile(olderVersionJar);
    ZipFile newZip = new ZipFile(newerVersionJar);
    Enumeration oldEntries = oldZip.entries();
    Enumeration newEntries = newZip.entries();

    HashMap<String, Long> map = new HashMap<String, Long>();
    while (newEntries.hasMoreElements()) {
      ZipEntry entry = (ZipEntry) newEntries.nextElement();
      map.put(entry.getName(), entry.getCrc());
    }

    while (oldEntries.hasMoreElements()) {
      ZipEntry entry = (ZipEntry) oldEntries.nextElement();
      Long l = map.get(entry.getName());
      if (l != null && l.longValue() == entry.getCrc()) {
        map.remove(entry.getName());
      }
    }

    if (!map.isEmpty()) {
      ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outputDestination));

      Set<Entry<String, Long>> set = map.entrySet();
      Iterator<Entry<String, Long>> it = set.iterator();
      while (it.hasNext()) {
        Entry<String, Long> entry = it.next();
        ZipEntry zipEntry = newZip.getEntry(entry.getKey());
        InputStream is = newZip.getInputStream(zipEntry);
        zos.putNextEntry(zipEntry);
        copyInputStream(is, zos);
        zos.closeEntry();
        is.close();
      }

      zos.flush();
      zos.close();
    }

    oldZip.close();
    newZip.close();

    if (map.isEmpty()) {
      return false;
    } else {
      return true;
    }
  }
예제 #6
0
  private static void packageListFromZip(String filename, Hashtable<String, Object> table) {
    try {
      ZipFile file = new ZipFile(filename);
      Enumeration entries = file.entries();
      while (entries.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) entries.nextElement();

        if (!entry.isDirectory()) {
          String name = entry.getName();

          if (name.endsWith(".class")) {
            int slash = name.lastIndexOf('/');
            if (slash == -1) {
              continue;
            }

            String pname = name.substring(0, slash);
            if (table.get(pname) == null) {
              table.put(pname, new Object());
            }
          }
        }
      }
    } catch (IOException e) {
      System.err.println("Ignoring " + filename + " (" + e.getMessage() + ")");
      // e.printStackTrace();
    }
  }
예제 #7
0
 /**
  * Unzip a zip file into a directory.
  *
  * @param zipFile The zip file to be unzipped.
  * @param dest the destination directory.
  * @throws IOException if the destination does not exist or is not a directory, or if the zip file
  *     cannot be extracted.
  */
 public static void unzip(ZipFile zipFile, File dest) throws IOException {
   Enumeration<? extends ZipEntry> entries = zipFile.entries();
   if (dest.exists() && dest.isDirectory()) {
     while (entries.hasMoreElements()) {
       ZipEntry entry = entries.nextElement();
       if (!entry.isDirectory()) {
         File destFile = new File(dest, entry.getName());
         createFileWithPath(destFile);
         InputStream in = new BufferedInputStream(zipFile.getInputStream(entry));
         OutputStream out = new BufferedOutputStream(new FileOutputStream(destFile));
         byte[] buffer = new byte[2048];
         for (; ; ) {
           int nBytes = in.read(buffer);
           if (nBytes <= 0) break;
           out.write(buffer, 0, nBytes);
         }
         out.flush();
         out.close();
         in.close();
       }
     }
   } else {
     throw new IOException(
         "Destination " + dest.getAbsolutePath() + " is not a directory or does not exist");
   }
 }
  private void removePreviousModVersion(String modName, String installedVersion) {
    try {
      // Mod has been previously installed uninstall previous version
      File previousModZip = new File(cacheDir, modName + "-" + installedVersion + ".zip");
      ZipFile zf = new ZipFile(previousModZip);
      Enumeration<? extends ZipEntry> entries = zf.entries();
      // Go through zipfile of previous version and delete all file from
      // Modpack that exist in the zip
      while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        if (entry.isDirectory()) {
          continue;
        }
        File file = new File(GameUpdater.modpackDir, entry.getName());
        Util.log("Deleting '%s'", entry.getName());
        if (file.exists()) {
          // File from mod exists.. delete it
          file.delete();
        }
      }

      InstalledModsYML.removeMod(modName);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  private synchronized void loadArchiveFromFile() {
    String fullArchiveFileName =
        GlobalDefaults.greenhouseDirName
            + System.getProperty("file.separator")
            + archiveFileName
            + ".zip";

    File archiveFile = new File(fullArchiveFileName);
    if (archiveFile.exists()) {
      try {
        ZipFile archiveZip = new ZipFile(fullArchiveFileName);
        Enumeration zipFileEntries = archiveZip.entries();
        while (zipFileEntries.hasMoreElements()) {
          ZipEntry zipEntry = (ZipEntry) zipFileEntries.nextElement();
          BufferedReader zipReader =
              new BufferedReader(new InputStreamReader(archiveZip.getInputStream(zipEntry)));
          String line = null;
          while ((line = zipReader.readLine()) != null) {
            if (line.indexOf(":") > -1) {
              addEntryToArchive(line);
            }
          }
          zipReader.close();
        }
        archiveZip.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
예제 #10
0
 static ArrayList<String> getZipFileEntryNames(ZipFile z) {
   ArrayList<String> out = new ArrayList<String>();
   for (ZipEntry ze : Collections.list(z.entries())) {
     out.add(ze.getName());
   }
   return out;
 }
예제 #11
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());
      }
    }
  }
예제 #12
0
 private static void search(File[] files) {
   try {
     for (File f : files) {
       if (f.isDirectory()) {
         search(f.listFiles());
       } else {
         ZipFile jar = new ZipFile(f);
         Enumeration enumration = jar.entries();
         while (enumration.hasMoreElements()) {
           ZipEntry zipEntry = (ZipEntry) enumration.nextElement();
           InputStreamReader isr = new InputStreamReader(jar.getInputStream(zipEntry));
           BufferedReader br = new BufferedReader(isr);
           String line = br.readLine();
           int line_num = 1;
           while (null != line) {
             // System.out.println(line);
             if (line.toLowerCase().contains(keywords.toLowerCase())) {
               System.out.println(
                   f.getPath() + "," + zipEntry.getName() + "," + "line number = " + line_num);
             }
             line = br.readLine();
             line_num++;
           }
         }
       }
     }
   } catch (ZipException z_e) {
     z_e.printStackTrace();
   } catch (IOException io_e) {
     io_e.printStackTrace();
   }
 }
  /**
   * 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;
  }
예제 #14
0
 public static void unzip(File dest, String jar) throws IOException {
   dest.mkdirs();
   ZipFile zf = new ZipFile(jar);
   try {
     Enumeration es = zf.entries();
     while (es.hasMoreElements()) {
       ZipEntry je = (ZipEntry) es.nextElement();
       String n = je.getName();
       File f = new File(dest, n);
       if (je.isDirectory()) {
         f.mkdirs();
       } else {
         if (f.exists()) {
           f.delete();
         } else {
           f.getParentFile().mkdirs();
         }
         InputStream is = zf.getInputStream(je);
         FileOutputStream os = new FileOutputStream(f);
         try {
           copyStream(is, os);
         } finally {
           os.close();
         }
       }
       long time = je.getTime();
       if (time != -1) f.setLastModified(time);
     }
   } finally {
     zf.close();
   }
 }
예제 #15
0
  private void unzip() throws IOException {
    int BUFFER = 2048;
    BufferedOutputStream dest = null;
    BufferedInputStream is = null;
    ZipEntry entry;
    ZipFile zipfile = new ZipFile("update.zip");
    Enumeration e = zipfile.entries();
    (new File(root)).mkdir();
    while (e.hasMoreElements()) {
      entry = (ZipEntry) e.nextElement();
      output.setText(output.getText() + "\nExtracting: " + entry);
      if (entry.isDirectory()) {
        (new File(root + entry.getName())).mkdir();
      } else {
        (new File(root + entry.getName())).createNewFile();
        is = new BufferedInputStream(zipfile.getInputStream(entry));
        int count;
        byte[] data = new byte[BUFFER];
        FileOutputStream fos = new FileOutputStream(root + entry.getName());
        dest = new BufferedOutputStream(fos, BUFFER);
        while ((count = is.read(data, 0, BUFFER)) != -1) {
          dest.write(data, 0, count);
        }

        dest.flush();
        dest.close();
        is.close();
      }
    }
  }
예제 #16
0
  public static void main(final String[] args) throws IOException {
    DependencyVisitor v = new DependencyVisitor();

    ZipFile f = new ZipFile(args[0]);

    long l1 = System.currentTimeMillis();
    Enumeration<? extends ZipEntry> en = f.entries();
    while (en.hasMoreElements()) {
      ZipEntry e = en.nextElement();
      String name = e.getName();
      if (name.endsWith(".class")) {
        new ClassReader(f.getInputStream(e)).accept(v, 0);
      }
    }
    long l2 = System.currentTimeMillis();

    Map<String, Map<String, Integer>> globals = v.getGlobals();
    Set<String> jarPackages = globals.keySet();
    Set<String> classPackages = v.getPackages();
    int size = classPackages.size();
    System.err.println("time: " + (l2 - l1) / 1000f + "  " + size);

    String[] jarNames = jarPackages.toArray(new String[jarPackages.size()]);
    String[] classNames = classPackages.toArray(new String[classPackages.size()]);
    Arrays.sort(jarNames);
    Arrays.sort(classNames);

    buildDiagram(jarNames, classNames, globals);
  }
예제 #17
0
 public static List<File> unzip(File zip, File toDir) throws IOException {
   ZipFile zf = null;
   List<File> files = null;
   try {
     zf = new ZipFile(zip);
     files = new ArrayList<File>();
     Enumeration<?> entries = zf.entries();
     while (entries.hasMoreElements()) {
       ZipEntry entry = (ZipEntry) entries.nextElement();
       if (entry.isDirectory()) {
         new File(toDir, entry.getName()).mkdirs();
       } else {
         InputStream input = null;
         OutputStream output = null;
         try {
           File f = new File(toDir, entry.getName());
           input = zf.getInputStream(entry);
           output = new FileOutputStream(f);
           copy(input, output);
           files.add(f);
         } finally {
           closeQuietly(output);
           closeQuietly(input);
         }
       }
     }
   } finally {
     if (zf != null) {
       zf.close();
     }
   }
   return files;
 }
예제 #18
0
 /**
  * 解压缩一个文件
  *
  * @param zipFile 压缩文件
  * @param folderPath 文件解压到指定目标路径
  * @throws IOException 当解压缩过程出错时抛出
  */
 public static void upZipFile(File zipFile, String folderPath) throws ZipException, IOException {
   File desDir = new File(folderPath);
   if (!desDir.exists()) {
     desDir.mkdirs();
   }
   ZipFile zf = new ZipFile(zipFile);
   for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements(); ) {
     ZipEntry entry = ((ZipEntry) entries.nextElement());
     InputStream in = zf.getInputStream(entry);
     String str = folderPath + File.separator + entry.getName();
     str = new String(str.getBytes("8859_1"), "GB2312");
     File desFile = new File(str);
     if (!desFile.exists()) {
       File fileParentDir = desFile.getParentFile();
       if (!fileParentDir.exists()) {
         fileParentDir.mkdirs();
       }
       desFile.createNewFile();
     }
     OutputStream out = new FileOutputStream(desFile);
     byte buffer[] = new byte[BUFF_SIZE];
     int realLength;
     while ((realLength = in.read(buffer)) > 0) {
       out.write(buffer, 0, realLength);
     }
     in.close();
     out.close();
   }
 }
예제 #19
0
  public static final boolean unzip(File file, File target) throws MojoExecutionException {
    Enumeration entries;
    ZipFile zipFile;

    display(" --- Extracting ---");

    try {

      zipFile = new ZipFile(file);

      entries = zipFile.entries();

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

        if (entry.isDirectory()) {
          display("       + " + entry.getName());
          File newFolder = new File(target + "/" + entry.getName());
          newFolder.mkdir();
          continue;
        }

        display("         " + entry.getName());
        copyInputStream(
            zipFile.getInputStream(entry),
            new BufferedOutputStream(new FileOutputStream(target + "/" + entry.getName())));
      }

      zipFile.close();
      return true;

    } catch (IOException ioe) {
      throw new MojoExecutionException("Unzip Error", ioe);
    }
  }
  /**
   * Reads a Zip file.
   *
   * @param fl a zip file name
   * @return <code>true</code> if reading a file is successful; <code>false</code> otherwise.
   * @throws IOException if the there was any error reading the file
   */
  private boolean readZipFile(final File fl) throws IOException {
    boolean success = false;
    ZipFile zipFile = null;
    try {
      BufferedReader reader = null;

      // ZipFile offers an Enumeration of all the files in the file
      zipFile = new ZipFile(fl);
      final Enumeration<? extends ZipEntry> e = zipFile.entries();
      while (e.hasMoreElements()) {
        success = false; // reset the value again
        final ZipEntry zipEntry = e.nextElement();

        reader = new BufferedReader(new InputStreamReader(zipFile.getInputStream(zipEntry)));

        // read one line at the time
        int line = 1;
        while (reader.ready()) {
          parseValue(reader.readLine(), line);
          line++;
        }

        reader.close();
        success = true;
      }
    } finally {
      if (zipFile != null) {
        zipFile.close();
      }
    }

    return success;
  }
예제 #21
0
    public Enumeration<? extends ZipEntry> entries() {
      Enumeration<? extends ZipEntry> entries = null;

      if (_zipfile != null) {
        entries = _zipfile.entries();
      } else if (_url != null) {
        try {
          URLConnection con = _url.openConnection();
          con.connect();
          InputStream is = con.getInputStream();
          ZipInputStream zis = new ZipInputStream(is);
          List<ZipEntry> entryList = new ArrayList<ZipEntry>();
          ZipEntry ze;

          while ((ze = zis.getNextEntry()) != null) {
            entryList.add(ze);
          } // end while

          entries = Collections.enumeration(entryList);
        } catch (IOException ex) {
          entries = null;
        }
      } // end if

      return entries;
    }
예제 #22
0
파일: ZipUtil.java 프로젝트: llyloveyh/CDOJ
 /**
  * Unzip the zip file and put all the files in the zip file to the path.
  *
  * <p><strong>WARN:</strong> If the file list can not pass the checker's validation, delete all
  * the contents in the {@code path}, and the {@code path} itself.
  *
  * @param zipFile zipFile object
  * @param path target path
  * @param checker checker to validate ZIP files.
  * @throws AppException if exception occurred, convert them into {@code AppException} object.
  */
 public static void unzipFile(ZipFile zipFile, String path, Checker<File> checker)
     throws AppException {
   try {
     Enumeration<?> enumeration = zipFile.entries();
     while (enumeration.hasMoreElements()) {
       ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();
       if (zipEntry.isDirectory()) {
         if (!new File(path + "/" + zipEntry.getName()).mkdirs()) throw new Exception();
         continue;
       }
       File file = new File(path + "/" + zipEntry.getName());
       File parent = file.getParentFile();
       if (parent != null && !parent.exists()) {
         if (!parent.mkdirs()) throw new AppException();
       }
       FileUtil.saveToFile(zipFile.getInputStream(zipEntry), new FileOutputStream(file));
     }
     zipFile.close();
     File targetFile = new File(path);
     try {
       checker.check(targetFile);
     } catch (AppException e) {
       FileUtil.clearDirectory(targetFile.getAbsolutePath());
       throw e;
     }
   } catch (AppException e) {
     throw e;
   } catch (Exception e) {
     e.printStackTrace();
     throw new AppException("Unzip zip file error.");
   }
 }
 private void addExportedPackages(Set allpackages, ArrayList instructions, File file)
     throws ZipException, IOException {
   if (file.isDirectory()) {
     DirectoryScanner ds = new DirectoryScanner();
     ds.setBasedir(file);
     ds.setIncludes(new String[] {"**"});
     ds.scan();
     String[] files = ds.getIncludedFiles();
     for (int i = 0; i < files.length; i++) {
       String pkg = getPackage(files[i]);
       if (pkg != null && !excluded(instructions, pkg)) {
         allpackages.add(pkg);
       }
     }
   } else {
     ZipFile zip = new ZipFile(file);
     try {
       Enumeration entries = zip.entries();
       while (entries.hasMoreElements()) {
         ZipEntry entry = (ZipEntry) entries.nextElement();
         String pkg = getPackage(entry.getName());
         if (pkg != null && !excluded(instructions, pkg)) {
           allpackages.add(pkg);
         }
       }
     } finally {
       zip.close();
     }
   }
 }
  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());
    }
  }
예제 #25
0
  public static void registerModInJar(String modid, File jar) {
    try {
      ZipFile zipfile = new ZipFile(jar);
      Enumeration enumeration = zipfile.entries();
      while (enumeration.hasMoreElements()) {
        ZipEntry zipentry = (ZipEntry) enumeration.nextElement();
        String fileName = zipentry.getName();
        Path path1 = Paths.get(fileName);
        Path path2 = Paths.get("assets", modid, "books");

        if (path1.startsWith(path2)) {
          try {
            String json = IOUtils.toString(zipfile.getInputStream(zipentry));
            BookData data =
                BookRegistry.register(GsonClientHelper.getGson().fromJson(json, BookData.class));
            ELogger.log(
                Level.INFO,
                "Successfully loaded in the book with the unique identifier: "
                    + data.uniqueName
                    + " for the language: "
                    + data.language);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }

      zipfile.close();
    } catch (Exception e) {
    }
  }
예제 #26
0
  public static List<String> getImportFileNamesFromZip(
      String accountName, List<String> packageNames, String zipFilename) throws ServiceException {

    List<String> result = new ArrayList<String>();

    try {
      if (!new File(zipFilename).exists()) {
        return result;
      }

      ZipFile zipFile = new ZipFile(zipFilename);
      Enumeration<? extends ZipEntry> entries = zipFile.entries();
      while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        InputStream in = zipFile.getInputStream(entry);
        if (isValidFile(accountName, in, packageNames)) {
          result.add(entry.getName());
        }
      }

      zipFile.close();
      return result;
    } catch (IOException e) {
      Log.e(TAG, "Error reading zip file: " + e.getMessage());

      return new ArrayList<String>();
    }
  }
예제 #27
0
  /** @throws IOException */
  @Override
  protected final void setImageZipEntries() throws IOException {
    final File folder = file.getInputFile();
    ZipFile zipFolder = new ZipFile(folder);
    final Enumeration enumeration = zipFolder.entries();
    ZipEntry zipEntry;
    List<ZipEntry> tempSource = new ArrayList<ZipEntry>();
    final Pattern bandFilenamePattern = Pattern.compile("band[\\d]");

    while (enumeration.hasMoreElements()) {
      zipEntry = (ZipEntry) enumeration.nextElement();
      if (bandFilenamePattern
          .matcher(LandsatUtils.getZipEntryFileName(zipEntry).toLowerCase())
          .matches()) {
        tempSource.add(zipEntry);
      }
    }
    Collections.sort(
        tempSource,
        new Comparator<ZipEntry>() {
          public int compare(ZipEntry entry1, ZipEntry entry2) {
            String entry1FileName = LandsatUtils.getZipEntryFileName(entry1);
            String entry2FileName = LandsatUtils.getZipEntryFileName(entry2);
            return entry1FileName.compareTo(entry2FileName);
          }
        });
    imageSources = tempSource.toArray();
  }
  SortedSet<ZipEntry> getPatchFiles() throws IOException {

    SortedSet<ZipEntry> sortedEntries =
        new TreeSet<ZipEntry>(
            new Comparator<ZipEntry>() {
              @Override
              public int compare(ZipEntry a, ZipEntry b) {
                String na = a.getName(), nb = b.getName();
                int s = na.length() - nb.length();
                return s != 0 ? s : na.compareTo(nb);
              }
            });

    File file = new File("swiftdoc-patches.zip");
    if (!file.exists()) file = new File("evaluation/swiftdoc/swiftdoc-patches.zip");

    zipFile = new ZipFile(file);

    Enumeration<? extends ZipEntry> e = zipFile.entries();
    while (e.hasMoreElements()) {
      ZipEntry i = e.nextElement();
      sortedEntries.add(i);
    }
    return sortedEntries;
  }
예제 #29
0
 private void checkLoadedModForPermissionClass(File modFile) {
   try {
     Pattern p = Pattern.compile("permission", Pattern.CASE_INSENSITIVE);
     if (modFile.isDirectory()) {
       for (File file : modFile.listFiles()) {
         checkLoadedModForPermissionClass(file);
       }
     } else if ((modFile.getName().endsWith(".zip")) || (modFile.getName().endsWith(".jar"))) {
       ZipFile zip = new ZipFile(modFile);
       Enumeration entries = zip.entries();
       while (entries.hasMoreElements()) {
         ZipEntry zipentry = (ZipEntry) entries.nextElement();
         if (zipentry != null
             && zipentry.getName().endsWith(".class")
             && p.matcher(zipentry.getName()).find()) {
           checkLoadedClass(zip.getInputStream(zipentry));
         }
       }
       zip.close();
     } else if (modFile.getName().endsWith(".class") && p.matcher(modFile.getName()).find()) {
       checkLoadedClass(new FileInputStream(modFile));
     }
   } catch (IOException e) {
   }
 }
예제 #30
0
파일: ZipUtility.java 프로젝트: ranvirp/Bw
  public static final void unzip(File zip, File extractTo) throws IOException {
    ZipFile archive = new ZipFile(zip);
    Enumeration e = archive.entries();
    while (e.hasMoreElements()) {
      ZipEntry entry = (ZipEntry) e.nextElement();
      File file = new File(extractTo, entry.getName());
      if (entry.isDirectory() && !file.exists()) {
        file.mkdirs();
      } else {
        if (!file.getParentFile().exists()) {
          file.getParentFile().mkdirs();
        }

        InputStream in = archive.getInputStream(entry);
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));

        byte[] buffer = new byte[8192];
        int read;

        while (-1 != (read = in.read(buffer))) {
          out.write(buffer, 0, read);
        }

        in.close();
        out.close();
      }
    }
  }