Java Code Examples for java.util.zip.ZipEntry

The following are top voted examples for showing how to use java.util.zip.ZipEntry. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: rapidminer   File: Tools.java   Source Code and License 12 votes vote down vote up
/**
 * This method checks if the given file is a Zip file containing one entry (in case of file
 * extension .zip). If this is the case, a reader based on a ZipInputStream for this entry is
 * returned. Otherwise, this method checks if the file has the extension .gz. If this applies, a
 * gzipped stream reader is returned. Otherwise, this method just returns a BufferedReader for
 * the given file (file was not zipped at all).
 */
public static BufferedReader getReader(File file, Charset encoding) throws IOException {
	// handle zip files if necessary
	if (file.getAbsolutePath().endsWith(".zip")) {
		try (ZipFile zipFile = new ZipFile(file)) {
			if (zipFile.size() == 0) {
				throw new IOException("Input of Zip file failed: the file archive does not contain any entries.");
			}
			if (zipFile.size() > 1) {
				throw new IOException("Input of Zip file failed: the file archive contains more than one entry.");
			}
			Enumeration<? extends ZipEntry> entries = zipFile.entries();
			InputStream zipIn = zipFile.getInputStream(entries.nextElement());
			return new BufferedReader(new InputStreamReader(zipIn, encoding));
		}
	} else if (file.getAbsolutePath().endsWith(".gz")) {
		return new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(file)), encoding));
	} else {
		return new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
	}
}
 
Example 2
Project: can4eve   File: RandomAccessLogReader.java   Source Code and License 7 votes vote down vote up
/**
 * create me based on a (potentially zipped) file
 * 
 * @param file
 * @throws Exception
 */
public RandomAccessLogReader(File logFile) throws Exception {
  if (logFile.getName().endsWith(".zip")) {
    File unzipped = new File(logFile.getParentFile(), "unzipped");
    zipFile = new ZipFile(logFile);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    if (entries.hasMoreElements()) {
      ZipEntry entry = entries.nextElement();
      if (!entry.isDirectory()) {
        if (!unzipped.isDirectory()) {
          unzipped.mkdir();
        }
        elmLogFile = new File(unzipped, entry.getName());
        InputStream in = zipFile.getInputStream(entry);
        OutputStream out = new FileOutputStream(elmLogFile);
        IOUtils.copy(in, out);
        IOUtils.closeQuietly(in);
        out.close();
      }
    }
  } else {
    elmLogFile = logFile;
  }
}
 
