示例#1
0
  /** @see java.net.URLConnection#connect() */
  @Override
  public void connect() throws IOException {
    this.connected = true;
    String file = url.getFile();
    int index = file.indexOf("!/");
    if (index == -1) {
      // It is a direct file access
      this.directAccess = new File(file);
      if (!directAccess.exists())
        throw new FileNotFoundException("Cannot find the file at " + file);
      if (directAccess.isDirectory()) throw new IOException("A file was expected at " + file);
      return;
    }
    File f = new File(file.substring(0, index));
    if (!f.exists())
      throw new FileNotFoundException("Cannot find the file at " + f.getAbsolutePath());
    if (f.isDirectory()) throw new IOException("A zip file was expected at " + f.getAbsolutePath());
    this.zipFile = new ZipFile(f);
    try {
      int fromIndex = index + 2;
      index = file.indexOf("!/", fromIndex);
      String nameEntry;
      if (index == -1) nameEntry = file.substring(fromIndex);
      else nameEntry = file.substring(fromIndex, index);

      ZipEntry entry = zipFile.getEntry(nameEntry);
      if (entry == null)
        throw new FileNotFoundException(
            "Cannot find the file at " + file.substring(0, index == -1 ? file.length() : index));
      if (zipFile.getEntry(nameEntry + "/") != null)
        throw new IOException(
            "A "
                + (index == -1 ? "" : "zip")
                + " file was expected at "
                + file.substring(0, index == -1 ? file.length() : index));
      nameEntries = new ArrayList<String>();
      nameEntries.add(nameEntry);
      if (index == -1) {
        // there is no more entries
        return;
      }
      nameEntry = file.substring(index + 2);
      // We add it without checking if it exists to avoid reading twice the ZipInputStream
      nameEntries.add(nameEntry);
    } catch (IOException e) {
      try {
        zipFile.close();
      } catch (IOException e2) {
        LOG.debug("Could not close the zip file");
      }
      throw e;
    } catch (RuntimeException e) {
      try {
        zipFile.close();
      } catch (IOException e2) {
        LOG.debug("Could not close the zip file");
      }
      throw e;
    }
  }
示例#2
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);
    }
  }
示例#3
0
  // TODO: Needs optimization
  private void writeWithCorrectEncoding(
      File zipFile, String entryName, File valuesDir, String resourceDir, boolean isClassifier)
      throws IOException {
    String encoding = null;
    ZipFile zip = new ZipFile(zipFile);
    BufferedReader in =
        new BufferedReader(new InputStreamReader(zip.getInputStream(zip.getEntry(entryName))));
    try {
      String line = in.readLine();

      while (line != null) {
        if (line.startsWith("\"Content-Type:")) {
          int i = line.indexOf("charset=");
          try {
            encoding = line.substring(i + 8, line.length() - 1).split(" ")[0];
            this.getLog().info("Encoding found: " + encoding);
          } catch (Exception e) {
          }
          break;
        }
        line = in.readLine();
      }

      if (encoding == null) {
        encoding = System.getProperty("file.encoding");
      }
      File outputFile =
          new File(valuesDir, entryName.substring(0, entryName.lastIndexOf(".")) + ".xml");

      PoTransformer.transformToStrings(
          new ZipFile(zipFile).getInputStream(zip.getEntry(entryName)), outputFile, encoding);
      /**
       * We need to copy default resources to main resource directory. Not ideal but it keeps the
       * Android Eclipse plugin working
       */
      if (isClassifier) {
        FileUtils.copyFileToDirectory(outputFile, new File(resourceDir, "values"));
      }
    } finally {
      if (zip != null) {
        try {
          zip.close();
        } catch (IOException e) {
        }
      }
      if (in != null) {
        in.close();
      }
    }
  }
示例#4
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;
    }
示例#5
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;
   }
 }
示例#6
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;
  }
 /**
  * This method will check a jar file for a manifest, and, if it has it, find the value for the
  * given property.
  *
  * <p>If either the jar, manifest or the property are not found, return null.
  *
  * @param systemJarFile
  * @param propertyName
  * @return
  */
 public static String getJarProperty(File systemJarFile, String propertyName) {
   if (systemJarFile.canRead()) {
     ZipFile jar = null;
     try {
       jar = new ZipFile(systemJarFile);
       ZipEntry manifest = jar.getEntry("META-INF/MANIFEST.MF"); // $NON-NLS-1$
       Properties props = new Properties();
       props.load(jar.getInputStream(manifest));
       String value = (String) props.get(propertyName);
       return value;
     } catch (IOException e) {
       // Intentionally empty
       return null;
     } finally {
       if (jar != null) {
         try {
           jar.close();
         } catch (IOException e) {
           // Intentionally empty
           return null;
         }
       }
     }
   }
   return null;
 }
  @Override
  @Nullable
  Resource getResource(String name, boolean flag) {
    JarMemoryLoader loader = myMemoryLoader != null ? myMemoryLoader.get() : null;
    if (loader != null) {
      Resource resource = loader.getResource(name);
      if (resource != null) return resource;
    }

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

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

        @Override
        public void close() throws IOException {
          try {
            reportStream.close();
          } finally {
            fprFile.close();
          }
        }
      };
    } catch (IOException e) {
      fprFile.close();
      throw e;
    }
  }
