Esempio n. 1
0
  /**
   * Parse a repository document.
   *
   * @param url
   * @throws IOException
   * @throws XmlPullParserException
   * @throws Exception
   */
  void parseDocument(URL url) throws IOException, XmlPullParserException, Exception {
    if (!visited.contains(url)) {
      visited.add(url);
      try {
        System.out.println("Visiting: " + url);
        InputStream in = null;

        if (url.getPath().endsWith(".zip")) {
          ZipInputStream zin = new ZipInputStream(url.openStream());
          ZipEntry entry = zin.getNextEntry();
          while (entry != null) {
            if (entry.getName().equals("repository.xml")) {
              in = zin;
              break;
            }
            entry = zin.getNextEntry();
          }
        } else {
          in = url.openStream();
        }
        Reader reader = new InputStreamReader(in);
        XmlPullParser parser = new KXmlParser();
        parser.setInput(reader);
        parseRepository(parser);
      } catch (MalformedURLException e) {
        System.out.println("Cannot create connection to url");
      }
    }
  }
  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();
    }
  }
Esempio n. 3
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) {
   }
 }
Esempio n. 4
0
  /* @see loci.formats.FormatReader#initFile(String) */
  protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    reader = new ImageReader();

    reader.setMetadataOptions(getMetadataOptions());
    reader.setMetadataFiltered(isMetadataFiltered());
    reader.setOriginalMetadataPopulated(isOriginalMetadataPopulated());
    reader.setNormalized(isNormalized());
    reader.setMetadataStore(getMetadataStore());

    // NB: We need a raw handle on the ZIP data itself, not a ZipHandle.
    IRandomAccess rawHandle = Location.getHandle(id, false, false);
    in = new RandomAccessInputStream(rawHandle, id);

    ZipInputStream zip = new ZipInputStream(in);
    while (true) {
      ZipEntry ze = zip.getNextEntry();
      if (ze == null) break;
      ZipHandle handle = new ZipHandle(id, ze);
      Location.mapFile(ze.getName(), handle);
      mappedFiles.add(ze.getName());
    }

    ZipHandle base = new ZipHandle(id);
    reader.setId(base.getEntryName());

    metadataStore = reader.getMetadataStore();
    core = reader.getCoreMetadata();
    metadata = reader.getGlobalMetadata();

    base.close();
  }
Esempio n. 5
0
  /**
   * Unzips entries from {@code stream} into {@code directory}.
   *
   * @param stream source zip stream
   * @param directory target directory to which entries going to be unzipped.
   * @param buffer the buffer to use
   * @throws IOException if an I/O error occurs.
   */
  public static void unzip(final ZipInputStream stream, final File directory, final byte[] buffer)
      throws IOException {

    if (stream == null) {
      throw new NullPointerException("stream");
    }

    if (directory == null) {
      throw new NullPointerException("directory");
    }

    if (!directory.isDirectory()) {
      throw new IllegalArgumentException("directory doesn't exist");
    }

    if (buffer == null) {
      throw new NullPointerException("buffer");
    }

    if (buffer.length == 0) {
      throw new IllegalArgumentException("buffer.length(" + buffer.length + ") == 0");
    }

    ZipEntry entry;
    while ((entry = stream.getNextEntry()) != null) {
      final File file = file(directory, entry);
      if (!entry.isDirectory()) {
        ByteStreams.copy(stream, file, buffer, -1L);
      }
      stream.closeEntry();
    }
  }
Esempio n. 6
0
 @Override
 public String getScript() throws IOException {
   ZipInputStream zippedIn = null;
   try {
     zippedIn = new ZipInputStream(new FileInputStream(getZipFile()));
     ZipEntry entry;
     while ((entry = zippedIn.getNextEntry()) != null) {
       if (entry.getName().equals(getEntryName())) {
         break;
       }
     }
     if (entry == null) {
       throw new OpenGammaRuntimeException(
           "No entry found in zip file " + getZipFile() + " with name " + getEntryName());
     }
     return IOUtils.toString(zippedIn);
   } catch (FileNotFoundException e) {
     throw new OpenGammaRuntimeException("Zip file not found: " + getZipFile());
   } catch (IOException e) {
     throw new OpenGammaRuntimeException("Error reading from zip file: " + getZipFile());
   } finally {
     if (zippedIn != null) {
       try {
         zippedIn.close();
       } catch (IOException e) {
       }
     }
   }
 }