Example 3
Project: aem-epic-tool   File: PackageContents.java   Source Code and License 7 votes vote down vote up
private void determineTypesInZipFile(ZipFullEntry entry) {
    InputStream in = entry.getInputStream();
    if (in == null) {
            Logger.getLogger(PackageContents.class.getName()).log(Level.SEVERE, "No file contents provided for {0}", entry.getName());
    } else {
        try (ZipInputStream bundle = new ZipInputStream(in)) {
            ZipEntry jarEntry;
            while ((jarEntry = bundle.getNextEntry()) != null) {
                ZipFullEntry jarFullEntry = new ZipFullEntry(bundle, jarEntry, entry.getName().endsWith(".jar"));
                observeFileEntry(jarFullEntry);
                subfiles.put(entry.getName() + "!" + jarFullEntry.getName(), new FileContents(jarFullEntry, this));
            }
        } catch (IOException ex) {
            Logger.getLogger(PackageContents.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
 
Example 4
Project: ServerBrowser   File: FileUtility.java   Source Code and License 6 votes vote down vote up
/**
 * Unzips a file, placing its contents in the given output location.
 *
 * @param zipFilePath
 *            input zip file
 * @param outputLocation
 *            zip file output folder
 * @throws IOException
 *             if there was an error reading the zip file or writing the unzipped data
 */
public static void unzip(final String zipFilePath, final String outputLocation) throws IOException {
	// Open the zip file
	try (final ZipFile zipFile = new ZipFile(zipFilePath)) {
		final Enumeration<? extends ZipEntry> enu = zipFile.entries();
		while (enu.hasMoreElements()) {

			final ZipEntry zipEntry = enu.nextElement();
			final String name = zipEntry.getName();
			final File outputFile = new File(outputLocation + separator + name);

			if (name.endsWith("/")) {
				outputFile.mkdirs();
				continue;
			}

			final File parent = outputFile.getParentFile();
			if (parent != null) {
				parent.mkdirs();
			}

			// Extract the file
			try (final InputStream inputStream = zipFile.getInputStream(zipEntry);
					final FileOutputStream outputStream = new FileOutputStream(outputFile)) {
				/*
				 * The buffer is the max amount of bytes kept in RAM during any given time while
				 * unzipping. Since most windows disks are aligned to 4096 or 8192, we use a
				 * multiple of those values for best performance.
				 */
				final byte[] bytes = new byte[8192];
				while (inputStream.available() > 0) {
					final int length = inputStream.read(bytes);
					outputStream.write(bytes, 0, length);
				}
			}
		}
	}
}
 
Example 5
Project: r2-streamer-java   File: EpubContainer.java   Source Code and License 6 votes vote down vote up
@Override
public String rawData(String relativePath) throws NullPointerException {
    //Log.d(TAG, "Reading file at path: " + relativePath);

    try {
        ZipEntry zipEntry = zipFile.getEntry(relativePath);
        InputStream is = zipFile.getInputStream(zipEntry);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line;

        while ((line = br.readLine()) != null) {
            sb.append(line);        //.append('\n');
        }
        //Log.d(TAG, "Reading data: " + sb.toString());

        return sb.toString();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 6
Project: hadoop   File: JarFinder.java   Source Code and License 6 votes vote down vote up
public static void jarDir(File dir, String relativePath, ZipOutputStream zos)
  throws IOException {
  Preconditions.checkNotNull(relativePath, "relativePath");
  Preconditions.checkNotNull(zos, "zos");

  // by JAR spec, if there is a manifest, it must be the first entry in the
  // ZIP.
  File manifestFile = new File(dir, JarFile.MANIFEST_NAME);
  ZipEntry manifestEntry = new ZipEntry(JarFile.MANIFEST_NAME);
  if (!manifestFile.exists()) {
    zos.putNextEntry(manifestEntry);
    new Manifest().write(new BufferedOutputStream(zos));
    zos.closeEntry();
  } else {
    copyToZipStream(manifestFile, manifestEntry, zos);
  }
  zos.closeEntry();
  zipDir(dir, relativePath, zos, true);
  zos.close();
}
 
Example 7
Project: Pogamut3   File: ExampleBotProjectWizardIterator.java   Source Code and License 6 votes vote down vote up
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());
                if ("nbproject/project.xml".equals(entry.getName())) {
                    // Special handling for setting name of Ant-based projects; customize as needed:
                    filterProjectXML(fo, str, projectRoot.getName());
                } else {
                    writeFile(str, fo);
                }
            }
        }
    } finally {
        source.close();
    }
}
 
Example 8
Project: OperatieBRP   File: TimestampMojo.java   Source Code and License 6 votes vote down vote up
private void verwerkManifest(final Path tmpFolder, final FileTime bestandstijd, final JarOutputStream nieuwArchiefStream) throws MojoExecutionException {
    final File archiefBestand = new File(tmpFolder.toFile(), JarFile.MANIFEST_NAME);
    getLog().debug("Processing manifest");
    if (archiefBestand.exists()) {
        try (final FileInputStream fis = new FileInputStream(archiefBestand)) {
            Manifest manifest = new Manifest();
            if (archiefBestand.exists()) {
                manifest.read(fis);
            }
            ZipEntry manifestFolder = new ZipEntry(META_INF_PATH);
            fixeerDatumTijd(manifestFolder, bestandstijd);
            nieuwArchiefStream.putNextEntry(manifestFolder);
            nieuwArchiefStream.closeEntry();
            ZipEntry manifestBestand = new ZipEntry(JarFile.MANIFEST_NAME);
            fixeerDatumTijd(manifestBestand, bestandstijd);
            nieuwArchiefStream.putNextEntry(manifestBestand);
            manifest.write(nieuwArchiefStream);
            nieuwArchiefStream.closeEntry();
            getLog().debug("manifest processed");
        } catch (IOException e) {
            throw new MojoExecutionException("Cannot write manifest file", e);
        }
    }
}
 
Example 9
Project: tomcat7   File: JspUtil.java   Source Code and License 6 votes vote down vote up
public static InputStream getInputStream(String fname, JarFile jarFile,
        JspCompilationContext ctxt, ErrorDispatcher err)
        throws JasperException, IOException {

    InputStream in = null;

    if (jarFile != null) {
        String jarEntryName = fname.substring(1, fname.length());
        ZipEntry jarEntry = jarFile.getEntry(jarEntryName);
        if (jarEntry == null) {
            throw new FileNotFoundException(Localizer.getMessage(
                    "jsp.error.file.not.found", fname));
        }
        in = jarFile.getInputStream(jarEntry);
    } else {
        in = ctxt.getResourceAsStream(fname);
    }

    if (in == null) {
        throw new FileNotFoundException(Localizer.getMessage(
                "jsp.error.file.not.found", fname));
    }

    return in;
}
 
Example 10
Project: hadoop   File: JarFinder.java   Source Code and License 6 votes vote down vote up
private static void copyToZipStream(File file, ZipEntry entry,
                            ZipOutputStream zos) throws IOException {
  InputStream is = new FileInputStream(file);
  try {
    zos.putNextEntry(entry);
    byte[] arr = new byte[4096];
    int read = is.read(arr);
    while (read > -1) {
      zos.write(arr, 0, read);
      read = is.read(arr);
    }
  } finally {
    try {
      is.close();
    } finally {
      zos.closeEntry();
    }
  }
}
 
Example 11
Project: Reer   File: DefaultModuleRegistry.java   Source Code and License 6 votes vote down vote up
private Properties loadModuleProperties(String name, File jarFile) {
    try {
        ZipFile zipFile = new ZipFile(jarFile);
        try {
            final String entryName = name + "-classpath.properties";
            ZipEntry entry = zipFile.getEntry(entryName);
            if (entry == null) {
                throw new IllegalStateException("Did not find " + entryName + " in " + jarFile.getAbsolutePath());
            }
            return GUtil.loadProperties(zipFile.getInputStream(entry));
        } finally {
            zipFile.close();
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 12
Project: Tengine   File: GameLoader.java   Source Code and License 6 votes vote down vote up
/**
 * Load zip entries from package to HashMap and check if meta-file is present
 * @param path path to package
 * @throws Exception thrown when meta-file is not present in package
 */
private static void loadAndValidate(String path) throws Exception {
    boolean found = false;
    zip = new ZipFile(path);
    Enumeration<? extends ZipEntry> entries = zip.entries();

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

        if (entry.getName().equals("meta-file") && !entry.isDirectory()) {
            found = true;
        }

        GameLoader.entries.put(entry.getName(), entry);
    }

    if (!found) {
        throw new Exception(String.format("'%s' is not valid game!", path));
    }
}
 
Example 13
Project: atlas   File: Dex.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a new dex buffer from the dex file {@code file}.
 */
public Dex(File file) throws IOException {
    if (FileUtils.hasArchiveSuffix(file.getName())) {
        ZipFile zipFile = new ZipFile(file);
        ZipEntry entry = zipFile.getEntry(DexFormat.DEX_IN_JAR_NAME);
        if (entry != null) {
            loadFrom(zipFile.getInputStream(entry));
            zipFile.close();
        } else {
            throw new DexException("Expected " + DexFormat.DEX_IN_JAR_NAME + " in " + file);
        }
    } else if (file.getName().endsWith(".dex")) {
        loadFrom(new FileInputStream(file));
    } else {
        throw new DexException("unknown output extension: " + file);
    }
}
 
Example 14
Project: tenhou-visualizer   File: AnalyzeZipTask.java   Source Code and License 6 votes vote down vote up
@Override
protected Void call() throws Exception {
    Platform.runLater(this.observableList::clear);
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxParserFactory.newSAXParser();
    try (ZipFile zipFile = new ZipFile(this.selectedFile)) {
        int workMax = zipFile.size();
        long workDone = 0;
        for (Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements();) {
            ZipEntry zipEntry = e.nextElement();
            int position = zipEntry.getName().charAt(zipEntry.getName().length() - 7) - '0';
            SyantenAnalyzer analyzer = new SyantenAnalyzer(position);
            ParseHandler parseHandler = new ParseHandler(analyzer);
            try (InputStream is = zipFile.getInputStream(zipEntry);
                GZIPInputStream gzis = new GZIPInputStream(is)) {
                saxParser.parse(gzis, parseHandler);
            }
            ArrayList<MahjongScene> scenes = analyzer.getOriScenes();
            workDone++;
            Platform.runLater(() -> observableList.addAll(scenes));
            updateMessage(workDone + "/" + workMax);
            updateProgress(workDone, workMax);
        }
    }
    return null;
}
 
Example 15
Project: gemini.blueprint   File: JarUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 
 * Writes a resource content to a jar.
 * 
 * @param res
 * @param entryName
 * @param jarStream
 * @param bufferSize
 * @return the number of bytes written to the jar file
 * @throws Exception
 */
public static int writeToJar(Resource res, String entryName, JarOutputStream jarStream, int bufferSize)
		throws IOException {
	byte[] readWriteJarBuffer = new byte[bufferSize];

	// remove leading / if present.
	if (entryName.charAt(0) == '/')
		entryName = entryName.substring(1);

	jarStream.putNextEntry(new ZipEntry(entryName));
	InputStream entryStream = res.getInputStream();

	int numberOfBytes;

	// read data into the buffer which is later on written to the jar.
	while ((numberOfBytes = entryStream.read(readWriteJarBuffer)) != -1) {
		jarStream.write(readWriteJarBuffer, 0, numberOfBytes);
	}
	return numberOfBytes;
}
 
Example 16
Project: multidexlib2   File: ZipFileDexContainer.java   Source Code and License 6 votes vote down vote up
public ZipFileDexContainer(File zip, DexFileNamer namer, Opcodes opcodes) throws IOException {
	Map<String, WrappingMultiDexFile<DexBackedDexFile>> entryMap = new TreeMap<>(new DexFileNameComparator(namer));
	try (ZipFile zipFile = new ZipFile(zip)) {
		Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
		while (zipEntries.hasMoreElements()) {
			ZipEntry zipEntry = zipEntries.nextElement();
			String entryName = zipEntry.getName();
			if (namer.isValidName(entryName)) {
				DexBackedDexFile dexFile;
				try (InputStream inputStream = zipFile.getInputStream(zipEntry)) {
					dexFile = RawDexIO.readRawDexFile(inputStream, zipEntry.getSize(), opcodes);
				}
				WrappingMultiDexFile<DexBackedDexFile> multiDexFile =
						new BasicMultiDexFile<>(this, entryName, dexFile);
				if (entryMap.put(entryName, multiDexFile) != null) throwDuplicateEntryName(entryName);
			}
		}
	}
	initialize(entryMap, opcodes);
}
 
Example 17
Project: n4js   File: ZipFileExporter.java   Source Code and License 6 votes vote down vote up
/**
 * Create a new entry in the zip file with the given content.
 */
public void writeFile(InputStream contentStream, long timeStamp, String destinationPath) throws IOException {
	ZipEntry newEntry = new ZipEntry(destinationPath);
	byte[] readBuffer = new byte[4096];

	newEntry.setTime(timeStamp);

	outputStream.putNextEntry(newEntry);
	try {
		int n;
		while ((n = contentStream.read(readBuffer)) > 0) {
			outputStream.write(readBuffer, 0, n);
		}
	} finally {
		if (contentStream != null) {
			contentStream.close();
		}
	}
	outputStream.closeEntry();
}
 
Example 18
Project: rskj   File: VMUtilsTest.java   Source Code and License 6 votes vote down vote up
@Test
public void saveZippedProgramTraceFile() throws Exception {
    Path traceFilePath = tempRule.newFolder().toPath();
    ProgramTrace mockTrace = new ProgramTrace(ConfigHelper.CONFIG);
    String mockTxHash = "1234";

    VMUtils.saveProgramTraceFile(
            traceFilePath,
            mockTxHash,
            true,
            mockTrace
    );

    ZipInputStream zipIn = new ZipInputStream(Files.newInputStream(traceFilePath.resolve(mockTxHash + ".zip")));
    ZipEntry zippedTrace = zipIn.getNextEntry();
    Assert.assertThat(zippedTrace.getName(), is(mockTxHash + ".json"));
    ByteArrayOutputStream unzippedTrace = new ByteArrayOutputStream();
    byte[] traceBuffer = new byte[2048];
    int len;
    while ((len = zipIn.read(traceBuffer)) > 0) {
        unzippedTrace.write(traceBuffer, 0, len);
    }
    Assert.assertThat(new String(unzippedTrace.toByteArray()), is(Serializers.serializeFieldsOnly(mockTrace, true)));
}
 
Example 19
Project: OpenJSharp   File: Utils.java   Source Code and License 6 votes vote down vote up
static void copyJarFile(JarInputStream in, JarOutputStream out) throws IOException {
    if (in.getManifest() != null) {
        ZipEntry me = new ZipEntry(JarFile.MANIFEST_NAME);
        out.putNextEntry(me);
        in.getManifest().write(out);
        out.closeEntry();
    }
    byte[] buffer = new byte[1 << 14];
    for (JarEntry je; (je = in.getNextJarEntry()) != null; ) {
        out.putNextEntry(je);
        for (int nr; 0 < (nr = in.read(buffer)); ) {
            out.write(buffer, 0, nr);
        }
    }
    in.close();
    markJarFile(out);  // add PACK200 comment
}
 
Example 20
Project: incubator-netbeans   File: JarURLStreamHandlerTest.java   Source Code and License 6 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();
    clearWorkDir();
    
    jar = new File(getWorkDir(), "x.jar");
    JarOutputStream os = new JarOutputStream(
        new FileOutputStream(jar)
    );
    os.putNextEntry(new ZipEntry("fldr/plain.txt"));
    os.write("Ahoj\n".getBytes());
    os.closeEntry();
    os.close();
    JarClassLoader registerJarSource = new JarClassLoader(
        Collections.nCopies(1, jar),
        new ClassLoader[] { getClass().getClassLoader() }
    );
    assertNotNull("Registered", registerJarSource);
}
 
Example 21
Project: Tower-Defense-Galaxy   File: Tools.java   Source Code and License 6 votes vote down vote up
public static FileHandle getRealFileHandle(String zipEntryPath, ZipFile zipFile) {
    if (Gdx.files.local(zipEntryPath).exists()) {
        return Gdx.files.local(zipEntryPath);
    } else {
        Gdx.app.log("OBB", "Unzipping file '" + zipEntryPath + "'...");
        try {
            FileHandle unzippedFile;
            ZipEntry entry = zipFile.getEntry(zipEntryPath);
            if (entry != null) {
                unzippedFile = Gdx.files.local(zipEntryPath);
                InputStream is = zipFile.getInputStream(entry);
                byte[] buffer = new byte[65536];
                int readLength;
                while ((readLength = is.read(buffer)) >= 0) {
                    unzippedFile.writeBytes(buffer, 0, readLength, true);
                }
                return unzippedFile;
            } else {
                Gdx.app.error("OBB", "Entry '" + zipEntryPath + "' not found inside zip file.");
            }
        } catch (IOException ioe) {
            Gdx.app.error("OBB", "A problem occurred while writing to the local file.");
        }
    }
    return null;
}
 
Example 22
Project: jdk8u-jdk   File: B7050028.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
    int len = conn.getContentLength();
    byte[] data = new byte[len];
    InputStream is = conn.getInputStream();
    is.read(data);
    is.close();
    conn.setDefaultUseCaches(false);
    File jar = File.createTempFile("B7050028", ".jar");
    jar.deleteOnExit();
    OutputStream os = new FileOutputStream(jar);
    ZipOutputStream zos = new ZipOutputStream(os);
    ZipEntry ze = new ZipEntry("B7050028.class");
    ze.setMethod(ZipEntry.STORED);
    ze.setSize(len);
    CRC32 crc = new CRC32();
    crc.update(data);
    ze.setCrc(crc.getValue());
    zos.putNextEntry(ze);
    zos.write(data, 0, len);
    zos.closeEntry();
    zos.finish();
    zos.close();
    os.close();
    System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
 
Example 23
Project: alfresco-remote-api   File: SiteExportServiceTest.java   Source Code and License 6 votes vote down vote up
private List<String> getAcpEntries(InputStream inputStream) throws Exception
{
    List<String> entries = Lists.newArrayList();
    ZipInputStream zipInputStream = new ZipInputStream(inputStream);
    ZipEntry entry = null;
    try
    {
        while ((entry = zipInputStream.getNextEntry()) != null)
        {
            entries.add(entry.getName());
        }
    }
    catch (ZipException e)
    {
        // ignore
    }
    return entries;
}
 
Example 24
Project: incubator-netbeans   File: SourceForBinaryQueryTest.java   Source Code and License 6 votes vote down vote up
@Override
protected void setUp() throws Exception {
    this.clearWorkDir();
    super.setUp();
    File wd = this.getWorkDir();
    FileObject wdfo = FileUtil.toFileObject(wd);
    br1 = wdfo.createFolder("bin1");
    br2 = wdfo.createFolder("bin2");
    sr1 = wdfo.createFolder("src1");
    File zf = new File (wd,"src2.zip");
    ZipOutputStream zos = new ZipOutputStream (new FileOutputStream (zf));
    zos.putNextEntry(new ZipEntry("foo.java"));
    zos.closeEntry();
    zos.close();
    sr2 = FileUtil.getArchiveRoot(FileUtil.toFileObject(zf));
    map.put(br1.toURL(), Collections.singletonList(sr1));
    map.put(br2.toURL(), Collections.singletonList(sr2));
}
 
Example 25
Project: lams   File: ArchiveResourceListSource.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a list of file resources contained in the specified directory
 * within a given Zip'd archive file.
 * 
 * @param  file the zip file containing the resources to return
 * @param  root the directory within the zip file containing the resources
 * @return a list of file resources contained in the specified directory
 *         within a given Zip'd archive file
 */
private List getResources(ZipFile file, String root)
{
    List resourceNames = new ArrayList();
    Enumeration e = file.entries();
    while (e.hasMoreElements())
    {
        ZipEntry entry = (ZipEntry) e.nextElement();
        String name = entry.getName();
        if (name.startsWith(root)
            && !(name.indexOf('/') > root.length())
            && !entry.isDirectory())
        {
            // Calling File.getPath() cleans up the path so that it's using
            // the proper path separators for the host OS
            name = new File(name).getPath();
            resourceNames.add(name);
        }
    }
    return resourceNames;
}
 
Example 26
Project: letv   File: FabricKitsFinder.java   Source Code and License 6 votes vote down vote up
private KitInfo loadKitInfo(ZipEntry fabricFile, ZipFile apk) {
    KitInfo kitInfo;
    InputStream inputStream = null;
    try {
        inputStream = apk.getInputStream(fabricFile);
        Properties properties = new Properties();
        properties.load(inputStream);
        String id = properties.getProperty(FABRIC_IDENTIFIER_KEY);
        String version = properties.getProperty(FABRIC_VERSION_KEY);
        String buildType = properties.getProperty(FABRIC_BUILD_TYPE_KEY);
        if (TextUtils.isEmpty(id) || TextUtils.isEmpty(version)) {
            throw new IllegalStateException("Invalid format of fabric file," + fabricFile.getName());
        }
        kitInfo = new KitInfo(id, version, buildType);
        return kitInfo;
    } catch (IOException ie) {
        kitInfo = Fabric.getLogger();
        kitInfo.e(Fabric.TAG, "Error when parsing fabric properties " + fabricFile.getName(), ie);
        return null;
    } finally {
        CommonUtils.closeQuietly(inputStream);
    }
}
 
Example 27
Project: jdk8u-jdk   File: TestExtraTime.java   Source Code and License 5 votes vote down vote up
static void check(FileTime mtime, FileTime atime, FileTime ctime,
                  ZipEntry ze, byte[] extra) {
    /*
    System.out.printf("    mtime [%tc]: [%tc]/[%tc]%n",
                      mtime.to(TimeUnit.MILLISECONDS),
                      ze.getTime(),
                      ze.getLastModifiedTime().to(TimeUnit.MILLISECONDS));
     */
    if (mtime.to(TimeUnit.SECONDS) !=
        ze.getLastModifiedTime().to(TimeUnit.SECONDS))
        throw new RuntimeException("Timestamp: storing mtime failed!");
    if (atime != null &&
        atime.to(TimeUnit.SECONDS) !=
        ze.getLastAccessTime().to(TimeUnit.SECONDS))
        throw new RuntimeException("Timestamp: storing atime failed!");
    if (ctime != null &&
        ctime.to(TimeUnit.SECONDS) !=
        ze.getCreationTime().to(TimeUnit.SECONDS))
        throw new RuntimeException("Timestamp: storing ctime failed!");
    if (extra != null) {
        // if extra data exists, the current implementation put it at
        // the end of the extra data array (implementation detail)
        byte[] extra1 = ze.getExtra();
        if (extra1 == null || extra1.length < extra.length ||
            !Arrays.equals(Arrays.copyOfRange(extra1,
                                              extra1.length - extra.length,
                                              extra1.length),
                           extra)) {
            throw new RuntimeException("Timestamp: storing extra field failed!");
        }
    }
}
 
Example 28
Project: FSTestTools   File: ZipImportCommandsTest.java   Source Code and License 5 votes vote down vote up
private void fillZipWithContent() throws IOException {
    RandomAccessFile raf = new RandomAccessFile(txtFile,"rw");
    raf.writeUTF("Test");
    raf.close();
    try (FileOutputStream fos = new FileOutputStream(zipFile)) {
        try (ZipOutputStream zos = new ZipOutputStream(fos)) {
            try (FileInputStream fis = new FileInputStream(txtFile)) {
                ZipEntry zipEntry = new ZipEntry("test.txt");
                zos.putNextEntry(zipEntry);
                byte[] bytes = new byte[1024];
                int length;
                while ((length = fis.read(bytes)) >= 0) {
                    zos.write(bytes, 0, length);
                }
                zos.flush();
                zos.closeEntry();
                fos.flush();
            }
        }
    }
    zipFile.deleteOnExit();
    txtFile.deleteOnExit();
}
 
Example 29
Project: atlas   File: ZipUtils.java   Source Code and License 5 votes vote down vote up
public static boolean removeZipEntry(File file, Pattern pattern, File targetFile)
    throws FileNotFoundException, IOException {
    byte[] buffer = new byte[1024];
    java.util.zip.ZipFile zipFile = new java.util.zip.ZipFile(file);
    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(targetFile)));
    BufferedOutputStream bo = new BufferedOutputStream(out);
    InputStream inputStream;
    Enumeration enumeration = zipFile.entries();
    while (enumeration.hasMoreElements()) {
        ZipEntry zipEntry = (ZipEntry)enumeration.nextElement();
        String name = zipEntry.getName();
        if (pattern.matcher(name).find()) {
            continue;
        }
        out.putNextEntry(zipEntry);
        inputStream = zipFile.getInputStream(zipEntry);
        write(inputStream, out, buffer);
        bo.flush();

    }

    closeQuitely(zipFile);
    closeQuitely(out);
    closeQuitely(bo);

    return true;
}
 
