Beispiel #1
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");
   }
 }
  /** @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();
  }
  @Test
  public void includeAsClasses() throws Exception {
    String baseDir = testIssue("flexmojos-247").getBasedir();
    File target = new File(baseDir, "target");
    Assert.assertTrue(target.exists());

    File swc = new File(target, "flexmojos-247-1.0-SNAPSHOT.swc");
    Assert.assertTrue(swc.exists());

    String catalog;
    ZipFile zf = new ZipFile(swc);
    try {
      InputStream in = zf.getInputStream(zf.getEntry("catalog.xml"));
      catalog = IOUtils.toString(in);
      in.close();
    } finally {
      zf.close();
    }

    // must have both classes and the uri
    MatcherAssert.assertThat(catalog, StringContains.containsString("AClass"));
    MatcherAssert.assertThat(catalog, StringContains.containsString("BClass"));
    MatcherAssert.assertThat(
        catalog, StringContains.containsString("http://flexmojos.sonatype.org/tests"));
  }
  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) {
    }
  }
Beispiel #5
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;
  }
  @Override
  @Nullable
  Resource getResource(String name, boolean flag) {
    JarMemoryLoader loader = myMemoryLoader != null ? myMemoryLoader.get() : null;
    if (loader != null) {
      Resource resource = loader.getResource(name);
      if (resource != null) return resource;
    }

    try {
      ZipFile zipFile = getZipFile();
      try {
        ZipEntry entry = zipFile.getEntry(name);
        if (entry != null) {
          return MemoryResource.load(getBaseURL(), zipFile, entry, myAttributes);
        }
      } finally {
        releaseZipFile(zipFile);
      }
    } catch (Exception e) {
      error("file: " + myCanonicalFile, e);
    }

    return null;
  }
  private InputStream getInputStreamFromFprFile(File file) throws IOException {
    final ZipFile fprFile = new ZipFile(file);
    try {
      final InputStream reportStream =
          fprFile.getInputStream(fprFile.getEntry(FortifyConstants.AUDIT_FVDL_FILE));
      return new InputStream() {
        @Override
        public int read() throws IOException {
          return reportStream.read();
        }

        @Override
        public void close() throws IOException {
          try {
            reportStream.close();
          } finally {
            fprFile.close();
          }
        }
      };
    } catch (IOException e) {
      fprFile.close();
      throw e;
    }
  }
  public void testCoverageContents() throws Exception {
    final Long processId = issueProcessAndWaitForTermination();

    final String request = RESTLET_PATH + "/" + processId.longValue();

    final MockHttpServletResponse response = getAsServletResponse(request);
    assertEquals(Status.SUCCESS_OK, Status.valueOf(response.getStatus()));
    assertEquals(MediaType.APPLICATION_ZIP, MediaType.valueOf(response.getContentType()));

    final ByteArrayInputStream responseStream = getBinaryInputStream(response);
    File dataDirectoryRoot = super.getTestData().getDataDirectoryRoot();
    File file = new File(dataDirectoryRoot, "testCoverageContents.zip");
    super.getTestData().copyTo(responseStream, file.getName());

    ZipFile zipFile = new ZipFile(file);
    try {
      // TODO: change this expectation once we normalize the raster file name
      String rasterName = RASTER_LAYER.getPrefix() + ":" + RASTER_LAYER.getLocalPart() + ".tiff";
      ZipEntry nextEntry = zipFile.getEntry(rasterName);
      assertNotNull(nextEntry);
      InputStream coverageInputStream = zipFile.getInputStream(nextEntry);
      // Use a file, geotiffreader might not work well reading out of a plain input stream
      File covFile = new File(file.getParentFile(), "coverage.tiff");
      IOUtils.copy(coverageInputStream, covFile);
      GeoTiffReader geoTiffReader = new GeoTiffReader(covFile);
      GridCoverage2D coverage = geoTiffReader.read(null);
      CoordinateReferenceSystem crs = coverage.getCoordinateReferenceSystem();
      assertEquals(CRS.decode("EPSG:4326", true), crs);
    } finally {
      zipFile.close();
    }
  }
  /** @see java.net.URLConnection#connect() */
  @Override
  public void connect() throws IOException {
    this.connected = true;
    String file = url.getFile();
    int index = file.indexOf("!/");
    if (index == -1) {
      // It is a direct file access
      this.directAccess = new File(file);
      if (!directAccess.exists())
        throw new FileNotFoundException("Cannot find the file at " + file);
      if (directAccess.isDirectory()) throw new IOException("A file was expected at " + file);
      return;
    }
    File f = new File(file.substring(0, index));
    if (!f.exists())
      throw new FileNotFoundException("Cannot find the file at " + f.getAbsolutePath());
    if (f.isDirectory()) throw new IOException("A zip file was expected at " + f.getAbsolutePath());
    this.zipFile = new ZipFile(f);
    try {
      int fromIndex = index + 2;
      index = file.indexOf("!/", fromIndex);
      String nameEntry;
      if (index == -1) nameEntry = file.substring(fromIndex);
      else nameEntry = file.substring(fromIndex, index);

      ZipEntry entry = zipFile.getEntry(nameEntry);
      if (entry == null)
        throw new FileNotFoundException(
            "Cannot find the file at " + file.substring(0, index == -1 ? file.length() : index));
      if (zipFile.getEntry(nameEntry + "/") != null)
        throw new IOException(
            "A "
                + (index == -1 ? "" : "zip")
                + " file was expected at "
                + file.substring(0, index == -1 ? file.length() : index));
      nameEntries = new ArrayList<String>();
      nameEntries.add(nameEntry);
      if (index == -1) {
        // there is no more entries
        return;
      }
      nameEntry = file.substring(index + 2);
      // We add it without checking if it exists to avoid reading twice the ZipInputStream
      nameEntries.add(nameEntry);
    } catch (IOException e) {
      try {
        zipFile.close();
      } catch (IOException e2) {
        LOG.debug("Could not close the zip file");
      }
      throw e;
    } catch (RuntimeException e) {
      try {
        zipFile.close();
      } catch (IOException e2) {
        LOG.debug("Could not close the zip file");
      }
      throw e;
    }
  }
 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();
   }
 }
  /*
   * Load a class from a file in an archive.  We currently assume that
   * the file is a Zip archive.
   *
   * Returns null if the class wasn't found.
   */
  private byte[] loadFromArchive(ZipFile zip, String name) {
    ZipEntry entry;

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

    ByteArrayOutputStream byteStream;
    InputStream stream;
    int count;

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

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

    // System.out.println("  loaded from Zip");
    return byteStream.toByteArray();
  }
  @NotNull
  @Override
  public byte[] contentsToByteArray(@NotNull String relativePath) throws IOException {
    FileAccessorCache.Handle<ZipFile> zipRef;

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

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

    throw new FileNotFoundException(getFile() + "!/" + relativePath);
  }
  @NotNull
  private EntryInfo getOrCreate(
      @NotNull String entryName, Map<String, EntryInfo> map, @NotNull ZipFile zip) {
    EntryInfo info = map.get(entryName);

    if (info == null) {
      ZipEntry entry = zip.getEntry(entryName + "/");
      if (entry != null) {
        return getOrCreate(entry, map, zip);
      }

      Pair<String, String> path = splitPath(entryName);
      EntryInfo parentInfo = getOrCreate(path.first, map, zip);
      info =
          store(map, parentInfo, path.second, true, DEFAULT_LENGTH, DEFAULT_TIMESTAMP, entryName);
    }

    if (!info.isDirectory) {
      Logger.getInstance(getClass())
          .info(zip.getName() + ": " + entryName + " should be a directory");
      info = store(map, info.parent, info.shortName, true, info.length, info.timestamp, entryName);
    }

    return info;
  }