示例#10
0
  @NotNull
  private EntryInfo getOrCreate(
      @NotNull String entryName, Map<String, EntryInfo> map, @NotNull ZipFile zip) {
    EntryInfo info = map.get(entryName);

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

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

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

    return info;
  }
示例#11
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;
  }
示例#12
0
文件: JarLoader.java 项目: sprig/MPS
 @Nullable
 @Override
 /*package*/ Resource getResource(String name, boolean flag) {
   final long started = (myDebugTime ? System.nanoTime() : 0);
   ZipFile file = null;
   try {
     file = acquireZipFile();
     if (file == null) {
       return null;
     }
     ZipEntry entry = file.getEntry(name);
     if (entry != null) {
       return new JarLoader.MyResource(entry, new URL(getBaseURL(), name));
     }
   } catch (Exception e) {
     return null;
   } finally {
     try {
       releaseZipFile(file);
     } catch (IOException ignored) {
     }
     final long doneFor = (myDebugTime ? System.nanoTime() - started : 0);
     if (doneFor > NS_THRESHOLD) {
       System.out.println(doneFor / 1000000 + " ms for jar loader get resource:" + name);
     }
   }
   return null;
 }
示例#13
0
 /** Attempts to open the zip entry. */
 public void connect() throws IOException {
   this.zipFile = new ZipFile(file);
   this.zipEntry = zipFile.getEntry(zipEntryName);
   if (zipEntry == null)
     throw new IOException("Entry " + zipEntryName + " not found in file " + file);
   this.connected = true;
 }
示例#14
0
  /**
   * Checks the contents of the specified zip entry.
   *
   * @param file file to be checked
   * @param data expected file contents
   * @throws IOException I/O exception
   */
  private static void checkEntry(final String file, final byte[] data) throws IOException {

    ZipFile zf = null;
    try {
      zf = new ZipFile(TMPZIP);
      final ZipEntry ze = zf.getEntry(file);
      assertNotNull("File not found: " + file, ze);
      final DataInputStream is = new DataInputStream(zf.getInputStream(ze));
      final byte[] dt = new byte[(int) ze.getSize()];
      is.readFully(dt);
      assertTrue(
          "Wrong contents in file \""
              + file
              + "\":"
              + Prop.NL
              + "Expected: "
              + string(data)
              + Prop.NL
              + "Found: "
              + string(dt),
          eq(data, dt));
    } finally {
      if (zf != null) zf.close();
    }
  }
  /**
   * @param garFile GAR file.
   * @param hasDescr Whether GAR file has descriptor.
   * @throws IOException If GAR file is not found.
   * @return Whether GAR file structure is correct.
   */
  private boolean checkStructure(File garFile, boolean hasDescr) throws IOException {
    ZipFile zip = new ZipFile(garFile);

    String descr = "META-INF/ignite.xml";

    ZipEntry entry = zip.getEntry(descr);

    if (entry == null && !hasDescr) {
      if (log().isInfoEnabled()) {
        log()
            .info(
                "Process deployment without descriptor file [path="
                    + descr
                    + ", file="
                    + garFile.getAbsolutePath()
                    + ']');
      }

      return true;
    } else if (entry != null && hasDescr) {
      InputStream in = null;

      try {
        in = new BufferedInputStream(zip.getInputStream(entry));

        return true;
      } finally {
        U.close(in, log());
      }
    } else return false;
  }
