Exemplo n.º 1
0
  protected void unzip(File zipRoot, InputStream zipData, Reciver<String> log) throws IOException {
    ZipInputStream zip = new ZipInputStream(zipData);
    while (true) {
      ZipEntry ze = zip.getNextEntry();
      if (ze == null) break;
      if (ze.isDirectory()) {
        zip.closeEntry();
        continue;
      }

      String name = ze.getName();
      File file = new File(zipRoot, name.replace("\\", "/"));
      File fdir = file.getParentFile();
      if (!fdir.exists()) {
        fdir.mkdirs();
      }

      FileOutputStream fout = new FileOutputStream(file);
      FileUtil.copyAllData(zip, fout);
      fout.close();
      zip.closeEntry();

      //            logInfo("unpacked {0} to {1}", name, file);
      if (log != null) log.recive(Text.template("unpacked {0} to {1}", name, file));
    }
    zip.close();
  }
Exemplo n.º 2
0
  /**
   * Loads a factorisation machine from a compressed, human readable file.
   *
   * @param in input
   * @return factorisation machine
   * @throws IOException when I/O error
   */
  public static FM load(InputStream in) throws IOException {
    int N;
    int K;
    double b;
    DoubleMatrix1D w;
    DoubleMatrix2D m;
    try (ZipInputStream zip = new ZipInputStream(in)) {
      zip.getNextEntry();
      BufferedReader reader = new BufferedReader(new InputStreamReader(zip));
      N = parseInt(reader.readLine());
      K = parseInt(reader.readLine());
      zip.closeEntry();

      zip.getNextEntry();
      reader = new BufferedReader(new InputStreamReader(zip));
      b = parseDouble(reader.readLine());
      zip.closeEntry();

      zip.getNextEntry();
      w = loadDenseDoubleMatrix1D(zip, N);
      zip.closeEntry();

      zip.getNextEntry();
      m = loadDenseDoubleMatrix2D(zip, N, K);
      zip.closeEntry();
    }

    return new FM(b, w, m);
  }
  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;
  }
Exemplo n.º 4
0
  /**
   * Loads a matrix from a compressed input stream.
   *
   * @param <U> type of the users
   * @param <I> type of the items
   * @param in input stream
   * @param uIndex fast user index
   * @param iIndex fast item index
   * @param uParser user type parser
   * @param iParser item type parser
   * @return a factorization
   * @throws IOException when IO error
   */
  public static <U, I> Factorization<U, I> load(
      InputStream in,
      FastUserIndex<U> uIndex,
      FastItemIndex<I> iIndex,
      Parser<U> uParser,
      Parser<I> iParser)
      throws IOException {
    int K;
    DenseDoubleMatrix2D userMatrix;
    DenseDoubleMatrix2D itemMatrix;
    try (ZipInputStream zip = new ZipInputStream(in)) {
      zip.getNextEntry();
      BufferedReader reader = new BufferedReader(new InputStreamReader(zip));
      int numUsers = ip.parse(reader.readLine());
      int numItems = ip.parse(reader.readLine());
      K = ip.parse(reader.readLine());
      zip.closeEntry();

      zip.getNextEntry();
      userMatrix = loadDenseDoubleMatrix2D(zip, numUsers, K);
      zip.closeEntry();

      zip.getNextEntry();
      itemMatrix = loadDenseDoubleMatrix2D(zip, numItems, K);
      zip.closeEntry();
    }

    return new Factorization<>(uIndex, iIndex, userMatrix, itemMatrix, K);
  }