Example 30
Project: HeadlineNews   File: ZipUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 获取压缩文件中的文件路径链表
 *
 * @param zipFile 压缩文件
 * @return 压缩文件中的文件路径链表
 * @throws IOException IO错误时抛出
 */
public static List<String> getFilesPath(final File zipFile)
        throws IOException {
    if (zipFile == null) return null;
    List<String> paths = new ArrayList<>();
    Enumeration<?> entries = getEntries(zipFile);
    while (entries.hasMoreElements()) {
        paths.add(((ZipEntry) entries.nextElement()).getName());
    }
    return paths;
}
 
Example 31
Project: java-nio-test   File: ByteBufferEncoder.java   Source Code and License 5 votes vote down vote up
public static Request decodeRequest(byte[] pack) {
    byte[] zippedBytes = Base64.getDecoder().decode(pack);

    ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(zippedBytes));
    ZipEntry zipEntry;
    Request request = new Request(null);

    try {
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            byte[] entryContent = readFromInputStream(zipInputStream);
            String entryName = zipEntry.getName();

            switch (entryName) {
                case "sequence":
                    request.setSequence(Bytes.bytesToLong(entryContent));
                    break;
                case "path":
                    request.setPath(new String(entryContent));
                    break;
                case "params":
                    request.setParams(parseJsonObject(entryContent));
                    break;
            }
        }

        return request;
    } catch (IOException e) {
        LOG.error("Error reading zip stream", e);
        return null;
    }
}
 
