Example #1
0
  @Transactional
  public void load(String gtfsUrl) throws IOException {
    File file = openGtfsFile(gtfsUrl);

    cleanDB();

    ZipInputStream stream = new ZipInputStream(new FileInputStream(file));
    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
      write("Routes...");
      getEntry(stream, "routes.txt");
      parseRoutes(reader);
      write("Stops...");
      getEntry(stream, "stops.txt");
      parseStops(reader);
      write("Trips...");
      getEntry(stream, "trips.txt");
      parseTrips(reader);
      write("Stop Times...");
      getEntry(stream, "stop_times.txt");
      parseStopTimes(reader);
      write("Finialising...");
    } catch (Exception e) {
      write(e + ": " + e.getMessage());
    } finally {
      Route.entityManager().flush();
      stream.close();
      write("Done.");
    }
  }
Example #2
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();
    }
  }
Example #3
0
  /**
   * The URLs are a bit ugly and so we need to find out which area name a certain lat,lon coordinate
   * has.
   */
  private SRTMProvider init() {
    try {
      String strs[] = {
        "Africa", "Australia", "Eurasia", "Islands", "North_America", "South_America"
      };
      for (String str : strs) {
        InputStream is = getClass().getResourceAsStream(str + "_names.txt.zip");
        ZipInputStream zis = new ZipInputStream(is);
        zis.getNextEntry();
        for (String line : Helper.readFile(new InputStreamReader(zis, "UTF-8"))) {
          int lat = Integer.parseInt(line.substring(1, 3));
          if (line.substring(0, 1).charAt(0) == 'S') lat = -lat;

          int lon = Integer.parseInt(line.substring(4, 7));
          if (line.substring(3, 4).charAt(0) == 'W') lon = -lon;

          int intKey = calcIntKey(lat, lon);
          String key = areas.put(intKey, str);
          if (key != null)
            throw new IllegalStateException(
                "do not overwrite existing! key " + intKey + " " + key + " vs. " + str);
        }
      }
      return this;
    } catch (Exception ex) {
      throw new IllegalStateException("Cannot load area names from classpath", ex);
    }
  }
Example #4
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);
    }
  }
Example #5
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();
  }
 private static ArrayList<BatteryData> prepareBatteryData() {
   ArrayList<BatteryData> batteryList = new ArrayList<BatteryData>();
   BufferedReader br = null;
   String line = "";
   String cvsSplitBy = ",";
   try {
     ZipInputStream zin = new ZipInputStream(new FileInputStream(Battery_Name));
     zin.getNextEntry();
     br = new BufferedReader(new InputStreamReader(zin));
     while ((line = br.readLine()) != null) {
       String[] values = line.toLowerCase().split(cvsSplitBy);
       // line format: SAMSUNG I9500 GALAXY S4, 2600
       if (values.length < 2) continue;
       Matcher matcher = modelRegEx.matcher(values[0]);
       String model = values[0];
       if (matcher.find()) model = matcher.group(0);
       batteryList.add(new BatteryData(values[0], model, values[1]));
     }
     br.close();
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     if (br != null) {
       try {
         br.close();
       } catch (Exception e) {
       }
     }
   }
   return batteryList;
 }