Exemplo n.º 5
0
  protected void unzip(String pathToFile, String outputFolder) {
    System.out.println("Start unzipping: " + pathToFile + " to " + outputFolder);
    String pathToUnzip;
    if (outputFolder.equals(pathManager.getPlatformFolderInAndroidSdk())) {
      pathToUnzip = outputFolder;
    } else {
      pathToUnzip = outputFolder + "/" + FileUtil.getNameWithoutExtension(new File(pathToFile));
    }
    if (new File(pathToUnzip).listFiles() != null) {
      System.out.println("File was already unzipped: " + pathToFile);
      return;
    }
    try {
      byte[] buf = new byte[1024];
      ZipInputStream zipinputstream = null;
      ZipEntry zipentry;
      zipinputstream = new ZipInputStream(new FileInputStream(pathToFile));

      zipentry = zipinputstream.getNextEntry();
      try {
        while (zipentry != null) {
          String entryName = zipentry.getName();
          int n;
          File outputFile = new File(outputFolder + "/" + entryName);

          if (zipentry.isDirectory()) {
            outputFile.mkdirs();
            zipinputstream.closeEntry();
            zipentry = zipinputstream.getNextEntry();
            continue;
          } else {
            File parentFile = outputFile.getParentFile();
            if (parentFile != null && !parentFile.exists()) {
              parentFile.mkdirs();
            }
            outputFile.createNewFile();
          }

          FileOutputStream fileoutputstream = new FileOutputStream(outputFile);
          try {
            while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
              fileoutputstream.write(buf, 0, n);
            }
          } finally {
            fileoutputstream.close();
          }
          zipinputstream.closeEntry();
          zipentry = zipinputstream.getNextEntry();
        }

        zipinputstream.close();
      } catch (IOException e) {
        System.err.println("Entry name: " + zipentry.getName());
        e.printStackTrace();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.println("Finish unzipping: " + pathToFile + " to " + outputFolder);
  }
Exemplo n.º 6
0
  public void processInDirectory() {
    //
    // распакуем все файлы из каталага in
    //
    final int BUFFER_SIZE = 4096;
    SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
    final String sessionDate = df.format(new Date());
    //
    // ищем файлы с ответом
    logger.info("Обрабатываем входной каталог " + ABS_INPUT_DIR);
    try {
      File[] directoryList =
          (new File(ABS_INPUT_DIR))
              .listFiles(
                  pathname -> !pathname.isDirectory() && pathname.getName().endsWith(".zip"));
      //
      // распаковываем каждый zip
      //
      for (File curFile : directoryList) {
        logger.info("Распаковываем " + curFile.getName());
        //
        // открываем архив
        //
        FileInputStream fis = new FileInputStream(curFile);
        ZipInputStream zis = new ZipInputStream(fis);
        ZipEntry zipEntry;
        while ((zipEntry = zis.getNextEntry()) != null) {
          //
          // пропускаем директории, т.к. их быть не должно
          //
          if (zipEntry.isDirectory()) continue;
          //
          // из архива извлекаем только xml !!!
          //
          if (zipEntry.getName().endsWith(".xml")) {
            File unzippedFile = new File(ABS_INPUT_DIR + "/" + zipEntry.getName());
            logger.info("Извлекаем файл " + zipEntry.getName());
            FileOutputStream fos = new FileOutputStream(unzippedFile);
            byte[] buffer = new byte[BUFFER_SIZE];
            int count = 0;
            while ((count = zis.read(buffer)) > 0) {
              fos.write(buffer, 0, count);
            }
            fos.close();
          }
          zis.closeEntry();
        }
        zis.close();
        fis.close();
        Files.move(
            curFile.toPath(),
            Paths.get(ABS_ARCH_IN_DIR + "/" + sessionDate + "-" + curFile.getName()));
      }
    } catch (Exception e) {
      logger.error(e.getMessage());
      e.printStackTrace();
    }

    logger.info("Обработан входной каталог " + ABS_INPUT_DIR);
  }
Exemplo n.º 7
0
  public static void unzip(byte[] content, final File destinationDir) throws IOException {
    byte[] buffer = new byte[BUFFER_SIZE];

    ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(content));
    ZipEntry zipEntry = zis.getNextEntry();

    while (zipEntry != null) {
      String fileName = zipEntry.getName();
      File file = new File(destinationDir + File.separator + fileName);

      if (zipEntry.isDirectory()) {
        ensureExistingDirectory(file);
      } else {
        ensureExistingDirectory(file.getParentFile());

        FileOutputStream fos = new FileOutputStream(file);
        try {
          int len;
          while ((len = zis.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
          }
        } finally {
          closeQuietly(fos);
        }
      }

      zipEntry = zis.getNextEntry();
    }

    zis.closeEntry();
    zis.close();
  }
Exemplo n.º 8
0
  private void unpackZip(File tmpZipFile) throws IOException {
    ZipInputStream zis = new ZipInputStream(new FileInputStream(tmpZipFile));
    // get the zipped file list entry
    ZipEntry ze = zis.getNextEntry();

    while (ze != null) {
      if (ze.isDirectory()) {
        ze = zis.getNextEntry();
        continue;
      }

      String fileName = stripLeadingPath(ze.getName());
      File newFile = new File(outputDirectory + File.separator + fileName);

      new File(newFile.getParent()).mkdirs();

      FileOutputStream fos = new FileOutputStream(newFile);

      IOUtils.copy(zis, fos);

      fos.close();
      ze = zis.getNextEntry();
    }

    zis.closeEntry();
    zis.close();
  }
  /**
   * The constructor.
   *
   * @param outputFilename The output filename.
   * @param plistener The packager listener.
   * @exception Exception Description of the Exception
   */
  public WebKunststoffPackager(String outputFilename, PackagerListener plistener) throws Exception {
    super(outputFilename, plistener);

    // Copies the Kunststoff library
    sendMsg("Copying the Kunststoff library ...");
    ZipInputStream skeleton_is =
        new ZipInputStream(getClass().getResourceAsStream("/lib/kunststoff.jar"));

    if (skeleton_is == null) {
      skeleton_is =
          new JarInputStream(
              new FileInputStream(
                  Compiler.IZPACK_HOME + "lib" + File.separator + "kunststoff.jar"));
    }

    ZipEntry zentry;

    while ((zentry = skeleton_is.getNextEntry()) != null) {
      // Puts a new entry
      outJar.putNextEntry(new ZipEntry(zentry.getName()));

      // Copy the data
      copyStream(skeleton_is, outJar);

      outJar.closeEntry();
      skeleton_is.closeEntry();
    }
  }
  private static void unzip(File src, File dest) throws IOException {
    InputStream is = new FileInputStream(src);
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
    ZipEntry ze;

    dest.mkdirs();

    while ((ze = zis.getNextEntry()) != null) {
      byte[] buffer = new byte[16384];
      int count;
      FileOutputStream fos = new FileOutputStream(new File(dest, ze.getName()));
      BufferedOutputStream out = new BufferedOutputStream(fos);

      try {
        while ((count = zis.read(buffer)) != -1) {
          out.write(buffer, 0, count);
        }
        out.flush();
      } finally {
        fos.getFD().sync();
        out.close();
      }

      zis.closeEntry();
    }

    zis.close();
  }
Exemplo n.º 11
0
  public static void decompressAll(File zipFile, File targetDirectory)
      throws IOException, ZipException {

    if (!targetDirectory.isDirectory())
      throw new IOException("2nd Parameter targetDirectory is not a valid diectory!");

    byte[] buf = new byte[4096];
    ZipInputStream in = new ZipInputStream(new FileInputStream(zipFile));
    while (true) {
      // N�chsten Eintrag lesen
      ZipEntry entry = in.getNextEntry();
      if (entry == null) {
        break;
      }

      // Ausgabedatei erzeugen
      FileOutputStream out =
          new FileOutputStream(
              targetDirectory.getAbsolutePath() + "/" + new File(entry.getName()).getName());
      // Lese-Vorgang
      int len;
      while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
      }
      out.close();

      // Eintrag schlie�en
      in.closeEntry();
    }
    in.close();
  }