Beispiel #14
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());
 }
Beispiel #15
0
  public static Part getBinaryPart(ZipFile zf, ContentTypeManager ctm, String resolvedPartUri)
      throws Docx4JException {

    Part part = null;
    InputStream in = null;
    try {
      in = zf.getInputStream(zf.getEntry(resolvedPartUri));
      part = new BinaryPart(new PartName("/" + resolvedPartUri));

      if (conserveMemory) {
        ((BinaryPart) part).setBinaryDataRef(zf.getName(), resolvedPartUri);
      } else {
        ((BinaryPart) part).setBinaryData(in);
      }

      log.info("Stored as BinaryData");

    } catch (IOException ioe) {
      ioe.printStackTrace();
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException exc) {
          exc.printStackTrace();
        }
      }
    }
    return part;
  }
Beispiel #16
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);
    }
  }
  private boolean installBundle(ZipFile zipFile, String location, Application application) {

    log.info("processLibsBundle entryName " + location);
    this.bundleDebug.installExternalBundle(location);
    String fileNameFromEntryName = Utils.getFileNameFromEntryName(location);
    String packageNameFromEntryName = Utils.getPackageNameFromEntryName(location);
    if (packageNameFromEntryName == null || packageNameFromEntryName.length() <= 0) {
      return false;
    }
    File archvieFile =
        new File(new File(application.getFilesDir().getParentFile(), "lib"), fileNameFromEntryName);
    if (OpenAtlas.getInstance().getBundle(packageNameFromEntryName) != null) {
      return false;
    }
    try {
      if (archvieFile.exists()) {
        OpenAtlas.getInstance().installBundle(packageNameFromEntryName, archvieFile);
      } else {
        OpenAtlas.getInstance()
            .installBundle(
                packageNameFromEntryName, zipFile.getInputStream(zipFile.getEntry(location)));
      }
      log.info("Succeed to install bundle " + packageNameFromEntryName);
      return true;
    } catch (Throwable e) {
      Log.e("BundlesInstaller", "Could not install bundle.", e);
      return false;
    }
  }
