@Override public Element parse(InputStream in) { ZipInputStream zin = new ZipInputStream(in); ZipEntryPeer root; Map<String, Element> map = new HashMap<String, Element>(); ZipEntry entry = null; entry = getNextEntrySilently(zin); while (entry != null) { Plugin<?> plugin = rechecker.getInputTypeMatcher().getPlugin(entry); if (!(plugin instanceof FilePlugin)) { Element child = plugin.parse(new ZippedFileInputStream(zin)); } else { ZipEntryPeer next = new ZipEntryPeer(entry); } entry = getNextEntrySilently(zin); } // TODO implement // read all zip entries // map them such that we know the children return null; }
public ZipModInputStream(FileHandle file) { try { inputStream = new FileInputStream(file.file()); zipInputStream = new ZipInputStream(inputStream); fileStream = new FilterInputStream(zipInputStream) { @Override public void close() throws IOException { // no close } }; } catch (Exception e) { try { close(); } catch (IOException ignored) { } throw new CubesException("Failed to create zip mod input stream", e); } }
public ZipFullEntry(ZipInputStream stream, ZipEntry e, boolean isParentJarFile) { insideJar = isParentJarFile; entry = e; contentsGetter = () -> { try { long size = e.getSize(); // Note: This will fail to properly read 2gb+ files, but we have other problems if that's in this JAR file. if (size <= 0) { return Optional.empty(); } byte[] buffer = new byte[(int) size]; stream.read(buffer); return Optional.of(new ByteInputStream(new byte[(int) e.getSize()], buffer.length)); } catch (IOException ex) { Logger.getLogger(ZipFullEntry.class.getName()).log(Level.SEVERE, null, ex); return Optional.empty(); } }; }
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); } } }
/** * 获取jar文件的entry列表 * * @param jarFile * @return */ public static List<String> getZipEntries(File jarFile) throws IOException { List<String> entries = new ArrayList<String>(); FileInputStream fis = new FileInputStream(jarFile); ZipInputStream zis = new ZipInputStream(fis); try { // loop on the entries of the jar file package and put them in the final jar ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { // do not take directories or anything inside a potential META-INF folder. if (entry.isDirectory()) { continue; } String name = entry.getName(); entries.add(name); } } finally { zis.close(); } return entries; }
private static String getContent(InputStream input, final String zipEntryName) { try (ZipInputStream zipin = new ZipInputStream(input)) { ZipEntry ze; while ((ze = zipin.getNextEntry()) != null) { String zeName = ze.getName(); if (zipEntryName.equals(zeName)) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int b = zipin.read(); while (b >= 0) { baos.write(b); b = zipin.read(); } zipin.close(); return new String(baos.toByteArray()); } } zipin.close(); return null; } catch (Exception e) { throw new RuntimeException(e); } }
@Override public Csar create(String identifier, InputStream inputStream) { csarMap.remove(identifier); File csarDir = setupDir(identifier); File contentDir = new File(csarDir, CONTENT_DIR); File transformationDir = new File(csarDir, TRANSFORMATION_DIR); transformationDir.mkdir(); try { ZipUtility.unzip(new ZipInputStream(inputStream), contentDir.getPath()); logger.info("Extracted csar '{}' into '{}'", identifier, contentDir.getPath()); } catch (IOException e) { logger.error("Failed to unzip csar with identifier '{}'", identifier, e); } Csar csar = new CsarImpl(identifier, getLog(identifier)); csarMap.put(identifier, csar); return csar; }
public static void unzip(final InputStream zipfile, final File directory) throws IOException { final ZipInputStream zfile = new ZipInputStream(zipfile); ZipEntry entry; while ((entry = zfile.getNextEntry()) != null) { final File file = new File(directory, entry.getName()); if (entry.isDirectory()) { file.mkdirs(); } else { file.getParentFile().mkdirs(); try { StreamUtilities.copy(zfile, file); } catch (IOException e) { log.log(Level.SEVERE, e.getMessage(), e); } } } zfile.close(); }
@Test public void shouldCreateHashForFile() { //given PowerMockito.mockStatic(IoUtil.class); PowerMockito.mockStatic(DigestUtils.class); byte[] bytes = new byte[]{1,2,3}; final String fileEntry = "fileEntry"; final ZipInputStream zipInputStream = mock(ZipInputStream.class); when(IoUtil.readInputStream(zipInputStream, fileEntry)).thenReturn(bytes); final String hash = "hash"; when(DigestUtils.md5DigestAsHex(bytes)).thenReturn(hash); //when final String result = zipResourceService.createHashForFile(zipInputStream, fileEntry); //then assertThat(result, equalTo(hash)); }
public static void unZipFile(InputStream source, FileObject rootFolder) throws IOException { try { ZipInputStream str = new ZipInputStream(source); ZipEntry entry; while ((entry = str.getNextEntry()) != null) { if (entry.isDirectory()) { FileUtil.createFolder(rootFolder, entry.getName()); continue; } FileObject fo = FileUtil.createData(rootFolder, entry.getName()); FileLock lock = fo.lock(); try { OutputStream out = fo.getOutputStream(lock); try { FileUtil.copy(str, out); } finally { out.close(); } } finally { lock.releaseLock(); } } } finally { source.close(); } }
@Test(expected = IllegalArgumentException.class) public void zipAndUnzipWrongEncodedBytes() throws IOException { ZipOutputOf<byte[]> zos = IoStream.bytes().zipOutputStream("UTF-16"); try { zos.putNextEntry(new ZipEntry("ééé")); zos.write("aaaaaaa".getBytes()); } finally { zos.close(); } ZipInputStream zis = IoStream.bytes(zos.get()).zipInputStream("UTF-8"); try { ZipEntry ze = zis.getNextEntry(); assertThat(ze.getName()).isEqualTo("ééé"); } finally { zis.close(); } }
/*** Added by julienda - 08/09/2012 * Return the project name by reading the first directory into the archive (.car) * @param path: the archive path * @return filename: the project name * @throws IOException */ public static String getProjectName(String path) throws IOException { Engine.logEngine.trace("PATH: "+path); ZipInputStream zis = new ZipInputStream(new FileInputStream(path)); ZipEntry ze = null; String fileName = null; try { if((ze = zis.getNextEntry()) != null){ fileName = ze.getName().replaceAll("/.*",""); Engine.logEngine.trace("ZipUtils.getProjectName() - fileName: "+fileName); } } finally { zis.close(); } return fileName; }
@Test public void zip_single_file() throws Exception { file.mkdirs(); final File target = new File(file, "target.zip"); final File f1 = new File(file, "f1.txt"); FileUtil.write(TEST_TEXT, f1); FileUtil.zip(Collections.singletonList(f1), target); try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(target))) { final ZipEntry entry = zipInputStream.getNextEntry(); Assert.assertEquals("f1.txt", entry.getName()); final Scanner scanner = new Scanner(zipInputStream); final String line = scanner.nextLine(); Assert.assertEquals(TEST_TEXT, line); } }
public static void unZipFile(InputStream source, FileObject projectRoot) throws IOException { try { ZipInputStream str = new ZipInputStream(source); ZipEntry entry; while ((entry = str.getNextEntry()) != null) { if (entry.isDirectory()) { FileUtil.createFolder(projectRoot, entry.getName()); } else { FileObject fo = FileUtil.createData(projectRoot, entry.getName()); FileLock lock = fo.lock(); try { OutputStream out = fo.getOutputStream(lock); try { FileUtil.copy(str, out); } finally { out.close(); } } finally { lock.releaseLock(); } } } } finally { source.close(); } }
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(); } }
/** * 部署单个流程定义 * * @param resourceLoader {@link ResourceLoader} * @param processKey 模块名称 * @throws IOException 找不到zip文件时 */ private void deploySingleProcess(ResourceLoader resourceLoader, String processKey, String exportDir) throws IOException { String classpathResourceUrl = "classpath:/deployments/" + processKey + ".bar"; logger.debug("read workflow from: {}", classpathResourceUrl); Resource resource = resourceLoader.getResource(classpathResourceUrl); InputStream inputStream = resource.getInputStream(); if (inputStream == null) { logger.warn("ignore deploy workflow module: {}", classpathResourceUrl); } else { logger.debug("finded workflow module: {}, deploy it!", classpathResourceUrl); ZipInputStream zis = new ZipInputStream(inputStream); Deployment deployment = repositoryService.createDeployment().addZipInputStream(zis).deploy(); // export diagram List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).list(); for (ProcessDefinition processDefinition : list) { WorkflowUtils.exportDiagramToFile(repositoryService, processDefinition, exportDir); } } }
public void testExportSiteWithMutipleUsers() throws Exception { // Create a site String shortName = GUID.generate(); createSite("myPreset", shortName, "myTitle", "myDescription", SiteVisibility.PUBLIC, 200); // add a user and a person as members addSiteMember(USER_FROM_LDAP, shortName); addSiteMember(USER_ONE, shortName); // Export site Response response = sendRequest(new GetRequest(getExportUrl(shortName)), 200); // check exported files List<String> entries = getEntries(new ZipInputStream(new ByteArrayInputStream( response.getContentAsByteArray()))); assertFalse(entries.contains("No_Users_In_Site.txt")); assertFalse(entries.contains("No_Persons_In_Site.txt")); assertTrue(entries.contains("People.acp")); assertTrue(entries.contains(shortName + "-people.xml")); assertTrue(entries.contains("Users.acp")); assertTrue(entries.contains(shortName + "-users.xml")); }
private static List<Map<String, Object>> processInput(File input) { List<Map<String, Object>> output = new ArrayList<>(); InfoClassVisitor visitor = new InfoClassVisitor(output); try (ZipInputStream zip = new ZipInputStream(new FileInputStream(input))) { ZipEntry entry; while ((entry = zip.getNextEntry()) != null) { if (!entry.getName().endsWith(".class")) { continue; } ClassReader cr = new ClassReader(zip); cr.accept(visitor, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); } } catch (IOException ex) { ex.printStackTrace(); return null; } return output; }
private void expandZippedApplication(InputStream stream, ApplicationDescription desc) throws IOException { ZipInputStream zis = new ZipInputStream(stream); ZipEntry entry; File appDir = new File(appsDir, desc.name()); while ((entry = zis.getNextEntry()) != null) { if (!entry.isDirectory()) { byte[] data = ByteStreams.toByteArray(zis); zis.closeEntry(); File file = new File(appDir, entry.getName()); createParentDirs(file); write(data, file); } } zis.close(); }
/** Extracts a ZipInputStream specified by the zipIn to a directory specified by destDirectory (will be created if does not exists) @param zipIn ZipInputStream of zip archive @param destDirectory target directory for unzipping */ public static void unzip(ZipInputStream zipIn, String destDirectory) throws IOException { File destDir = new File(destDirectory); if (!destDir.exists()) { destDir.mkdir(); } ZipEntry entry = zipIn.getNextEntry(); while (entry != null) { String filePath = destDirectory + File.separator + entry.getName(); if (!entry.isDirectory()) { extractFile(zipIn, filePath); } else { logger.trace("Creating directory: {}", filePath); File dir = new File(filePath); dir.mkdir(); } zipIn.closeEntry(); entry = zipIn.getNextEntry(); } zipIn.close(); }
public static void unzipRemoteFile(String localFileName, String directoryPath){ try { FileInputStream fin = new FileInputStream(localFileName); ZipInputStream zin = new ZipInputStream(fin); ZipEntry ze = null; while ((ze = zin.getNextEntry()) != null) { Log.v("Decompress", "Unzipping " + ze.getName()); if(ze.isDirectory()) { Common.dirChecker(directoryPath + File.separator + ze.getName()); } else { FileOutputStream fout = new FileOutputStream(directoryPath + File.separator + ze.getName()); for (int c = zin.read(); c != -1; c = zin.read()) { fout.write(c); } zin.closeEntry(); fout.close(); } } zin.close(); } catch(Exception e) { Log.e("Decompress", "unzip", e); } }
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("Usage: java DrbgCavp drbgtestvectors.zip"); return; } File tv = new File(args[0]); EntropySource es = new TestEntropySource(); System.setErr(new PrintStream(bout)); // The testsuite is a zip file containing more zip files for different // working modes. Each internal zip file contains test materials for // different mechanisms. try (ZipFile zf = new ZipFile(tv)) { String[] modes = {"no_reseed", "pr_false", "pr_true"}; for (String mode : modes) { try (ZipInputStream zis = new ZipInputStream(zf.getInputStream( zf.getEntry("drbgvectors_" + mode + ".zip")))) { while (true) { ZipEntry ze = zis.getNextEntry(); if (ze == null) { break; } String fname = ze.getName(); if (fname.equals("Hash_DRBG.txt") || fname.equals("HMAC_DRBG.txt") || fname.equals("CTR_DRBG.txt")) { String algorithm = fname.substring(0, fname.length() - 4); test(mode, algorithm, es, zis); } } } } } finally { System.setErr(err); } }
private void processJarFile(File file, final Trie.Builder builder) throws IOException { IoActions.withResource(openJarFile(file), new ErroringAction<ZipInputStream>() { @Override protected void doExecute(ZipInputStream inputStream) throws Exception { ZipEntry zipEntry = inputStream.getNextEntry(); while (zipEntry != null) { processEntry(zipEntry, builder); zipEntry = inputStream.getNextEntry(); } } }); }
@Test public void shouldOpenZipResource() { //given final Resource resource = mock(Resource.class); //when final ZipInputStream result = zipResourceService.openZipResource(resource); //then assertThat(result, notNullValue()); }
private Map<String, byte[]> extractContents(InputStream inputStream) throws IOException { Map<String, byte[]> contents = new HashMap<String, byte[]>(); // assumption: the zip is non-empty ZipInputStream zip = new ZipInputStream(inputStream); ZipEntry entry; while ((entry = zip.getNextEntry()) != null) { if (entry.isDirectory()) continue; ByteArrayOutputStream contentStream = new ByteArrayOutputStream(); ByteStreams.copy(zip, contentStream); contents.put(entry.getName(), contentStream.toByteArray()); } zip.close(); return contents; }
public static ZipInputStream getFileFromZip(InputStream zipFileStream) throws IOException { ZipInputStream zis = new ZipInputStream(zipFileStream); ZipEntry ze; while ((ze = zis.getNextEntry()) != null) { Log.w(TAG, "extracting file: '" + ze.getName() + "'..."); return zis; } return null; }
/** * Extracts content of Zip file to specified output path. * * @param is {@link InputStream} InputStream of Zip file * @param outputFolder folder where Zip file should be extracted to * @throws IOException */ public static void extract(InputStream is, File outputFolder) throws IOException { ZipInputStream zis = new ZipInputStream(is); ZipEntry entry; byte[] buffer = new byte[1024]; while ((entry = zis.getNextEntry()) != null) { File outputFile = new File(outputFolder.getCanonicalPath() + File.separatorChar + entry.getName()); File outputParent = new File(outputFile.getParent()); outputParent.mkdirs(); if (entry.isDirectory()) { if (!outputFile.exists()) { outputFile.mkdir(); } } else { FileOutputStream fos = new FileOutputStream(outputFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); } } }
private ZipInputStream getArchiveStream(final URI archiveLocation) throws CoreException, IOException { if (archiveLocation.isPlatformResource()) { IFile workspaceFile = workspace.getFile(new Path(archiveLocation.toPlatformString(true))); return new ZipInputStream(workspaceFile.getContents()); } else { return new ZipInputStream(new URL(archiveLocation.toString()).openStream()); } }
/** * @source http://stackoverflow.com/a/27050680 */ public static void unzip(InputStream zipFile, File targetDirectory) throws Exception { ZipInputStream in = new ZipInputStream(new BufferedInputStream(zipFile)); try { ZipEntry ze; int count; byte[] buffer = new byte[8192]; while ((ze = in.getNextEntry()) != null) { File file = new File(targetDirectory, ze.getName()); File dir = ze.isDirectory() ? file : file.getParentFile(); if (!dir.isDirectory() && !dir.mkdirs()) { throw new Exception("Failed to ensure directory: " + dir.getAbsolutePath()); } if (ze.isDirectory()) { continue; } BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); try { while ((count = in.read(buffer)) != -1) out.write(buffer, 0, count); } finally { out.close(); } long time = ze.getTime(); if (time > 0) { file.setLastModified(time); } } } finally { in.close(); } }
private String unzipData(InputStream is, String extension, File writeDirectory) throws IOException { String baseFileName = UUID.randomUUID().toString(); ZipInputStream zipInputStream = new ZipInputStream(is); ZipEntry entry; String returnFile = null; while ((entry = zipInputStream.getNextEntry()) != null) { String currentExtension = entry.getName(); int beginIndex = currentExtension.lastIndexOf(".") + 1; currentExtension = currentExtension.substring(beginIndex); String fileName = baseFileName + "." + currentExtension; File currentFile = new File(writeDirectory, fileName); if (!writeDirectory.exists()) { writeDirectory.mkdir(); } currentFile.createNewFile(); FileOutputStream fos = new FileOutputStream(currentFile); org.apache.commons.io.IOUtils.copy(zipInputStream, fos); if (currentExtension.equalsIgnoreCase(extension)) { returnFile = currentFile.getAbsolutePath(); } fos.close(); } zipInputStream.close(); return returnFile; }
private void createNamespacePackFromCoreBackup(ZipInputStream zipInputStream) throws IOException, SerializerException { try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { for (int chunk = zipInputStream.read(); chunk != -1; chunk = zipInputStream.read()) { out.write(chunk); } this.namespacesFromBackup = jsonFasterxmlSerializer.deserialize(out.toString(), Namespaces.class); } }
/** * Unpacks a ZIP file to disk. * All entries are unpacked, even {@code META-INF/MANIFEST.MF} if present. * Parent directories are created as needed (even if not mentioned in the ZIP); * empty ZIP directories are created too. * Existing files are overwritten. * @param zip a ZIP file * @param dir the base directory in which to unpack (need not yet exist) * @throws IOException in case of problems */ public static void unpackZipFile(File zip, File dir) throws IOException { byte[] buf = new byte[8192]; InputStream is = new FileInputStream(zip); try { ZipInputStream zis = new ZipInputStream(is); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { String name = entry.getName(); int slash = name.lastIndexOf('/'); File d = new File(dir, name.substring(0, slash).replace('/', File.separatorChar)); if (!d.isDirectory() && !d.mkdirs()) { throw new IOException("could not make " + d); } if (slash != name.length() - 1) { File f = new File(dir, name.replace('/', File.separatorChar)); OutputStream os = new FileOutputStream(f); try { int read; while ((read = zis.read(buf)) != -1) { os.write(buf, 0, read); } } finally { os.close(); } } } } finally { is.close(); } }
private void unpack (String filename) throws IOException { File zipLarge = new File(getDataDir(), filename); ZipInputStream is = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipLarge))); ZipEntry entry; while ((entry = is.getNextEntry()) != null) { File unpacked = new File(workDir, entry.getName()); FileChannel channel = new FileOutputStream(unpacked).getChannel(); byte[] bytes = new byte[2048]; try { int len; long size = entry.getSize(); while (size > 0 && (len = is.read(bytes, 0, 2048)) > 0) { ByteBuffer buffer = ByteBuffer.wrap(bytes, 0, len); int j = channel.write(buffer); size -= len; } } finally { channel.close(); } } ZipEntry e = is.getNextEntry(); }
@Test public void shouldDeployWhenResourcesExistAndVersionNotDeployedBefore() throws IOException { // given final String resourceFileName = "resource.zip"; final Resource resource = mock(Resource.class); InputStream inputStreamResource = mock(InputStream.class); when(resource.getInputStream()).thenReturn(inputStreamResource); when(resource.getFilename()).thenReturn(resourceFileName); ChangelogVersion changelogVersion = new ChangelogVersion(); changelogVersion.setArchiveFile(resourceFileName); String deploymentName = "deploymentName"; changelogVersion.setDeploymentName(deploymentName); String deploymentSource = "deploymentSource"; changelogVersion.setDeploymentSource(deploymentSource); boolean deployChangedOnly = true; changelogVersion.setDeployChangedOnly(deployChangedOnly); when(zipResourceServiceMock.loadZipResource(CLASSPATH_TO_ARCHIVE_FILES + resourceFileName)).thenReturn(resource); when(repositoryServiceMock.createDeployment().addZipInputStream(any(ZipInputStream.class)).name(deploymentName).source(deploymentSource).enableDuplicateFiltering(deployChangedOnly)).thenReturn(deploymentBuilderMock); when(repositoryServiceMock.createProcessDefinitionQuery().versionTag(any()).list()).thenReturn(Collections.emptyList()); // when deploymentService.deploy(changelogVersion); // then verify(deploymentBuilderMock, times(1)).deploy(); }
private static void unzip(InputStream source, FileObject targetFolder) throws IOException { //installation ZipInputStream zip=new ZipInputStream(source); try { ZipEntry ent; while ((ent = zip.getNextEntry()) != null) { if (ent.isDirectory()) { FileUtil.createFolder(targetFolder, ent.getName()); } else { FileObject destFile = FileUtil.createData(targetFolder,ent.getName()); FileLock lock = destFile.lock(); try { OutputStream out = destFile.getOutputStream(lock); try { FileUtil.copy(zip, out); } finally { out.close(); } } finally { lock.releaseLock(); } } } } finally { zip.close(); } }
private static void unzip(InputStream source, FileObject targetFolder) throws IOException { //installation ZipInputStream zip = new ZipInputStream(source); try { ZipEntry ent; while ((ent = zip.getNextEntry()) != null) { if (ent.isDirectory()) { FileUtil.createFolder(targetFolder, ent.getName()); } else { FileObject destFile = FileUtil.createData(targetFolder, ent.getName()); FileLock lock = destFile.lock(); try { OutputStream out = destFile.getOutputStream(lock); try { FileUtil.copy(zip, out); } finally { out.close(); } } finally { lock.releaseLock(); } } } } finally { zip.close(); } }
public InputStream getStoreFileInputStream() throws FileNotFoundException, IOException { ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(getStoreFile()))); ZipEntry entry; while ( (entry = zis.getNextEntry()) != null ) { if( entry.getName().equals(getStoreFile().getName()) ) { return zis; } } throw new FileNotFoundException("no entry in zip store file " + getStoreFile().getAbsolutePath() + " for file " + getFile()); }
private DataInputStream getCategoryInputStream(File file) throws IOException { if (!file.exists()) { return null; } ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(file))); zis.getNextEntry(); return new DataInputStream(zis); }