Exemplo n.º 12
0
  /**
   * Gets all file names out of a zip file in sorted name order Returns a list String names or null
   * if none
   *
   * @param zipFile
   * @return
   * @throws IOException
   */
  public static String[] getZipFileEntryNames(File zipFile) throws IOException {
    ZipInputStream zIn = null;
    ZipEntry zipEntry;
    final int bufSize = 1024;
    List<String> fileList = new ArrayList<String>();

    BufferedInputStream in = new BufferedInputStream(new FileInputStream(zipFile), bufSize);

    zIn = new ZipInputStream(in);

    try {
      while ((zipEntry = zIn.getNextEntry()) != null) {
        // Don't add directories
        if (!zipEntry.isDirectory()) {
          String zipEntryName = zipEntry.getName();
          fileList.add(zipEntryName);
        }
        zIn.closeEntry();
      }
    }
    // We'll catch this exception to close the file otherwise it will remain locked
    catch (IOException ex) {
      zIn.close();
      throw ex;
    } finally {
      zIn.close();
    }

    String[] names = new String[fileList.size()];
    fileList.toArray(names);
    Arrays.sort(names);
    return names;
  }
Exemplo n.º 13
0
  public ZipRepository(final InputStream in, final MimeRegistry mimeRegistry) throws IOException {
    this(mimeRegistry);

    final ZipInputStream zipIn = new ZipInputStream(in);
    try {
      ZipEntry nextEntry = zipIn.getNextEntry();
      while (nextEntry != null) {
        final String[] buildName = RepositoryUtilities.splitPath(nextEntry.getName(), "/");
        if (nextEntry.isDirectory()) {
          root.updateDirectoryEntry(buildName, 0, nextEntry);
        } else {
          final ByteArrayOutputStream bos = new ByteArrayOutputStream();
          final Deflater def = new Deflater(nextEntry.getMethod());
          try {
            final DeflaterOutputStream dos = new DeflaterOutputStream(bos, def);
            try {
              IOUtils.getInstance().copyStreams(zipIn, dos);
              dos.flush();
            } finally {
              dos.close();
            }
          } finally {
            def.end();
          }

          root.updateEntry(buildName, 0, nextEntry, bos.toByteArray());
        }

        zipIn.closeEntry();
        nextEntry = zipIn.getNextEntry();
      }
    } finally {
      zipIn.close();
    }
  }