Example #7
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;
  }
  public void testDownload() throws Exception {

    final Long processId = issueProcessAndWaitForTermination();

    // zip extension is not required but should be handled
    final String request = RESTLET_PATH + "/" + processId.longValue() + ".zip";

    final MockHttpServletResponse response = getAsServletResponse(request);
    assertEquals(Status.SUCCESS_OK, Status.valueOf(response.getStatus()));
    assertEquals(MediaType.APPLICATION_ZIP, MediaType.valueOf(response.getContentType()));
    assertEquals(
        "attachment; filename=\"test map.zip\"", response.getHeader("Content-Disposition"));

    final ByteArrayInputStream responseStream = getBinaryInputStream(response);
    final ZipInputStream zipIn = new ZipInputStream(responseStream);

    Set<String> expectedFiles = new HashSet<String>();
    expectedFiles.add("README.txt");
    expectedFiles.add(VECTOR_LAYER.getLocalPart() + ".shp");
    expectedFiles.add(VECTOR_LAYER.getLocalPart() + ".cst");
    expectedFiles.add(VECTOR_LAYER.getLocalPart() + ".prj");
    expectedFiles.add(VECTOR_LAYER.getLocalPart() + ".dbf");
    expectedFiles.add(VECTOR_LAYER.getLocalPart() + ".shx");
    // TODO: change this expectation once we normalize the raster file name
    expectedFiles.add(RASTER_LAYER.getPrefix() + ":" + RASTER_LAYER.getLocalPart() + ".tiff");

    Set<String> archivedFiles = new HashSet<String>();

    ZipEntry nextEntry;
    while ((nextEntry = zipIn.getNextEntry()) != null) {
      archivedFiles.add(nextEntry.getName());
    }

    assertEquals(expectedFiles, archivedFiles);
  }
  private List<ComponentDeclaration> getDeclaredComponents(File jarFile) throws IOException {
    ZipInputStream zis = new ZipInputStream(new FileInputStream(jarFile));

    List<ComponentDeclaration> componentDeclarations = null;
    List<ComponentDeclaration> componentOverrideDeclarations = null;

    try {
      for (ZipEntry entry = zis.getNextEntry();
          entry != null && (componentDeclarations == null || componentOverrideDeclarations == null);
          entry = zis.getNextEntry()) {
        if (entry.getName().equals(ComponentAnnotationLoader.COMPONENT_LIST)) {
          componentDeclarations = this.jarLoader.getDeclaredComponents(zis);
        } else if (entry.getName().equals(ComponentAnnotationLoader.COMPONENT_OVERRIDE_LIST)) {
          componentOverrideDeclarations = this.jarLoader.getDeclaredComponents(zis);
        }
      }
    } finally {
      zis.close();
    }

    // Merge all overrides found with a priority of 0. This is purely for backward compatibility
    // since the
    // override files is now deprecated.
    if (componentOverrideDeclarations != null) {
      if (componentDeclarations == null) {
        componentDeclarations = new ArrayList<ComponentDeclaration>();
      }
      for (ComponentDeclaration componentOverrideDeclaration : componentOverrideDeclarations) {
        componentDeclarations.add(
            new ComponentDeclaration(componentOverrideDeclaration.getImplementationClassName(), 0));
      }
    }

    return componentDeclarations;
  }
  /**
   * 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);
    }
  }
  private void loadSharedStringsAndRels(FileInputStream inputStream) {
    try {
      int tasksComplete = 0;
      ZipInputStream zipInputStream = new ZipInputStream(inputStream);

      ZipEntry zipEntry = null;
      while ((zipEntry = zipInputStream.getNextEntry()) != null) {
        String filename = zipEntry.getName();
        if (filename.equals("xl/sharedStrings.xml")) {
          processSharedStrings(zipInputStream);
          tasksComplete++;
        } else if (filename.equals("xl/_rels/workbook.xml.rels")) {
          processRels(zipInputStream);
          tasksComplete++;
        }

        if (tasksComplete == 2) {
          zipInputStream.close();
          break;
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #12
0
  /**
   * Add the entries from the supplied {@link ZipInputStream} to this archive instance.
   *
   * @param zipStream The zip stream.
   * @return This archive instance.
   * @throws IOException Error reading zip stream.
   */
  public Archive addEntries(ZipInputStream zipStream) throws IOException {
    AssertArgument.isNotNull(zipStream, "zipStream");

    try {
      ZipEntry zipEntry = zipStream.getNextEntry();
      ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
      byte[] byteReadBuffer = new byte[512];
      int byteReadCount;

      while (zipEntry != null) {
        if (zipEntry.isDirectory()) {
          addEntry(zipEntry.getName(), (byte[]) null);
        } else {
          while ((byteReadCount = zipStream.read(byteReadBuffer)) != -1) {
            outByteStream.write(byteReadBuffer, 0, byteReadCount);
          }
          addEntry(zipEntry.getName(), outByteStream.toByteArray());
          outByteStream.reset();
        }
        zipEntry = zipStream.getNextEntry();
      }
    } finally {
      try {
        zipStream.close();
      } catch (IOException e) {
        logger.debug("Unexpected error closing EDI Mapping Model Zip stream.", e);
      }
    }

    return this;
  }
  private int extractZipEntry(String out_path, ZipInputStream zip, int total_size, String mes) {
    BufferedOutputStream out = null;
    try {
      out = new BufferedOutputStream(new FileOutputStream(out_path));
    } catch (Exception e) {
      sendMessage(-2, 0, "Failed to create file: " + e.toString());
      return -1;
    }
    ;

    int total_read = 0;
    try {
      int len = zip.read(buf);
      while (len >= 0) {
        if (len > 0) out.write(buf, 0, len);
        total_read += len;
        sendMessage(total_read, total_size, mes);
        len = zip.read(buf);
        try {
          Thread.sleep(1);
        } catch (InterruptedException e) {
        }
      }
      out.flush();
      out.close();
    } catch (java.io.IOException e) {
      sendMessage(-2, 0, "Failed to write: " + e.toString());
      return -1;
    }

    return 0;
  }