Example 32
Project: shrinker   File: JarProcessor.java   Source Code and License 5 votes vote down vote up
private List<Pair<String, byte[]>> readZipEntries(Path src) throws IOException {
    ImmutableList.Builder<Pair<String, byte[]>> list = ImmutableList.builder();
    try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(Files.readAllBytes(src)))) {
        for (ZipEntry entry = zip.getNextEntry();
             entry != null;
             entry = zip.getNextEntry()) {
            String name = entry.getName();
            if (!name.endsWith(".class")) {
                // skip
                continue;
            }
            long entrySize = entry.getSize();
            if (entrySize >= Integer.MAX_VALUE) {
                throw new OutOfMemoryError("Too large class file " + name + ", size is " + entrySize);
            }
            byte[] bytes = readByteArray(zip, (int) entrySize);
            list.add(Pair.of(name, bytes));
        }
    }
    return list.build();
}
 
Example 33
Project: hadoop   File: TestApplicationClassLoader.java   Source Code and License 5 votes vote down vote up
private File makeTestJar() throws IOException {
  File jarFile = new File(testDir, "test.jar");
  JarOutputStream out = new JarOutputStream(new FileOutputStream(jarFile));
  ZipEntry entry = new ZipEntry("resource.txt");
  out.putNextEntry(entry);
  out.write("hello".getBytes());
  out.closeEntry();
  out.close();
  return jarFile;
}
 