Exemplo n.º 14
0
    InMemorySourceRepository(@WillClose ZipInputStream in) throws IOException {
      try {
        while (true) {

          ZipEntry e = in.getNextEntry();
          if (e == null) break;
          if (!e.isDirectory()) {
            String name = e.getName();
            long size = e.getSize();

            if (size > Integer.MAX_VALUE)
              throw new IOException(name + " is too big at " + size + " bytes");
            ByteArrayOutputStream out;
            if (size <= 0) out = new ByteArrayOutputStream();
            else out = new ByteArrayOutputStream((int) size);
            GZIPOutputStream gOut = new GZIPOutputStream(out);
            IO.copy(in, gOut);
            gOut.close();
            byte data[] = out.toByteArray();
            contents.put(name, data);
            lastModified.put(name, e.getTime());
          }
          in.closeEntry();
        }
      } finally {
        Util.closeSilently(in);
      }
    }
Exemplo n.º 15
0
 /**
  * Extracts given zip to given location
  *
  * @param zipLocation - the location of the zip to be extracted
  * @param outputLocation - location to extract to
  */
 public static void extractZipTo(String zipLocation, String outputLocation) {
   ZipInputStream zipinputstream = null;
   try {
     byte[] buf = new byte[1024];
     zipinputstream = new ZipInputStream(new FileInputStream(zipLocation));
     ZipEntry zipentry = zipinputstream.getNextEntry();
     while (zipentry != null) {
       String entryName = zipentry.getName();
       int n;
       if (!zipentry.isDirectory()
           && !entryName.equalsIgnoreCase("minecraft")
           && !entryName.equalsIgnoreCase(".minecraft")
           && !entryName.equalsIgnoreCase("instMods")) {
         new File(outputLocation + File.separator + entryName).getParentFile().mkdirs();
         FileOutputStream fileoutputstream =
             new FileOutputStream(outputLocation + File.separator + entryName);
         while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
           fileoutputstream.write(buf, 0, n);
         }
         fileoutputstream.close();
       }
       zipinputstream.closeEntry();
       zipentry = zipinputstream.getNextEntry();
     }
   } catch (Exception e) {
     Logger.logError(e.getMessage(), e);
     backupExtract(zipLocation, outputLocation);
   } finally {
     try {
       zipinputstream.close();
     } catch (IOException e) {
     }
   }
 }
