Esempio n. 1
0
  @Override
  public CompoundArtifactDelta getDelta(File baseline, File reactor) throws IOException {
    Map<String, ArtifactDelta> result = new LinkedHashMap<>();

    ZipFile jar = new ZipFile(baseline);
    try {
      ZipFile jar2 = new ZipFile(reactor);
      try {
        Map<String, ZipEntry> entries = toEntryMap(jar);
        Map<String, ZipEntry> entries2 = toEntryMap(jar2);

        Set<String> names = new TreeSet<>();
        names.addAll(entries.keySet());
        names.addAll(entries2.keySet());

        for (String name : names) {
          ZipEntry entry = entries.get(name);
          if (entry == null) {
            result.put(name, new SimpleArtifactDelta("not present in baseline"));
            continue;
          }
          ZipEntry entry2 = entries2.get(name);
          if (entry2 == null) {
            result.put(name, new SimpleArtifactDelta("present in baseline only"));
            continue;
          }

          InputStream is = jar.getInputStream(entry);
          try {
            InputStream is2 = jar2.getInputStream(entry2);
            try {
              ContentsComparator comparator = comparators.get(getContentType(name));
              ArtifactDelta differences = comparator.getDelta(is, is2);
              if (differences != null) {
                result.put(name, differences);
                continue;
              }
            } finally {
              IOUtil.close(is2);
            }
          } finally {
            IOUtil.close(is);
          }
        }
      } finally {
        try {
          jar2.close();
        } catch (IOException e) {
          // too bad
        }
      }
    } finally {
      try {
        jar.close();
      } catch (IOException e) {
        // ouch
      }
    }
    return !result.isEmpty() ? new CompoundArtifactDelta("different", result) : null;
  }
 protected void handleArchive(
     File file, String paResourceRootPath, Map<String, byte[]> resourceMap) {
   try {
     ZipFile zipFile = new ZipFile(file);
     Enumeration<? extends ZipEntry> entries = zipFile.entries();
     while (entries.hasMoreElements()) {
       ZipEntry zipEntry = (ZipEntry) entries.nextElement();
       String processFileName = zipEntry.getName();
       if (ProcessApplicationScanningUtil.isDeployable(processFileName)
           && isBelowPath(processFileName, paResourceRootPath)) {
         addResource(
             zipFile.getInputStream(zipEntry), resourceMap, file.getName() + "!", processFileName);
         // find diagram(s) for process
         Enumeration<? extends ZipEntry> entries2 = zipFile.entries();
         while (entries2.hasMoreElements()) {
           ZipEntry zipEntry2 = (ZipEntry) entries2.nextElement();
           String diagramFileName = zipEntry2.getName();
           if (ProcessApplicationScanningUtil.isDiagramForProcess(
               diagramFileName, processFileName)) {
             addResource(
                 zipFile.getInputStream(zipEntry),
                 resourceMap,
                 file.getName() + "!",
                 diagramFileName);
           }
         }
       }
     }
     zipFile.close();
   } catch (IOException e) {
     throw new ProcessEngineException("IOException while scanning archive '" + file + "'.", e);
   }
 }
 private static void GetAuxZipAliases(ZipFile file, LocalPackage pack) {
   ZipEntry ze;
   Enumeration<? extends ZipEntry> entries = file.entries();
   while (entries.hasMoreElements()) {
     ze = entries.nextElement();
     if (ze.getName().endsWith(".ms")) {
       if (ze.getName().equals("auto_include.ms")) {
         pack.addAutoInclude(new File(file.getName() + File.separator + ze.getName()));
       } else {
         try {
           pack.appendMS(
               Installer.parseISToString(file.getInputStream(ze)),
               new File(file.getName() + File.separator + ze.getName()));
         } catch (IOException ex) {
           Logger.getLogger(AliasCore.class.getName()).log(Level.SEVERE, null, ex);
         }
       }
     } else if (ze.getName().endsWith(".msa")) {
       try {
         pack.appendMSA(
             Installer.parseISToString(file.getInputStream(ze)),
             new File(file.getName() + File.separator + ze.getName()));
       } catch (IOException ex) {
         Logger.getLogger(AliasCore.class.getName()).log(Level.SEVERE, null, ex);
       }
     }
   }
 }
  private void fillLists(
      String zipFileName,
      List<BxDocument> documents,
      List<DocumentContentStructure> headerStructures)
      throws IOException, TransformationException, JDOMException, URISyntaxException {
    ZipFile zipFile = new ZipFile(new File(this.getClass().getResource(zipFileName).toURI()));
    List<ZipEntry> entries = getEntries(zipFile);

    HierarchicalReadingOrderResolver roa = new HierarchicalReadingOrderResolver();
    TrueVizToBxDocumentReader bxReader = new TrueVizToBxDocumentReader();
    HTMLToDocContentStructReader dcsReader = new HTMLToDocContentStructReader();

    for (ZipEntry ze : entries) {
      if (ze.getName().matches("^.*/" + sourceDir + ".*$")) {
        InputStream xis = zipFile.getInputStream(ze);
        InputStreamReader xisr = new InputStreamReader(xis);

        System.out.println(ze.getName());
        List<BxPage> pages = bxReader.read(xisr);
        documents.add(roa.resolve(new BxDocument().setPages(pages)));
      }
      if (ze.getName().matches("^.*/" + structureDir + ".*$")) {
        InputStream cis = zipFile.getInputStream(ze);
        InputStreamReader cisr = new InputStreamReader(cis);

        DocumentContentStructure hs = dcsReader.read(cisr);
        headerStructures.add(hs);
      }
    }
  }