Example 34
Project: elasticsearch_my   File: InstallPluginCommandTests.java   Source Code and License 5 votes vote down vote up
public void testZipRelativeOutsideEntryName() throws Exception {
    Tuple<Path, Environment> env = createEnv(fs, temp);
    Path zip = createTempDir().resolve("broken.zip");
    try (ZipOutputStream stream = new ZipOutputStream(Files.newOutputStream(zip))) {
        stream.putNextEntry(new ZipEntry("elasticsearch/../blah"));
    }
    String pluginZip = zip.toUri().toURL().toString();
    IOException e = expectThrows(IOException.class, () -> installPlugin(pluginZip, env.v1()));
    assertTrue(e.getMessage(), e.getMessage().contains("resolving outside of plugin directory"));
}
 
Example 35
Project: amap   File: MIP_FileUtils.java   Source Code and License 5 votes vote down vote up
public static void ZipFiles(List<String> filepaths, String zipFileString)
    throws Exception
{
    File zipFile = new File(zipFileString);
    if (zipFile != null && zipFile.exists())
    {
        zipFile.delete();
    }
    if (filepaths != null)
    {
        ZipOutputStream outZip = new ZipOutputStream(new FileOutputStream(zipFileString));
        for (String filepath : filepaths)
        {
            File file = new File(filepath);
            if (file != null && file.exists())
            {
                ZipEntry zipEntry = new ZipEntry(file.getName());
                FileInputStream inputStream = new FileInputStream(file);
                outZip.putNextEntry(zipEntry);
                int len;
                byte[] buffer = new byte[4096];
                while ((len = inputStream.read(buffer)) != -1)
                {
                    outZip.write(buffer, 0, len);
                }
                outZip.closeEntry();
            }
        }
        outZip.finish();
        outZip.close();
    }
}
 