Exemplo n.º 16
0
  private void unzip(IProject project, IProgressMonitor monitor) throws IOException, CoreException {
    MultiStatus multiStatus =
        new MultiStatus(
            Activator.PLUGIN_ID, IStatus.OK, "Error(s) in setup mruby environment.", null);

    URL url = Activator.getContext().getBundle().getEntry("sources.zip");
    ZipInputStream zist = new ZipInputStream(url.openStream());
    ZipEntry zipEntry;
    while ((zipEntry = zist.getNextEntry()) != null) {
      try {
        String name = zipEntry.getName();
        if (zipEntry.isDirectory()) {
          unzipFolder(name, project, monitor);
        } else {
          unzipFile(name, project, zist, monitor);
        }
      } catch (CoreException e) {
        multiStatus.add(e.getStatus());
      }
      zist.closeEntry();
    }

    if (!multiStatus.isOK()) {
      throw new CoreException(multiStatus);
    }
  }
  public GenericStructureInfo structureInfoFromZip(ZipInputStream zipInputStream)
      throws StructureLoadException {
    try {
      String json = null;
      NBTTagCompound worldData = null;

      ZipEntry zipEntry;

      while ((zipEntry = zipInputStream.getNextEntry()) != null) {
        byte[] bytes = completeByteArray(zipInputStream);

        if (bytes != null) {
          if (STRUCTURE_INFO_JSON_FILENAME.equals(zipEntry.getName())) json = new String(bytes);
          else if (WORLD_DATA_NBT_FILENAME.equals(zipEntry.getName()))
            worldData = CompressedStreamTools.func_152457_a(bytes, NBTSizeTracker.field_152451_a);
        }

        zipInputStream.closeEntry();
      }
      zipInputStream.close();

      if (json == null || worldData == null)
        throw new StructureInvalidZipException(json != null, worldData != null);

      GenericStructureInfo genericStructureInfo = registry.createStructureFromJSON(json);
      genericStructureInfo.worldDataCompound = worldData;

      return genericStructureInfo;
    } catch (IOException e) {
      throw new StructureLoadException(e);
    }
  }
Exemplo n.º 18
0
  private static MemoStorable _unserialize(byte[] data, int size) {
    MemoStorable result = null;
    ByteArrayInputStream bis = new ByteArrayInputStream(data);

    try {
      ZipInputStream zis = new ZipInputStream(bis);
      zis.getNextEntry();
      BufferedInputStream bus = new BufferedInputStream(zis, size > 0 ? size : 15000);
      ObjectInputStream ios = new ObjectInputStream(bus);
      //			ios.readInt();
      //			System.out.println("Non-blocking available:
      // "+bis.available()+":"+zis.available()+":"+bus.available());
      result = (MemoStorable) ios.readObject();
      zis.closeEntry();
      bis.reset();
      bis.close();
      zis.close();
      ios.close();

    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
    return result;
  }
  public void unzip(File from, String to) throws FITTESTException {
    try {
      FileInputStream fis = new FileInputStream(from);
      ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis, BUFFER));
      ZipEntry entry = zis.getNextEntry();
      while (entry != null) {
        int count;
        byte data[] = new byte[BUFFER];

        File outFile = null;
        if (entry.isDirectory()) {
          outFile = new File(to, entry.getName());
          outFile.mkdirs();
        } else {
          outFile = new File(to, entry.getName());

          FileOutputStream fos = new FileOutputStream(outFile);
          BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER);
          while ((count = zis.read(data, 0, BUFFER)) != -1) {
            bos.write(data, 0, count);
          }
          bos.flush();
          bos.close();
        }
        zis.closeEntry();

        entry = zis.getNextEntry();
      }
      zis.close();
    } catch (Exception e) {
      throw new FITTESTException(e.getMessage());
    }
  }