Esempio n. 5
0
  public static void main(String[] args) throws Exception {
    Reader trainingFile = null;

    // Process arguments
    int restArgs = commandOptions.processOptions(args);

    // Check arguments
    if (restArgs != args.length) {
      commandOptions.printUsage(true);
      throw new IllegalArgumentException("Unexpected arg " + args[restArgs]);
    }
    if (trainFileOption.value == null) {
      commandOptions.printUsage(true);
      throw new IllegalArgumentException("Expected --train-file FILE");
    }
    if (modelFileOption.value == null) {
      commandOptions.printUsage(true);
      throw new IllegalArgumentException("Expected --model-file FILE");
    }

    // Get the CRF structure specification.
    ZipFile zipFile = new ZipFile(modelFileOption.value);
    ZipEntry zipEntry = zipFile.getEntry("crf-info.xml");
    CRFInfo crfInfo = new CRFInfo(zipFile.getInputStream(zipEntry));

    StringBuffer crfInfoBuffer = new StringBuffer();
    BufferedReader reader =
        new BufferedReader(new InputStreamReader(zipFile.getInputStream(zipEntry)));
    String line;
    while ((line = reader.readLine()) != null) {
      crfInfoBuffer.append(line).append('\n');
    }
    reader.close();

    // Create the CRF, and train it.
    CRF4 crf = createCRF(trainFileOption.value, crfInfo);

    // Create a new zip file for our output.  This will overwrite
    // the file we used for input.
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(modelFileOption.value));

    // Copy the CRF info xml to the output zip file.
    zos.putNextEntry(new ZipEntry("crf-info.xml"));
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(zos));
    writer.write(crfInfoBuffer.toString());
    writer.flush();
    zos.closeEntry();

    // Save the CRF classifier model to the output zip file.
    zos.putNextEntry(new ZipEntry("crf-model.ser"));
    ObjectOutputStream oos = new ObjectOutputStream(zos);
    oos.writeObject(crf);
    oos.flush();
    zos.closeEntry();
    zos.close();
  }