Esempio n. 7
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 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();
     }
   }
 }
  public static boolean unpackFileFromZip(Path zipfile, String filename, Path destDirectory)
      throws IOException {
    boolean ret = true;

    byte[] bytebuffer = new byte[BUFFERSIZE];
    ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(zipfile.toFile()));

    ZipEntry zipentry;
    while ((zipentry = zipinputstream.getNextEntry()) != null) {
      if (zipentry.getName().equals(filename)) {
        Path newFile = destDirectory.resolve(zipentry.getName());
        FileOutputStream fileoutputstream = new FileOutputStream(newFile.toFile());

        int bytes;
        while ((bytes = zipinputstream.read(bytebuffer)) > -1) {
          fileoutputstream.write(bytebuffer, 0, bytes);
        }

        fileoutputstream.close();
        zipinputstream.closeEntry();
        zipinputstream.close();

        return ret;
      }

      zipinputstream.closeEntry();
    }

    zipinputstream.close();

    return ret;
  }
  static boolean unpackZipTo(Path zipfile, Path destDirectory) throws IOException {
    boolean ret = true;

    byte[] bytebuffer = new byte[BUFFERSIZE];
    ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(zipfile.toFile()));

    ZipEntry zipentry;
    while ((zipentry = zipinputstream.getNextEntry()) != null) {
      Path newFile = destDirectory.resolve(zipentry.getName());

      if (!Files.exists(newFile.getParent(), LinkOption.NOFOLLOW_LINKS)) {
        Files.createDirectories(newFile.getParent());
      }

      if (!Files.isDirectory(newFile, LinkOption.NOFOLLOW_LINKS)) {
        FileOutputStream fileoutputstream = new FileOutputStream(newFile.toFile());

        int bytes;
        while ((bytes = zipinputstream.read(bytebuffer)) > -1) {
          fileoutputstream.write(bytebuffer, 0, bytes);
        }
        fileoutputstream.close();
      }
      zipinputstream.closeEntry();
    }

    zipinputstream.close();

    return ret;
  }
Esempio n. 12
0
 /** Разархивация файла с БД */
 private void dearchiveDB() {
   String zipFile = RES_ABS_PATH + File.separator + DB_ARCHIVE_NAME;
   String outputFolder = RES_ABS_PATH;
   try {
     ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
     ZipEntry ze = zis.getNextEntry();
     while (ze != null) {
       String fileName = ze.getName();
       File newFile = new File(outputFolder + File.separator + fileName);
       System.out.println("File unzip : " + newFile.getAbsoluteFile());
       new File(newFile.getParent()).mkdirs();
       FileOutputStream fos = new FileOutputStream(newFile);
       int len;
       byte[] buffer = new byte[1024];
       while ((len = zis.read(buffer)) > 0) {
         fos.write(buffer, 0, len);
       }
       fos.close();
       ze = zis.getNextEntry();
     }
     zis.closeEntry();
     zis.close();
     System.out.println("File unziped");
   } catch (IOException ex) {
     ex.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;
  }
Esempio n. 14
0
 public static void unZip(String unZipfileName, String mDestPath) {
   if (!mDestPath.endsWith("/")) {
     mDestPath = mDestPath + "/";
   }
   FileOutputStream fileOut = null;
   ZipInputStream zipIn = null;
   ZipEntry zipEntry = null;
   File file = null;
   int readedBytes = 0;
   byte buf[] = new byte[4096];
   try {
     zipIn = new ZipInputStream(new BufferedInputStream(new FileInputStream(unZipfileName)));
     while ((zipEntry = zipIn.getNextEntry()) != null) {
       file = new File(mDestPath + zipEntry.getName());
       if (zipEntry.isDirectory()) {
         file.mkdirs();
       } else {
         // 如果指定文件的目录不存在,则创建之.
         File parent = file.getParentFile();
         if (!parent.exists()) {
           parent.mkdirs();
         }
         fileOut = new FileOutputStream(file);
         while ((readedBytes = zipIn.read(buf)) > 0) {
           fileOut.write(buf, 0, readedBytes);
         }
         fileOut.close();
       }
       zipIn.closeEntry();
     }
   } catch (IOException ioe) {
     ioe.printStackTrace();
   }
 }
Esempio n. 15
0
  @Override
  public Item item(final QueryContext qc, final InputInfo ii) throws QueryException {
    checkCreate(qc);

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

    try (ArchiveIn in = ArchiveIn.get(archive.input(info), info)) {
      while (in.more()) {
        final ZipEntry ze = in.entry();
        final String name = ze.getName();
        if (hs == null || hs.delete(token(name)) != 0) {
          final Path file = path.resolve(name);
          if (ze.isDirectory()) {
            Files.createDirectories(file);
          } else {
            Files.createDirectories(file.getParent());
            Files.write(file, in.read());
          }
        }
      }
    } catch (final IOException ex) {
      throw ARCH_FAIL_X.get(info, ex);
    }
    return null;
  }
Esempio n. 16
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;
 }