Example 36
Project: BaseCore   File: CrashHander.java   Source Code and License 5 votes vote down vote up
/**
 * INTERNAL method that returns the build date of the current APK as a string, or null if unable to determine it.
 *
 * @param context    A valid context. Must not be null.
 * @param dateFormat DateFormat to use to convert from Date to String
 * @return The formatted date, or "Unknown" if unable to determine it.
 */
private static String getBuildDateAsString(Context context, DateFormat dateFormat) {
    String buildDate;
    try {
        ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);
        ZipFile zf = new ZipFile(ai.sourceDir);
        ZipEntry ze = zf.getEntry("classes.dex");
        long time = ze.getTime();
        buildDate = dateFormat.format(new Date(time));
        zf.close();
    } catch (Exception e) {
        buildDate = "Unknown";
    }
    return buildDate;
}
 
Example 37
Project: FreeStreams-TVLauncher   File: ZipUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 获得压缩文件内文件列表
 *
 * @param zipFile 压缩文件
 * @return 压缩文件内文件名称
 * @throws ZipException 压缩文件格式有误时抛出
 * @throws IOException 当解压缩过程出错时抛出
 */
public static ArrayList<String> getEntriesNames(File zipFile) throws ZipException, IOException {
    ArrayList<String> entryNames = new ArrayList<String>();
    Enumeration<?> entries = getEntriesEnumeration(zipFile);
    while (entries.hasMoreElements()) {
        ZipEntry entry = ((ZipEntry)entries.nextElement());
        entryNames.add(new String(getEntryName(entry).getBytes("GB2312"), "8859_1"));
    }
    return entryNames;
}
 