Esempio n. 6
0
 /** @see java.net.URLConnection#getInputStream() */
 @Override
 public InputStream getInputStream() throws IOException {
   if (!connected) connect();
   if (directAccess != null) return new FileInputStream(directAccess);
   if (zipFile == null) throw new IOException("no zip file defined");
   try {
     if (nameEntries == null || nameEntries.isEmpty())
       throw new IOException("no entry name specified");
     ZipEntry entry = zipFile.getEntry(nameEntries.get(0));
     if (entry == null)
       throw new FileNotFoundException("The entry " + nameEntries.get(0) + " could not be found");
     if (nameEntries.size() == 1) {
       return new ArchiveInputStream(zipFile.getInputStream(entry));
     }
     String nameEntry = nameEntries.get(1);
     ZipInputStream zis = new ZipInputStream(zipFile.getInputStream(entry));
     boolean closeZis = true;
     try {
       ZipEntry subZP;
       ZipEntry found = null;
       while ((subZP = zis.getNextEntry()) != null) {
         if (subZP.getName().equals(nameEntry) || subZP.getName().equals(nameEntry + "/")) {
           found = subZP;
           break;
         }
       }
       if (found == null)
         throw new FileNotFoundException("Cannot find the file at " + url.getFile());
       if (found.isDirectory()) throw new IOException("A file was expected at " + url.getFile());
       closeZis = false;
       return new ArchiveInputStream(zis);
     } finally {
       if (closeZis) {
         try {
           zis.close();
         } catch (IOException e) {
           LOG.debug("Could not close the zip input stream");
         }
       }
     }
   } catch (IOException e) {
     try {
       zipFile.close();
     } catch (IOException e2) {
       LOG.debug("Could not close the zip file");
     }
     throw e;
   } catch (RuntimeException e) {
     try {
       zipFile.close();
     } catch (IOException e2) {
       LOG.debug("Could not close the zip file");
     }
     throw e;
   }
 }
  /**
   * This method uses puts the new content of the differenceFile into the Jar targetFile, replacing
   * the files as necessary.
   *
   * @param targetFile
   * @param differenceFile - zip containing the files you want to add into the targetFile. This
   *     differenceFile must exsit and have at least 1 entry, or a ZipException will be thrown.
   * @throws ZipException - if a ZIP error has occurred
   * @throws IOException - if an I/O error has occurred
   */
  public static void putDifsInJar(File targetFile, File differenceFile)
      throws ZipException, IOException {
    File temp = new File(targetFile.getAbsolutePath() + ".temp");
    ZipFile sourceZipFile = new ZipFile(targetFile);
    ZipFile diffZipFile = new ZipFile(differenceFile);

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

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

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

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

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

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

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

    copyInputStream(fis, fos);

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

    temp.delete();
    temp.deleteOnExit();
  }
Esempio n. 8
0
  @Override
  public void executeTask() throws Exception {
    HMCLog.log("Extracting install profiles...");

    ZipFile zipFile = new ZipFile(forgeInstaller);
    ZipEntry entry = zipFile.getEntry("install_profile.json");
    String content = NetUtils.getStreamContent(zipFile.getInputStream(entry));
    InstallProfile profile = C.gsonPrettyPrinting.fromJson(content, InstallProfile.class);

    File from = new File(gameDir, "versions" + File.separator + profile.install.minecraft);
    if (!from.exists())
      if (MessageBox.Show(C.i18n("install.no_version_if_intall")) == MessageBox.YES_OPTION) {
        if (!mp.version().install(profile.install.minecraft, null))
          throw new IllegalStateException(C.i18n("install.no_version"));
      } else throw new IllegalStateException(C.i18n("install.no_version"));

    File to = new File(gameDir, "versions" + File.separator + profile.install.target);
    to.mkdirs();

    HMCLog.log(
        "Copying jar..."
            + profile.install.minecraft
            + ".jar to "
            + profile.install.target
            + ".jar");
    FileUtils.copyFile(
        new File(from, profile.install.minecraft + ".jar"),
        new File(to, profile.install.target + ".jar"));
    HMCLog.log("Creating new version profile..." + profile.install.target + ".json");
    /*
     * for (MinecraftLibrary library : profile.versionInfo.libraries)
     * if (library.name.startsWith("net.minecraftforge:forge:"))
     * library.url = installerVersion.universal;
     */
    FileUtils.write(
        new File(to, profile.install.target + ".json"),
        C.gsonPrettyPrinting.toJson(profile.versionInfo));

    HMCLog.log("Extracting universal forge pack..." + profile.install.filePath);

    entry = zipFile.getEntry(profile.install.filePath);
    InputStream is = zipFile.getInputStream(entry);

    MinecraftLibrary forge = new MinecraftLibrary(profile.install.path);
    forge.init();
    File file = new File(gameDir, "libraries/" + forge.formatted);
    file.getParentFile().mkdirs();
    try (FileOutputStream fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos)) {
      int c;
      while ((c = is.read()) != -1) bos.write((byte) c);
    }
  }