Exemplo n.º 20
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();
    }
  }
  /**
   * Unzip the data directory to the destination
   *
   * @throws IOException
   * @throws FileNotFoundException
   */
  private void unzipData(File destination) throws IOException, FileNotFoundException {
    byte[] buffer = new byte[1024];
    // get the zip file content
    ZipInputStream zis =
        new ZipInputStream(FileLocator.openStream(bundle, new Path(EXECUTION_PLAN_DATA_ZIP), true));
    // Get the zipped file list entry
    ZipEntry ze = zis.getNextEntry();

    while (ze != null) {
      String fileName = ze.getName();
      File newFile = new File(destination, fileName);

      // Create all directories if they do not already exist
      new File(newFile.getParent()).mkdirs();

      if (ze.isDirectory()) {
        newFile.mkdirs();
      } else {
        // Read out the file
        FileOutputStream fos = new FileOutputStream(newFile);

        int len;
        while ((len = zis.read(buffer)) > 0) {
          fos.write(buffer, 0, len);
        }

        fos.close();
      }

      ze = zis.getNextEntry();
    }

    zis.closeEntry();
    zis.close();
  }
Exemplo n.º 22
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);
    }
  }
Exemplo 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;
  }
Exemplo n.º 24
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();
   }
 }
Exemplo n.º 25
0
  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;
  }
Exemplo n.º 26
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();
   }
 }
  /**
   * Constructor.
   *
   * @param codeBaseLocator the codebase locator for this codebase
   * @param file the File containing the zip file (may be a temp file if the codebase was copied
   *     from a nested zipfile in another codebase)
   */
  public ZipInputStreamCodeBase(ICodeBaseLocator codeBaseLocator, File file) throws IOException {
    super(codeBaseLocator);

    this.file = file;
    setLastModifiedTime(file.lastModified());
    ZipInputStream zis = new ZipInputStream(new FileInputStream(file));
    try {
      ZipEntry ze;

      if (DEBUG) {
        System.out.println("Reading zip input stream " + file);
      }

      while ((ze = zis.getNextEntry()) != null) {
        String name = ze.getName();
        if (!ze.isDirectory()
            && (name.equals("META-INF/MANIFEST.MF")
                || name.endsWith(".class")
                || Archive.isArchiveFileName(name))) {
          entries.add(name);
          if (name.equals("META-INF/MANIFEST.MF")) {
            map.put(name, build(zis, ze));
          }
        }
        zis.closeEntry();
      }
    } finally {
      zis.close();
    }
    if (DEBUG) {
      System.out.println("Done with zip input stream " + file);
    }
  }
  /**
   * Unzip all the projects contained by the zip.
   *
   * @param bundleName the bundle name
   * @param zipLocation the zip location inside of the bundle
   * @param monitor the progress monitor
   * @throws IOException if there is an issue copying a file from the zip
   * @throws CoreException if there is an issue creating one of the projects
   */
  public static void unzipAllProjects(
      String bundleName, String zipLocation, IProgressMonitor monitor)
      throws IOException, CoreException {
    final URL interpreterZipUrl =
        FileLocator.find(Platform.getBundle(bundleName), new Path(zipLocation), null);
    final ZipInputStream zipFileStream = new ZipInputStream(interpreterZipUrl.openStream());
    ZipEntry zipEntry = zipFileStream.getNextEntry();

    Set<IProject> projects = new HashSet<IProject>();

    while (zipEntry != null) {
      String projectName = zipEntry.getName().split("/")[0];

      IProject project = createProject(projectName, monitor);
      projects.add(project);

      final File file =
          new File(
              project.getLocation().toString(),
              zipEntry
                  .getName()
                  .replaceFirst(projectName + "/", "")); // $NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$

      if (!zipEntry.isDirectory()) {

        /*
         * Copy files (and make sure parent directory exist)
         */
        final File parentFile = file.getParentFile();
        if (null != parentFile && !parentFile.exists()) {
          parentFile.mkdirs();
        }

        OutputStream os = null;

        try {
          os = new FileOutputStream(file);

          final int bufferSize = 102400;
          final byte[] buffer = new byte[bufferSize];
          while (true) {
            final int len = zipFileStream.read(buffer);
            if (zipFileStream.available() == 0) {
              break;
            }
            os.write(buffer, 0, len);
          }
        } finally {
          if (null != os) {
            os.close();
          }
        }
      }
      zipFileStream.closeEntry();
      zipEntry = zipFileStream.getNextEntry();
    }

    ResourcesPlugin.getWorkspace().getRoot().refreshLocal(IResource.DEPTH_INFINITE, monitor);
  }