Example #14
0
 private TreeSet<String> findClasses(String directory, String packageName) throws IOException {
   TreeSet<String> classes = new TreeSet<String>();
   if (directory.startsWith("file:") && directory.contains("!")) {
     String[] split = directory.split("!");
     URL jar = new URL(split[0]);
     ZipInputStream zip = new ZipInputStream(jar.openStream());
     ZipEntry entry = null;
     while ((entry = zip.getNextEntry()) != null) {
       if (entry.getName().startsWith("husacct/validate/domain/validation/ruletype")
           && entry.getName().endsWith(".class")) {
         final String className =
             entry.getName().replaceAll("[$].*", "").replaceAll("[.]class", "").replace('/', '.');
         classes.add(className);
       }
     }
   }
   File dir = new File(URLDecoder.decode(directory, "UTF-8"));
   if (!dir.exists()) {
     return classes;
   }
   File[] files = dir.listFiles();
   for (File file : files) {
     if (file.isDirectory()) {
       assert !file.getName().contains(".");
       classes.addAll(findClasses(file.getAbsolutePath(), packageName + "." + file.getName()));
     } else if (file.getName().endsWith(".class")) {
       classes.add(packageName + '.' + file.getName().substring(0, file.getName().length() - 6));
     }
   }
   return classes;
 }
Example #15
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);
  }
Example #16
0
    public ZipEntry getEntry(String entryName) {
      ZipEntry entry = null;

      if (_zipfile != null) {
        entry = _zipfile.getEntry(entryName);
      } else if (_url != null) {
        try {
          URLConnection con = _url.openConnection();
          con.connect();
          InputStream is = con.getInputStream();
          ZipInputStream zis = new ZipInputStream(is);
          ZipEntry ze;

          while ((ze = zis.getNextEntry()) != null) {
            String name = ze.getName();
            if (entryName.equals(name)) {
              entry = ze;
              break;
            }
          } // end while
        } catch (IOException ex) {
          entry = null;
        } // end try
      } // end if

      return entry;
    }
Example #17
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;
  }
Example #18
0
    public Enumeration<? extends ZipEntry> entries() {
      Enumeration<? extends ZipEntry> entries = null;

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

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

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

      return entries;
    }