Esempio n. 9
0
  public static void validateCDSbySchema(ZipFile zf, ZipEntry ze)
      throws IOException, ValidationException {
    try {
      // TODO validate using CDS.xsd as well

      InputStream cdsStream = zf.getInputStream(ze);
      validateSchema(cdsStream, sdmxMessageSchema);

      cdsStream = zf.getInputStream(ze);
      validateSchema(cdsStream, sdmxCompactDataSchema);
    } catch (SAXException e) {
      throw new ValidationException("Failed to validate CDS", e);
    }
  }
Esempio n. 10
0
  static void optimize(final File f) throws IOException {
    if (nodebug && f.getName().contains("debug")) {
      return;
    }

    if (f.isDirectory()) {
      File[] files = f.listFiles();
      for (int i = 0; i < files.length; ++i) {
        optimize(files[i]);
      }
    } else if (f.getName().endsWith(".jar")) {
      File g = new File(f.getParentFile(), f.getName() + ".new");
      ZipFile zf = new ZipFile(f);
      ZipOutputStream out = new ZipOutputStream(new FileOutputStream(g));
      Enumeration<? extends ZipEntry> e = zf.entries();
      byte[] buf = new byte[10000];
      while (e.hasMoreElements()) {
        ZipEntry ze = e.nextElement();
        if (ze.isDirectory()) {
          out.putNextEntry(ze);
          continue;
        }
        out.putNextEntry(ze);
        if (ze.getName().endsWith(".class")) {
          ClassReader cr = new ClassReader(zf.getInputStream(ze));
          // cr.accept(new ClassDump(), 0);
          cr.accept(new ClassVerifier(), 0);
        }
        InputStream is = zf.getInputStream(ze);
        int n;
        do {
          n = is.read(buf, 0, buf.length);
          if (n != -1) {
            out.write(buf, 0, n);
          }
        } while (n != -1);
        out.closeEntry();
      }
      out.close();
      zf.close();
      if (!f.delete()) {
        throw new IOException("Cannot delete file " + f);
      }
      if (!g.renameTo(f)) {
        throw new IOException("Cannot rename file " + g);
      }
    }
  }
Esempio n. 11
0
  private boolean installBundle(ZipFile zipFile, String location, Application application) {

    log.info("processLibsBundle entryName " + location);
    this.bundleDebug.installExternalBundle(location);
    String fileNameFromEntryName = Utils.getFileNameFromEntryName(location);
    String packageNameFromEntryName = Utils.getPackageNameFromEntryName(location);
    if (packageNameFromEntryName == null || packageNameFromEntryName.length() <= 0) {
      return false;
    }
    File archvieFile =
        new File(new File(application.getFilesDir().getParentFile(), "lib"), fileNameFromEntryName);
    if (OpenAtlas.getInstance().getBundle(packageNameFromEntryName) != null) {
      return false;
    }
    try {
      if (archvieFile.exists()) {
        OpenAtlas.getInstance().installBundle(packageNameFromEntryName, archvieFile);
      } else {
        OpenAtlas.getInstance()
            .installBundle(
                packageNameFromEntryName, zipFile.getInputStream(zipFile.getEntry(location)));
      }
      log.info("Succeed to install bundle " + packageNameFromEntryName);
      return true;
    } catch (Throwable e) {
      Log.e("BundlesInstaller", "Could not install bundle.", e);
      return false;
    }
  }