Exemplo n.º 29
0
  public static void extractLegacyEditorResources() {
    try {
      String destParent = applicationDataDir() + ".ApplicationData" + File.separator;
      File appHome = new File(destParent);
      if (!appHome.exists()) {
        if (!appHome.mkdirs()) {
          SEAGridDialogHelper.showExceptionDialogAndWait(
              new Exception("Cannot Create Application Data Dir"),
              "Cannot Create Application Data Dir",
              null,
              "Cannot Create Application Data Dir");
        }
      }
      byte[] buf = new byte[1024];
      ZipInputStream zipinputstream;
      ZipEntry zipentry;
      zipinputstream =
          new ZipInputStream(
              SEAGridDesktop.class.getClassLoader().getResourceAsStream("legacy.editors.zip"));

      zipentry = zipinputstream.getNextEntry();
      if (zipentry == null) {
        SEAGridDialogHelper.showExceptionDialogAndWait(
            new Exception("Cannot Read Application Resources"),
            "Cannot Read Application Resources",
            null,
            "Cannot Read Application Resources");
      } else {
        while (zipentry != null) {
          // for each entry to be extracted
          String entryName = destParent + zipentry.getName();
          entryName = entryName.replace('/', File.separatorChar);
          entryName = entryName.replace('\\', File.separatorChar);
          logger.info("entryname " + entryName);
          int n;
          FileOutputStream fileoutputstream;
          File newFile = new File(entryName);
          if (zipentry.isDirectory()) {
            if (!newFile.mkdirs()) {
              break;
            }
            zipentry = zipinputstream.getNextEntry();
            continue;
          }
          fileoutputstream = new FileOutputStream(entryName);
          while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
            fileoutputstream.write(buf, 0, n);
          }
          fileoutputstream.close();
          zipinputstream.closeEntry();
          zipentry = zipinputstream.getNextEntry();
        }
        zipinputstream.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
      logger.error(e.getMessage(), e);
    }
  }
Exemplo n.º 30
0
  public static String unzip(String zipFile, String location) throws IOException {
    int size;
    byte[] buffer = new byte[BUFFER_SIZE];

    if (!location.endsWith("/")) {
      location += "/";
    }
    File f = new File(location);
    if (!f.isDirectory()) {
      f.mkdirs();
    }
    ZipInputStream zin =
        new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile), BUFFER_SIZE));
    String fileName = null;
    try {
      ZipEntry ze = null;

      while ((ze = zin.getNextEntry()) != null) {
        String path = location + ze.getName();
        File unzipFile = new File(path);

        if (ze.isDirectory()) {
          throw new UnsupportedOperationException("Error: The zip file contains directory.");
        } else {
          if (fileName != null) {
            throw new UnsupportedOperationException(
                "Error: The zip file contains more than a single file.");
          }

          fileName = path;

          // check for and create parent directories if they don't exist
          File parentDir = unzipFile.getParentFile();
          if (null != parentDir) {
            if (!parentDir.isDirectory()) {
              parentDir.mkdirs();
            }
          }

          // unzip the file
          FileOutputStream out = new FileOutputStream(unzipFile, false);
          BufferedOutputStream fout = new BufferedOutputStream(out, BUFFER_SIZE);
          try {
            while ((size = zin.read(buffer, 0, BUFFER_SIZE)) != -1) {
              fout.write(buffer, 0, size);
            }
            zin.closeEntry();
          } finally {
            fout.flush();
            fout.close();
          }
        }
      }
    } finally {
      zin.close();
    }

    return fileName;
  }