Beispiel #18
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();
   }
 }
Beispiel #19
0
  /**
   * overriding getResource() because we want to search FIRST in this ClassLoader, then the parent,
   * the path, etc.
   */
  public URL getResource(String name) {
    try {
      if (jar != null) {
        ZipFile zipFile = jar.getZipFile();
        ZipEntry entry = zipFile.getEntry(name);
        if (entry != null) {
          return new URL(getResourceAsPath(name));
        }
      }

      Object obj = resourcesHash.get(name);
      if (obj instanceof JARClassLoader) {
        JARClassLoader classLoader = (JARClassLoader) obj;
        return classLoader.getResource(name);
      } else {
        URL ret = getSystemResource(name);
        if (ret != null) {
          Log.log(
              Log.DEBUG,
              JARClassLoader.class,
              "Would have returned null for getResource(" + name + ")");
          Log.log(Log.DEBUG, JARClassLoader.class, "returning(" + ret + ")");
        }
        return ret;
      }
    } catch (IOException io) {
      Log.log(Log.ERROR, this, io);
      return null;
    }
  } // }}}
  /**
   * 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;
  }
Beispiel #21
0
 public byte[] getBytes() throws EGLModelException {
   EGLElement pkg = (EGLElement) getParent();
   if (pkg instanceof EglarPackageFragment) {
     EglarPackageFragmentRoot root = (EglarPackageFragmentRoot) pkg.getParent();
     ZipFile zip = null;
     try {
       zip = root.getJar();
       String entryName =
           CharOperation.concatWith(((PackageFragment) pkg).names, getElementName(), '/');
       ZipEntry ze = zip.getEntry(entryName);
       if (ze != null) {
         return org.eclipse.edt.ide.core.internal.model.util.Util.getZipEntryByteContent(ze, zip);
       }
       throw new EGLModelException(
           new EGLModelStatus(IEGLModelStatusConstants.ELEMENT_DOES_NOT_EXIST, this));
     } catch (IOException ioe) {
       throw new EGLModelException(ioe, IEGLModelStatusConstants.IO_EXCEPTION);
     } catch (CoreException e) {
       if (e instanceof EGLModelException) {
         throw (EGLModelException) e;
       } else {
         throw new EGLModelException(e);
       }
     } finally {
       EGLModelManager.getEGLModelManager().closeZipFile(zip);
     }
   } else {
     IFile file = (IFile) getResource();
     return Util.getResourceContentsAsByteArray(file);
   }
 }
Beispiel #22
0
 public Properties searchForVersionProperties() {
   try {
     FMLLog.log(
         getModId(),
         Level.FINE,
         "Attempting to load the file version.properties from %s to locate a version number for %s",
         getSource().getName(),
         getModId());
     Properties version = null;
     if (getSource().isFile()) {
       ZipFile source = new ZipFile(getSource());
       ZipEntry versionFile = source.getEntry("version.properties");
       if (versionFile != null) {
         version = new Properties();
         version.load(source.getInputStream(versionFile));
       }
       source.close();
     } else if (getSource().isDirectory()) {
       File propsFile = new File(getSource(), "version.properties");
       if (propsFile.exists() && propsFile.isFile()) {
         version = new Properties();
         FileInputStream fis = new FileInputStream(propsFile);
         version.load(fis);
         fis.close();
       }
     }
     return version;
   } catch (Exception e) {
     Throwables.propagateIfPossible(e);
     FMLLog.log(getModId(), Level.FINEST, "Failed to find a usable version.properties file");
     return null;
   }
 }
Beispiel #23
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());
      }
    }
  }
  /**
   * extracts class files from jar/zip archive to specified path. See <code>IDecompiler</code>
   * documentation for the format of pareameters.
   */
  public static void extract(
      String archivePath, String packege, String className, boolean inner, String to)
      throws IOException {
    ZipFile archive = new ZipFile(archivePath);
    List entries = findRelevant(archive, packege, className, inner);
    InputStream in = null;
    OutputStream out = null;
    byte[] buffer = new byte[2048];
    ZipEntry entry;
    String outFile;
    int lastSep, amountRead;

    for (int i = 0; i < entries.size(); i++) {
      entry = (ZipEntry) entries.get(i);
      outFile = entry.getName();
      if ((lastSep = outFile.lastIndexOf('/')) != -1) outFile = outFile.substring(lastSep);

      try {
        in = archive.getInputStream(entry);
        if (in == null) throw new IOException("Zip file entry <" + entry.getName() + "> not found");
        out = new FileOutputStream(to + File.separator + outFile);

        while ((amountRead = in.read(buffer)) != -1) out.write(buffer, 0, amountRead);
      } finally {
        if (in != null) in.close();
        if (out != null) out.close();
      }
    }
  }
 private String readFromZipFile(String filename) {
   ZipFile zip = null;
   String str = null;
   try {
     InputStream fileStream = null;
     File applicationPackage = new File(mActivity.getApplication().getPackageResourcePath());
     zip = new ZipFile(applicationPackage);
     if (zip == null) return null;
     ZipEntry fileEntry = zip.getEntry(filename);
     if (fileEntry == null) return null;
     fileStream = zip.getInputStream(fileEntry);
     str = readStringFromStream(fileStream);
   } catch (IOException ioe) {
     Log.e(LOGTAG, "error reading zip file: " + filename, ioe);
   } finally {
     try {
       if (zip != null) zip.close();
     } catch (IOException ioe) {
       // catch this here because we can continue even if the
       // close failed
       Log.e(LOGTAG, "error closing zip filestream", ioe);
     }
   }
   return str;
 }
 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();
     }
   }
 }
  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();
    }
  }
Beispiel #28
0
  private static InputStream getInputStreamFromZippedPart(ZipFile zf, String partName)
      throws IOException {

    InputStream in = null;
    in = zf.getInputStream(zf.getEntry(partName));
    return in;
  }
Beispiel #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) {
   }
 }
Beispiel #30
0
  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();
      }
    }
  }