Esempio n. 12
0
  public static Part getBinaryPart(ZipFile zf, ContentTypeManager ctm, String resolvedPartUri)
      throws Docx4JException {

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

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

      log.info("Stored as BinaryData");

    } catch (IOException ioe) {
      ioe.printStackTrace();
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException exc) {
          exc.printStackTrace();
        }
      }
    }
    return part;
  }
Esempio n. 13
0
  private static InputStream getInputStreamFromZippedPart(ZipFile zf, String partName)
      throws IOException {

    InputStream in = null;
    in = zf.getInputStream(zf.getEntry(partName));
    return in;
  }
Esempio n. 14
0
 /**
  * Unzip a zip file into a directory.
  *
  * @param zipFile The zip file to be unzipped.
  * @param dest the destination directory.
  * @throws IOException if the destination does not exist or is not a directory, or if the zip file
  *     cannot be extracted.
  */
 public static void unzip(ZipFile zipFile, File dest) throws IOException {
   Enumeration<? extends ZipEntry> entries = zipFile.entries();
   if (dest.exists() && dest.isDirectory()) {
     while (entries.hasMoreElements()) {
       ZipEntry entry = entries.nextElement();
       if (!entry.isDirectory()) {
         File destFile = new File(dest, entry.getName());
         createFileWithPath(destFile);
         InputStream in = new BufferedInputStream(zipFile.getInputStream(entry));
         OutputStream out = new BufferedOutputStream(new FileOutputStream(destFile));
         byte[] buffer = new byte[2048];
         for (; ; ) {
           int nBytes = in.read(buffer);
           if (nBytes <= 0) break;
           out.write(buffer, 0, nBytes);
         }
         out.flush();
         out.close();
         in.close();
       }
     }
   } else {
     throw new IOException(
         "Destination " + dest.getAbsolutePath() + " is not a directory or does not exist");
   }
 }
  /**
   * 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();
      }
    }
  }
Esempio n. 16
0
 public Properties searchForVersionProperties() {
   try {
     FMLLog.log(
         getModId(),
         Level.FINE,
         "Attempting to load the file version.properties from %s to locate a version number for %s",
         getSource().getName(),
         getModId());
     Properties version = null;
     if (getSource().isFile()) {
       ZipFile source = new ZipFile(getSource());
       ZipEntry versionFile = source.getEntry("version.properties");
       if (versionFile != null) {
         version = new Properties();
         version.load(source.getInputStream(versionFile));
       }
       source.close();
     } else if (getSource().isDirectory()) {
       File propsFile = new File(getSource(), "version.properties");
       if (propsFile.exists() && propsFile.isFile()) {
         version = new Properties();
         FileInputStream fis = new FileInputStream(propsFile);
         version.load(fis);
         fis.close();
       }
     }
     return version;
   } catch (Exception e) {
     Throwables.propagateIfPossible(e);
     FMLLog.log(getModId(), Level.FINEST, "Failed to find a usable version.properties file");
     return null;
   }
 }
Esempio n. 17
0
  public static final void unzip(File zip, File extractTo) throws IOException {
    ZipFile archive = new ZipFile(zip);
    Enumeration e = archive.entries();
    while (e.hasMoreElements()) {
      ZipEntry entry = (ZipEntry) e.nextElement();
      File file = new File(extractTo, entry.getName());
      if (entry.isDirectory() && !file.exists()) {
        file.mkdirs();
      } else {
        if (!file.getParentFile().exists()) {
          file.getParentFile().mkdirs();
        }

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

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

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

        in.close();
        out.close();
      }
    }
  }
Esempio n. 18
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;
  }
  private InputStream getInputStreamFromFprFile(File file) throws IOException {
    final ZipFile fprFile = new ZipFile(file);
    try {
      final InputStream reportStream =
          fprFile.getInputStream(fprFile.getEntry(FortifyConstants.AUDIT_FVDL_FILE));
      return new InputStream() {
        @Override
        public int read() throws IOException {
          return reportStream.read();
        }

        @Override
        public void close() throws IOException {
          try {
            reportStream.close();
          } finally {
            fprFile.close();
          }
        }
      };
    } catch (IOException e) {
      fprFile.close();
      throw e;
    }
  }
Esempio n. 20
0
  @Test
  public void includeAsClasses() throws Exception {
    String baseDir = testIssue("flexmojos-247").getBasedir();
    File target = new File(baseDir, "target");
    Assert.assertTrue(target.exists());

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

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

    // must have both classes and the uri
    MatcherAssert.assertThat(catalog, StringContains.containsString("AClass"));
    MatcherAssert.assertThat(catalog, StringContains.containsString("BClass"));
    MatcherAssert.assertThat(
        catalog, StringContains.containsString("http://flexmojos.sonatype.org/tests"));
  }
  public void testCoverageContents() throws Exception {
    final Long processId = issueProcessAndWaitForTermination();

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

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

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

    ZipFile zipFile = new ZipFile(file);
    try {
      // TODO: change this expectation once we normalize the raster file name
      String rasterName = RASTER_LAYER.getPrefix() + ":" + RASTER_LAYER.getLocalPart() + ".tiff";
      ZipEntry nextEntry = zipFile.getEntry(rasterName);
      assertNotNull(nextEntry);
      InputStream coverageInputStream = zipFile.getInputStream(nextEntry);
      // Use a file, geotiffreader might not work well reading out of a plain input stream
      File covFile = new File(file.getParentFile(), "coverage.tiff");
      IOUtils.copy(coverageInputStream, covFile);
      GeoTiffReader geoTiffReader = new GeoTiffReader(covFile);
      GridCoverage2D coverage = geoTiffReader.read(null);
      CoordinateReferenceSystem crs = coverage.getCoordinateReferenceSystem();
      assertEquals(CRS.decode("EPSG:4326", true), crs);
    } finally {
      zipFile.close();
    }
  }
  /*
   * Load a class from a file in an archive.  We currently assume that
   * the file is a Zip archive.
   *
   * Returns null if the class wasn't found.
   */
  private byte[] loadFromArchive(ZipFile zip, String name) {
    ZipEntry entry;

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

    ByteArrayOutputStream byteStream;
    InputStream stream;
    int count;

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

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

    // System.out.println("  loaded from Zip");
    return byteStream.toByteArray();
  }