Esempio n. 17
0
  /**
   * Unzip given file into given folder.
   *
   * @param fileZip : zip file to unzip.
   * @param dirOut : folder where to put the unzipped files.
   */
  public static void unzip(File fileZip, File dirOut) {
    try {
      byte[] buf = new byte[10 * 1024];
      if (!fileZip.canRead()) throw new IllegalArgumentException(fileZip.getAbsolutePath());
      if (!dirOut.isDirectory()) dirOut.mkdirs();
      if (!dirOut.isDirectory()) throw new IllegalArgumentException(dirOut.getAbsolutePath());

      FileInputStream fin = new FileInputStream(fileZip);
      ZipInputStream zin = new ZipInputStream(fin);
      ZipEntry ze = null;
      while ((ze = zin.getNextEntry()) != null) {
        File fileZe = new File(dirOut, ze.getName());
        Log.i("Zip", fileZe.getAbsolutePath());
        if (ze.isDirectory()) continue;
        assureParentExists(fileZe);
        BufferedOutputStream fout = new BufferedOutputStream(new FileOutputStream(fileZe));
        while (true) {
          int read = zin.read(buf);
          if (-1 == read) break; // End of file.
          fout.write(buf, 0, read);
        }
        zin.closeEntry();
        fout.close();
      }
      zin.close();
    } catch (Exception e) {
      Log.e("MyZip", "unzip", e);
    }
  }
Esempio n. 18
0
  @Test
  public void packingALargeFileShouldGenerateTheSameOutputWhenOverwritingAsWhenAppending()
      throws IOException {
    File reference = File.createTempFile("reference", ".zip");
    String packageName = getClass().getPackage().getName().replace(".", "/");
    URL sample = Resources.getResource(packageName + "/macbeth.properties");
    byte[] input = Resources.toByteArray(sample);

    try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(output, OVERWRITE_EXISTING);
        ZipOutputStream ref = new ZipOutputStream(new FileOutputStream(reference))) {
      CustomZipEntry entry = new CustomZipEntry("macbeth.properties");
      entry.setTime(System.currentTimeMillis());
      out.putNextEntry(entry);
      ref.putNextEntry(entry);
      out.write(input);
      ref.write(input);
    }

    byte[] seen = Files.readAllBytes(output);
    byte[] expected = Files.readAllBytes(reference.toPath());

    // Make sure the output is valid.
    try (ZipInputStream in = new ZipInputStream(Files.newInputStream(output))) {
      ZipEntry entry = in.getNextEntry();
      assertEquals("macbeth.properties", entry.getName());
      assertNull(in.getNextEntry());
    }

    assertArrayEquals(expected, seen);
  }
Esempio n. 19
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) {
    }
  }