示例#16
0
  public ApkMetaData read(File file) throws PackReadException {
    if (!file.exists() || !file.isFile())
      throw new PackReadException(file.getAbsolutePath() + ":找到文件或不是apk文件");

    ZipFile zip = null;
    InputStream is = null;
    try {
      zip = new ZipFile(file);
      is = zip.getInputStream(zip.getEntry("AndroidManifest.xml"));
      Document dm =
          DocumentBuilderFactory.newInstance()
              .newDocumentBuilder()
              .parse(new ByteArrayInputStream(AXMLPrinter2.parse(is).getBytes("UTF-8")));
      Element el = (Element) dm.getElementsByTagName("manifest").item(0);
      return new ApkMetaData(
          Integer.parseInt(el.getAttribute("android:versionCode")), // 可能为空串
          el.getAttribute("android:versionName"),
          el.getAttribute("package"),
          file.length());
    } catch (Exception e) {
      throw new PackReadException("无法解析apk文件:" + file.getAbsolutePath(), e);
    } finally {
      try {
        if (is != null) is.close(); // 释放zip文件流
      } catch (Exception e) {
        e.printStackTrace();
      }
      try {
        if (zip != null) zip.close(); // 释放zip文件流
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
示例#17
0
  /*
   * (non-Javadoc)
   *
   * @see java.lang.Thread#run()
   */
  @Override
  public void run() {

    if (mArchive == null) {
      Log.e(this.getClass().getSimpleName(), "Archive is null");
      sendError(new FileNotFoundException("Archive not found."));
    } else {
      try {
        ZipEntry entry = null;
        String entryName = null;
        if (mClearThumbnails) {
          clearFiles();
        }
        Iterator<String> iPictures = mPictures.iterator();
        int pos = 0;

        List<String> files = Arrays.asList(mCacheDir.list());
        Bitmap thumb = null;
        OutputStream thumbOS = null;
        File thumbFile = null;
        while (mContinueCreation && iPictures.hasNext()) {
          entryName = iPictures.next();
          entry = mArchive.getEntry(entryName);
          // Build the thumbnail file name
          String thumbName = THUMBS_PREFIX + entryName.substring(entryName.lastIndexOf('/') + 1);
          thumbFile = new File(mCacheDir, thumbName);
          // Create the file only if it doesn't already exist
          if (!files.contains(thumbName)) {
            thumb = BitmapLoader.load(mContext, mArchive, entry, mThumbWidth, null);

            if (thumb != null) {
              thumbOS = new FileOutputStream(thumbFile);

              thumb.compress(CompressFormat.JPEG, 75, thumbOS);

              thumbOS.flush();
              thumbOS.close();
              thumb.recycle();
            } else {
              sendError(
                  new IOException("This archive is corrupt or contains bad character encoding."));
              stopCreation();
            }
          }

          // Provide the UI with the filename of the generated
          // thumbnail
          mThumbnails.put(entryName, thumbFile.getAbsolutePath());
          sendThumbnail(pos);
          pos++;
        }
      } catch (Exception e) {
        Log.e(this.getClass().getSimpleName(), "Error while creating thumbnail.", e);
        sendError(e);
      } catch (OutOfMemoryError e) {
        Log.e(this.getClass().getSimpleName(), "mem error", e);
        sendError(e);
      }
    }
  }
示例#18
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);
  }
示例#19
0
  private static InputStream getInputStreamFromZippedPart(ZipFile zf, String partName)
      throws IOException {

    InputStream in = null;
    in = zf.getInputStream(zf.getEntry(partName));
    return in;
  }
  /*
   * 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();
  }
  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;
    }
  }
  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();
    }
  }
示例#23
0
  /**
   * overriding getResource() because we want to search FIRST in this ClassLoader, then the parent,
   * the path, etc.
   */
  public URL getResource(String name) {
    try {
      if (jar != null) {
        ZipFile zipFile = jar.getZipFile();
        ZipEntry entry = zipFile.getEntry(name);
        if (entry != null) {
          return new URL(getResourceAsPath(name));
        }
      }

      Object obj = resourcesHash.get(name);
      if (obj instanceof JARClassLoader) {
        JARClassLoader classLoader = (JARClassLoader) obj;
        return classLoader.getResource(name);
      } else {
        URL ret = getSystemResource(name);
        if (ret != null) {
          Log.log(
              Log.DEBUG,
              JARClassLoader.class,
              "Would have returned null for getResource(" + name + ")");
          Log.log(Log.DEBUG, JARClassLoader.class, "returning(" + ret + ")");
        }
        return ret;
      }
    } catch (IOException io) {
      Log.log(Log.ERROR, this, io);
      return null;
    }
  } // }}}
示例#24
0
 private ZipEntry entry(TPath path) {
   String pathString = path.toPathString();
   if (pathString.startsWith("/")) {
     pathString = pathString.substring(1);
   }
   return file.getEntry(pathString);
 }
示例#25
0
 public byte[] getBytes() throws EGLModelException {
   EGLElement pkg = (EGLElement) getParent();
   if (pkg instanceof EglarPackageFragment) {
     EglarPackageFragmentRoot root = (EglarPackageFragmentRoot) pkg.getParent();
     ZipFile zip = null;
     try {
       zip = root.getJar();
       String entryName =
           CharOperation.concatWith(((PackageFragment) pkg).names, getElementName(), '/');
       ZipEntry ze = zip.getEntry(entryName);
       if (ze != null) {
         return org.eclipse.edt.ide.core.internal.model.util.Util.getZipEntryByteContent(ze, zip);
       }
       throw new EGLModelException(
           new EGLModelStatus(IEGLModelStatusConstants.ELEMENT_DOES_NOT_EXIST, this));
     } catch (IOException ioe) {
       throw new EGLModelException(ioe, IEGLModelStatusConstants.IO_EXCEPTION);
     } catch (CoreException e) {
       if (e instanceof EGLModelException) {
         throw (EGLModelException) e;
       } else {
         throw new EGLModelException(e);
       }
     } finally {
       EGLModelManager.getEGLModelManager().closeZipFile(zip);
     }
   } else {
     IFile file = (IFile) getResource();
     return Util.getResourceContentsAsByteArray(file);
   }
 }
示例#26
0
  public static void unZipFile(String zipFileName, String srcFileName, String destFileName)
      throws IOException {
    File destFile = new File(destFileName);
    if (!destFile.exists()) {
      File tmpDir = destFile.getParentFile();
      if (!tmpDir.exists()) {
        tmpDir.mkdirs();
      }

      destFile.createNewFile();
    }

    FileOutputStream out = new FileOutputStream(destFile);
    try {
      ZipFile zipFile = new ZipFile(zipFileName);
      ZipEntry zipEntry = zipFile.getEntry(srcFileName);
      if (zipEntry != null) {
        InputStream is = zipFile.getInputStream(zipEntry);
        int len = -1;
        byte[] buffer = new byte[512];
        while ((len = is.read(buffer, 0, 512)) != -1) {
          out.write(buffer, 0, len);
          out.flush();
        }

        is.close();
      }
      zipFile.close();
    } catch (IOException e) {
      // e.printStackTrace();
      throw e;
    } finally {
      out.close();
    }
  }
 private String readFromZipFile(String filename) {
   ZipFile zip = null;
   String str = null;
   try {
     InputStream fileStream = null;
     File applicationPackage = new File(mActivity.getApplication().getPackageResourcePath());
     zip = new ZipFile(applicationPackage);
     if (zip == null) return null;
     ZipEntry fileEntry = zip.getEntry(filename);
     if (fileEntry == null) return null;
     fileStream = zip.getInputStream(fileEntry);
     str = readStringFromStream(fileStream);
   } catch (IOException ioe) {
     Log.e(LOGTAG, "error reading zip file: " + filename, ioe);
   } finally {
     try {
       if (zip != null) zip.close();
     } catch (IOException ioe) {
       // catch this here because we can continue even if the
       // close failed
       Log.e(LOGTAG, "error closing zip filestream", ioe);
     }
   }
   return str;
 }
 public byte[] patchClassInJar(String name, byte[] bytes, String ObfName, File location) {
   try {
     // open the jar as zip
     ZipFile zip = new ZipFile(location);
     // find the file inside the zip that is called te.class or
     // net.minecraft.entity.monster.EntityCreeper.class
     // replacing the . to / so it would look for net/minecraft/entity/monster/EntityCreeper.class
     ZipEntry entry = zip.getEntry(name.replace('.', '/') + ".class");
     if (entry == null) {
       System.out.println(name + " not found in " + location.getName());
     } else {
       // serialize the class file into the bytes array
       InputStream zin = zip.getInputStream(entry);
       bytes = new byte[(int) entry.getSize()];
       zin.read(bytes);
       zin.close();
       System.out.println("[" + "ExtraFood-patcher" + "]: " + "Class " + name + " patched!");
     }
     zip.close();
   } catch (Exception e) {
     throw new RuntimeException("Error overriding " + name + " from " + location.getName(), e);
   }
   // return the new bytes
   return bytes;
 }
示例#29
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"));
  }
示例#30
0
  public static byte[] readFileContent(String zipFileString, String fileString) {
    MyLogger.logI(CLASS_TAG, "getFile");
    ByteArrayOutputStream baos = null;
    try {
      ZipFile zipFile = new ZipFile(zipFileString);
      ZipEntry zipEntry = zipFile.getEntry(fileString);
      if (zipEntry != null) {
        InputStream is = zipFile.getInputStream(zipEntry);
        baos = new ByteArrayOutputStream();
        int len = -1;
        byte[] buffer = new byte[512];
        while ((len = is.read(buffer, 0, 512)) != -1) {
          baos.write(buffer, 0, len);
        }
        is.close();
      }

      zipFile.close();
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }
    if (baos != null) {
      return baos.toByteArray();
    }
    return null;
  }