Example #19
0
  /**
   * Extract files from or list a zip archive.
   *
   * @param context the current call Context
   * @param zipFile The pathname of the zip file: tilde expansion (see path.expand) will be
   *     performed.
   * @param files A character vector of recorded filepaths to be extracted: the default is to
   *     extract all files.
   * @param exdirUri The directory to extract files to (the equivalent of unzip -d). It will be
   *     created if necessary.
   * @param list If TRUE, list the files and extract none. The equivalent of unzip -l.
   * @param overwrite If TRUE, overwrite existing files, otherwise ignore such files. The equivalent
   *     of unzip -o.
   * @param junkpaths If TRUE, use only the basename of the stored filepath when extracting. The
   *     equivalent of unzip -j.
   * @return If list = TRUE, a data frame with columns Name, Length (the size of the uncompressed
   *     file) and Date (of class "POSIXct"). Otherwise, a character vector of the filepaths
   *     extracted to, invisibly.
   * @throws IOException
   */
  @Internal
  public static SEXP unzip(
      @Current Context context,
      String zipFile,
      Vector files,
      String exdirUri,
      boolean list,
      boolean overwrite,
      boolean junkpaths)
      throws IOException {

    ZipInputStream zin =
        new ZipInputStream(context.resolveFile(pathExpand(zipFile)).getContent().getInputStream());
    try {
      FileObject exdir = context.resolveFile(exdirUri);

      if (list) {
        throw new EvalException("unzip(list=true) not yet implemented");
      }

      ZipEntry entry;
      while ((entry = zin.getNextEntry()) != null) {
        if (unzipMatches(entry, files)) {
          unzipExtract(zin, entry, exdir, junkpaths, overwrite);
        }
      }
      context.setInvisibleFlag();

      return new IntArrayVector(0);
    } finally {
      zin.close();
    }
  }
 private static void unZipFile(InputStream source, FileObject projectRoot) throws IOException {
   try {
     ZipInputStream str = new ZipInputStream(source);
     ZipEntry entry;
     while ((entry = str.getNextEntry()) != null) {
       if (entry.isDirectory()) {
         FileUtil.createFolder(projectRoot, entry.getName());
       } else {
         FileObject fo = FileUtil.createData(projectRoot, entry.getName());
         FileLock lock = fo.lock();
         try {
           OutputStream out = fo.getOutputStream(lock);
           try {
             FileUtil.copy(str, out);
           } finally {
             out.close();
           }
         } finally {
           lock.releaseLock();
         }
       }
     }
   } finally {
     source.close();
   }
 }
  /**
   * 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);
        }
      }
    }
  }
Example #22
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");
      }
    }
  }
Example #23
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) {
       }
     }
   }
 }
 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();
   }
 }
Example #25
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;
  }
  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;
  }
 public ZipInputStream createInputStream() throws IOException {
   ZipInputStream stream = new ZipInputStream(inner.createInputStream());
   if (openEntry) {
     stream.getNextEntry();
   }
   return stream;
 }
Example #28
0
  @Test
  public void shouldSetTimestampOfEntries() throws IOException {
    Calendar cal = Calendar.getInstance();
    cal.set(1999, SEPTEMBER, 10);
    long old = getTimeRoundedToSeconds(cal.getTime());

    long now = getTimeRoundedToSeconds(new Date());

    try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(output)) {
      ZipEntry oldAndValid = new ZipEntry("oldAndValid");
      oldAndValid.setTime(old);
      out.putNextEntry(oldAndValid);

      ZipEntry current = new ZipEntry("current");
      current.setTime(now);
      out.putNextEntry(current);
    }

    try (ZipInputStream in = new ZipInputStream(Files.newInputStream(output))) {
      ZipEntry entry = in.getNextEntry();
      assertEquals("oldAndValid", entry.getName());
      assertEquals(old, entry.getTime());

      entry = in.getNextEntry();
      assertEquals("current", entry.getName());
      assertEquals(now, entry.getTime());
    }
  }
Example #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();
  }
  @Override
  public void analyze(Document doc, StreamSource src, Writer xrefOut) throws IOException {
    try (ZipInputStream zis = new ZipInputStream(src.getStream())) {
      ZipEntry entry;
      while ((entry = zis.getNextEntry()) != null) {
        String ename = entry.getName();

        if (xrefOut != null) {
          xrefOut.append("<br/><b>");
          Util.htmlize(ename, xrefOut);
          xrefOut.append("</b>");
        }

        doc.add(new TextField("full", ename, Store.NO));
        IFileAnalyzerFactory fac = AnalyzerGuru.find(ename);
        if (fac instanceof JavaClassAnalyzerFactory) {
          if (xrefOut != null) {
            xrefOut.append("<pre>");
          }

          JavaClassAnalyzer jca = (JavaClassAnalyzer) fac.getAnalyzer();
          jca.analyze(doc, new BufferedInputStream(zis), xrefOut);

          if (xrefOut != null) {
            xrefOut.append("</pre>");
          }
        }
      }
    }
  }