Example 38
Project: hepek-classycle   File: Parser.java   Source Code and License 5 votes vote down vote up
private static void analyseClassFiles(ZipFile zipFile, String source, ArrayList<UnresolvedNode> unresolvedNodes,
        StringPattern reflectionPattern) throws IOException {
    final Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        final ZipEntry entry = entries.nextElement();
        if (!entry.isDirectory() && entry.getName().endsWith(".class")) {
            final InputStream stream = zipFile.getInputStream(entry);
            final int size = (int) entry.getSize();
            unresolvedNodes.add(Parser.createNode(stream, source, size, reflectionPattern));
        }
    }
}
 
Example 39
Project: atlas   File: TPatchTool.java   Source Code and License 5 votes vote down vote up
/**
 * add files to jar
 *
 * @param jos
 * @param file
 */
private void addFile(JarOutputStream jos, File file) throws IOException {
    byte[] buf = new byte[8064];
    String path = file.getName();
    InputStream in = null;
    try {
        in = new FileInputStream(file);
        ZipEntry fileEntry = new ZipEntry(path);
        jos.putNextEntry(fileEntry);
        // Transfer bytes from the file to the ZIP file
        int len;
        while ((len = in.read(buf)) > 0) {
            jos.write(buf, 0, len);
        }
        // Complete the entry
        jos.closeEntry();
    } finally {
        IOUtils.closeQuietly(in);
    }
}
 
Example 40
Project: elasticsearch_my   File: InstallPluginCommandTests.java   Source Code and License 5 votes vote down vote up
static String writeZip(Path structure, String prefix) throws IOException {
    Path zip = createTempDir().resolve(structure.getFileName() + ".zip");
    try (ZipOutputStream stream = new ZipOutputStream(Files.newOutputStream(zip))) {
        Files.walkFileTree(structure, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String target = (prefix == null ? "" : prefix + "/") + structure.relativize(file).toString();
                stream.putNextEntry(new ZipEntry(target));
                Files.copy(file, stream);
                return FileVisitResult.CONTINUE;
            }
        });
    }
    return zip.toUri().toURL().toString();
}