Esempio n. 20
0
  static Hashtable<String, PkgEntry> readJarFile(InputStream in) {
    Hashtable<String, PkgEntry> tbl = new Hashtable<String, PkgEntry>();
    try {
      ZipInputStream zis = new ZipInputStream(in);
      ZipEntry ze = zis.getNextEntry();
      while (ze != null) {
        String zname = ze.getName();
        if (zname.endsWith(".class")) {
          String pkgname = getPackageName(zname);
          if (!tbl.containsKey(pkgname)) {
            long csize = getCompressedSize(zis);
            tbl.put(pkgname, new PkgEntry(ze.getSize(), csize));
          } else {
            PkgEntry pe = tbl.get(pkgname);
            long csize = getCompressedSize(zis);
            pe.addSizes(ze.getSize(), csize);

            tbl.put(pkgname, pe);
          }
        }
        ze = zis.getNextEntry();
      }
    } catch (ZipException ex) {
      Logger.getLogger(JarAnalyzer.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
      Logger.getLogger(JarAnalyzer.class.getName()).log(Level.SEVERE, null, ex);
    }
    return tbl;
  }
Esempio n. 21
0
  private boolean unpackFile(ZipFile zip, byte[] buf, ZipEntry fileEntry, String name)
      throws IOException, FileNotFoundException {
    if (fileEntry == null) fileEntry = zip.getEntry(name);
    if (fileEntry == null)
      throw new FileNotFoundException("Can't find " + name + " in " + zip.getName());

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

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

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

    OutputStream outStream = new FileOutputStream(outFile);

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

    fileStream.close();
    outStream.close();
    outFile.setLastModified(fileEntry.getTime());
    return true;
  }
Esempio n. 22
0
 public static LinkedHashMap readJarFileEntries(File jarFile) throws Exception {
   LinkedHashMap entries = new LinkedHashMap();
   JarFile jarFileWrapper = null;
   if (jarFile != null) {
     logger.debug("Reading jar entries from " + jarFile.getAbsolutePath());
     try {
       jarFileWrapper = new JarFile(jarFile);
       Enumeration iter = jarFileWrapper.entries();
       while (iter.hasMoreElements()) {
         ZipEntry zipEntry = (ZipEntry) iter.nextElement();
         InputStream entryStream = jarFileWrapper.getInputStream(zipEntry);
         ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
         try {
           IOUtils.copy(entryStream, byteArrayStream);
           entries.put(zipEntry.getName(), byteArrayStream.toByteArray());
           logger.debug(
               "Read jar entry " + zipEntry.getName() + " from " + jarFile.getAbsolutePath());
         } finally {
           byteArrayStream.close();
         }
       }
     } finally {
       if (jarFileWrapper != null) {
         try {
           jarFileWrapper.close();
         } catch (Exception ignore) {
           logger.debug(ignore);
         }
       }
     }
   }
   return entries;
 }
Esempio n. 23
0
  /**
   * Get the preview image of a ggb file.
   *
   * @param file
   * @throws IOException
   * @return
   */
  public static final BufferedImage getPreviewImage(File file) throws IOException {
    // just allow preview images for ggb files
    if (!file.getName().endsWith(".ggb")) {
      throw new IllegalArgumentException("Preview image source file has to be of the type .ggb");
    }

    FileInputStream fis = new FileInputStream(file);
    ZipInputStream zip = new ZipInputStream(fis);
    BufferedImage result = null;

    // get all entries from the zip archive
    while (true) {
      ZipEntry entry = zip.getNextEntry();
      if (entry == null) break;

      if (entry.getName().equals(XML_FILE_THUMBNAIL)) {
        result = ImageIO.read(zip);
        break;
      }

      // get next entry
      zip.closeEntry();
    }

    zip.close();
    fis.close();

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

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

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

    return externs;
  }
Esempio n. 25
0
  protected static File file(final File root, final ZipEntry entry) throws IOException {

    if (root == null) {
      throw new NullPointerException("root");
    }

    if (!root.isDirectory()) {
      throw new IllegalArgumentException("root is not an existing directory");
    }

    if (entry == null) {
      throw new NullPointerException("entry");
    }

    final File file = new File(root, entry.getName());

    File parent = file;
    if (!entry.isDirectory()) {
      final String name = entry.getName();
      final int index = name.lastIndexOf('/');
      if (index != -1) {
        parent = new File(root, name.substring(0, index));
      }
    }
    if (parent != null && !parent.isDirectory() && !parent.mkdirs()) {
      throw new IOException("failed to create a directory: " + parent.getPath());
    }

    return file;
  }
Esempio n. 26
0
 public static boolean isJarDirectory(String path) {
   if (isJarFile()) {
     try {
       JarFile jar = new JarFile(getJarFile());
       ZipEntry entry = jar.getEntry(path);
       return entry != null && entry.isDirectory();
     } catch (Exception e) {
       e.printStackTrace();
     }
   } else {
     try {
       URL url = FileUtilities.class.getResource("/" + path);
       if (url != null) {
         URI uri = url.toURI();
         File classpath = new File(uri);
         return classpath.isDirectory();
       } else {
         return false;
       }
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return false;
 }
  /**
   * Reads all files into byte arrays. Here we don't know whether the ZIP file is valid.
   *
   * <p>The ZIP file is valid when contains a 'manifest.json' file and all BIN and DAT files that
   * are specified in the manifest.
   *
   * <p>For backwards compatibility ArchiveInputStream supports also ZIP archives without
   * 'manifest.json' file but than it MUST include at least one of the following files:
   * softdevice.bin/hex, bootloader.bin/hex, application.bin/hex. To support the init packet such
   * ZIP file should contain also application.dat and/or system.dat (with the CRC16 of a SD, BL or
   * SD+BL together).
   */
  private void parseZip(int mbrSize) throws IOException {
    final byte[] buffer = new byte[1024];
    String manifestData = null;

    ZipEntry ze;
    while ((ze = getNextEntry()) != null) {
      final String filename = ze.getName();

      // Read file content to byte array
      final ByteArrayOutputStream baos = new ByteArrayOutputStream();
      int count;
      while ((count = super.read(buffer)) != -1) {
        baos.write(buffer, 0, count);
      }
      byte[] source = baos.toByteArray();

      // In case of HEX file convert it to BIN
      if (filename.toLowerCase(Locale.US).endsWith("hex")) {
        final HexInputStream is = new HexInputStream(source, mbrSize);
        source = new byte[is.available()];
        is.read(source);
        is.close();
      }

      // Save the file content either as a manifest data or by adding it to entries
      if (MANIFEST.equals(filename)) manifestData = new String(source, "UTF-8");
      else entries.put(filename, source);
    }

    if (manifestData != null) {
      final ManifestFile manifestFile = new Gson().fromJson(manifestData, ManifestFile.class);
      manifest = manifestFile.getManifest();
    }
  }
  /**
   * Extracts all files from a zip to disk.
   *
   * @param zip data (zip format)
   * @throws IOException
   */
  private void extractZip(byte[] zip) throws IOException {
    ZipInputStream zis = null;
    try {
      ByteArrayInputStream bais = new ByteArrayInputStream(zip);
      zis = new ZipInputStream(new BufferedInputStream(bais));
      ZipEntry ze = null;

      // extract all entries
      Log.d(TAG, "Start extracting backup.");
      int i = 0;
      while ((ze = zis.getNextEntry()) != null) {
        if (!shouldIgnoreZipEntry(ze)) {
          extractFromZipAndSaveToFile(zis, ze);
          ++i;
        } else {
          Log.d(TAG, "Ignore entry: " + ze.getName());
        }
      }
      Log.i(TAG, "Extracted " + i + " elements from backup.");

    } finally {
      if (zis != null) {
        try {
          zis.close();
        } catch (IOException e) {
          Log.w(TAG, "Could not close zip input stream.", e);
        }
      }
    }
  }
Esempio n. 29
0
  /**
   * Copies your database from your local assets-folder to the just created empty database in the
   * system folder, from where it can be accessed and handled. This is done by transfering
   * bytestream.
   */
  private void copyDataBase() throws IOException {
    Log.d(TAG, "copyDataBase() called with: " + "");
    // Open your local db as the input stream
    ZipInputStream zipInputStream =
        new ZipInputStream(context.getAssets().open("data/" + DATABASE_NAME + ".zip"));
    ZipEntry entry;
    do {
      entry = zipInputStream.getNextEntry();
    } while (!entry.getName().equals(DATABASE_NAME));

    // InputStream myInput = context.getAssets().open(DATABASE_NAME);
    // Path to the just created empty db
    String outFileName = DATABASE_PATH + DATABASE_NAME;
    // Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);
    // transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = zipInputStream.read(buffer)) > 0) {
      myOutput.write(buffer, 0, length);
    }
    // Close the streams
    myOutput.flush();
    myOutput.close();
    zipInputStream.close();
  }
 private byte[] createMultiLevelArchive(List<String> resources, String archivePath)
     throws IOException {
   try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
     try (ZipOutputStream out = new ZipOutputStream(buffer)) {
       for (String resourcePath : resources) {
         ZipEntry entry = new ZipEntry(resourcePath);
         entry.setLastModifiedTime(time);
         out.putNextEntry(entry);
         try (InputStream in = getResourceAsStream(resourcePath)) {
           StreamUtils.copyStream(in, out);
         }
         out.closeEntry();
       }
       ZipEntry entry = new ZipEntry("test/");
       entry.setLastModifiedTime(time);
       out.putNextEntry(entry);
       out.closeEntry();
       entry = new ZipEntry(archivePath);
       entry.setLastModifiedTime(time);
       out.putNextEntry(entry);
       try (InputStream in = new ByteArrayInputStream(createArchive(resources))) {
         StreamUtils.copyStream(in, out);
       }
       out.closeEntry();
     }
     return buffer.toByteArray();
   }
 }