Esempio n. 23
0
 public static void unzip(File dest, String jar) throws IOException {
   dest.mkdirs();
   ZipFile zf = new ZipFile(jar);
   try {
     Enumeration es = zf.entries();
     while (es.hasMoreElements()) {
       ZipEntry je = (ZipEntry) es.nextElement();
       String n = je.getName();
       File f = new File(dest, n);
       if (je.isDirectory()) {
         f.mkdirs();
       } else {
         if (f.exists()) {
           f.delete();
         } else {
           f.getParentFile().mkdirs();
         }
         InputStream is = zf.getInputStream(je);
         FileOutputStream os = new FileOutputStream(f);
         try {
           copyStream(is, os);
         } finally {
           os.close();
         }
       }
       long time = je.getTime();
       if (time != -1) f.setLastModified(time);
     }
   } finally {
     zf.close();
   }
 }
Esempio n. 24
0
  @NotNull
  @Override
  public byte[] contentsToByteArray(@NotNull String relativePath) throws IOException {
    FileAccessorCache.Handle<ZipFile> zipRef;

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

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

    throw new FileNotFoundException(getFile() + "!/" + relativePath);
  }
Esempio n. 25
0
  public static void registerModInJar(String modid, File jar) {
    try {
      ZipFile zipfile = new ZipFile(jar);
      Enumeration enumeration = zipfile.entries();
      while (enumeration.hasMoreElements()) {
        ZipEntry zipentry = (ZipEntry) enumeration.nextElement();
        String fileName = zipentry.getName();
        Path path1 = Paths.get(fileName);
        Path path2 = Paths.get("assets", modid, "books");

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

      zipfile.close();
    } catch (Exception e) {
    }
  }
Esempio n. 26
0
 private static void search(File[] files) {
   try {
     for (File f : files) {
       if (f.isDirectory()) {
         search(f.listFiles());
       } else {
         ZipFile jar = new ZipFile(f);
         Enumeration enumration = jar.entries();
         while (enumration.hasMoreElements()) {
           ZipEntry zipEntry = (ZipEntry) enumration.nextElement();
           InputStreamReader isr = new InputStreamReader(jar.getInputStream(zipEntry));
           BufferedReader br = new BufferedReader(isr);
           String line = br.readLine();
           int line_num = 1;
           while (null != line) {
             // System.out.println(line);
             if (line.toLowerCase().contains(keywords.toLowerCase())) {
               System.out.println(
                   f.getPath() + "," + zipEntry.getName() + "," + "line number = " + line_num);
             }
             line = br.readLine();
             line_num++;
           }
         }
       }
     }
   } catch (ZipException z_e) {
     z_e.printStackTrace();
   } catch (IOException io_e) {
     io_e.printStackTrace();
   }
 }
 private String readFromZipFile(String filename) {
   ZipFile zip = null;
   String str = null;
   try {
     InputStream fileStream = null;
     File applicationPackage = new File(mActivity.getApplication().getPackageResourcePath());
     zip = new ZipFile(applicationPackage);
     if (zip == null) return null;
     ZipEntry fileEntry = zip.getEntry(filename);
     if (fileEntry == null) return null;
     fileStream = zip.getInputStream(fileEntry);
     str = readStringFromStream(fileStream);
   } catch (IOException ioe) {
     Log.e(LOGTAG, "error reading zip file: " + filename, ioe);
   } finally {
     try {
       if (zip != null) zip.close();
     } catch (IOException ioe) {
       // catch this here because we can continue even if the
       // close failed
       Log.e(LOGTAG, "error closing zip filestream", ioe);
     }
   }
   return str;
 }
  /**
   * 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. 29
0
 private void checkLoadedModForPermissionClass(File modFile) {
   try {
     Pattern p = Pattern.compile("permission", Pattern.CASE_INSENSITIVE);
     if (modFile.isDirectory()) {
       for (File file : modFile.listFiles()) {
         checkLoadedModForPermissionClass(file);
       }
     } else if ((modFile.getName().endsWith(".zip")) || (modFile.getName().endsWith(".jar"))) {
       ZipFile zip = new ZipFile(modFile);
       Enumeration entries = zip.entries();
       while (entries.hasMoreElements()) {
         ZipEntry zipentry = (ZipEntry) entries.nextElement();
         if (zipentry != null
             && zipentry.getName().endsWith(".class")
             && p.matcher(zipentry.getName()).find()) {
           checkLoadedClass(zip.getInputStream(zipentry));
         }
       }
       zip.close();
     } else if (modFile.getName().endsWith(".class") && p.matcher(modFile.getName()).find()) {
       checkLoadedClass(new FileInputStream(modFile));
     }
   } catch (IOException e) {
   }
 }
Esempio n. 30
0
  public static final boolean unzip(File file, File target) throws MojoExecutionException {
    Enumeration entries;
    ZipFile zipFile;

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

    try {

      zipFile = new ZipFile(file);

      entries = zipFile.entries();

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

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

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

      zipFile.close();
      return true;

    } catch (IOException ioe) {
      throw new MojoExecutionException("Unzip Error", ioe);
    }
  }