List of usage examples for org.apache.commons.compress.archivers ArchiveStreamFactory ArchiveStreamFactory
ArchiveStreamFactory
From source file:org.ugent.caagt.genestacker.io.ZIPWriter.java
/** * Creates a ZIP package containing 3 files for every schedule in the given Pareto frontier: * <ul>/*from www . j ava 2 s . c o m*/ * <li>a graph visualisation using the requested graph file format</li> * <li>a dot source file used to generate the visualisation</li> * <li>an XML file describing the schedule</li> * </ul> * * @param pf Pareto frontier * @param format graph file format (e.g. PDF) * @param colorScheme graph color scheme * @param outputFile output file (extension ".zip" is appended if not already contained in the file name) * * @throws IOException if any IO errors occur * @throws ArchiveException if the ZIP file can not be created * @throws GenestackerException if any problems occur with the Gene Stacker config file */ public void createZIP(ParetoFrontier pf, GraphFileFormat format, GraphColorScheme colorScheme, String outputFile) throws IOException, ArchiveException, GenestackerException { // format outputFile string if (!outputFile.endsWith(".zip")) { outputFile += ".zip"; } // name of folder inside ZIP (same as ZIP without extension) String inZIPFolder = outputFile.substring(0, outputFile.lastIndexOf('.')); if (inZIPFolder.indexOf('/') != -1) { inZIPFolder = inZIPFolder.substring(outputFile.lastIndexOf('/') + 1); } // create ZIP archive CrossingSchemeGraphWriter graphWriter = new CrossingSchemeGraphWriter(format, colorScheme); CrossingSchemeXMLWriter xmlWriter = new CrossingSchemeXMLWriter(); try (OutputStream out = new FileOutputStream(new File(outputFile)); ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);) { // add files int numScheme = 0; for (Map.Entry<Integer, Set<CrossingScheme>> gen : pf.getSchemes().entrySet()) { Set<CrossingScheme> schemes = gen.getValue(); for (CrossingScheme s : schemes) { numScheme++; // create xml File xml = Files.createTempFile("scheme-", ".xml").toFile(); xmlWriter.write(s, xml); // create graph File graph = Files.createTempFile("scheme-", "." + format).toFile(); File graphvizSource = graphWriter.write(s, graph); // copy xml, diagram and graphviz source to zip file os.putArchiveEntry(new ZipArchiveEntry(inZIPFolder + "/scheme" + numScheme + ".xml")); IOUtils.copy(new FileInputStream(xml), os); os.closeArchiveEntry(); // only copy graph if successfully created! if (graph.exists()) { os.putArchiveEntry(new ZipArchiveEntry(inZIPFolder + "/scheme" + numScheme + "." + format)); IOUtils.copy(new FileInputStream(graph), os); os.closeArchiveEntry(); } os.putArchiveEntry(new ZipArchiveEntry(inZIPFolder + "/scheme" + numScheme + ".graphviz")); IOUtils.copy(new FileInputStream(graphvizSource), os); os.closeArchiveEntry(); // delete temp files xml.delete(); graph.delete(); } } } }
From source file:org.vafer.jdeb.producers.DataProducerArchive.java
public void produce(final DataConsumer pReceiver) throws IOException { InputStream is = new BufferedInputStream(new FileInputStream(archive)); CompressorInputStream compressorInputStream = null; try {//from www .j a v a 2 s . c om compressorInputStream = new CompressorStreamFactory().createCompressorInputStream(is); } catch (CompressorException e) { // expected if the input file is a zip archive } if (compressorInputStream != null) { is = new BufferedInputStream(compressorInputStream); } ArchiveInputStream archiveInputStream = null; try { archiveInputStream = new ArchiveStreamFactory().createArchiveInputStream(is); } catch (ArchiveException e) { throw new IOException("Unsupported archive format: " + archive, e); } EntryConverter converter = null; if (archiveInputStream instanceof TarArchiveInputStream) { converter = new EntryConverter() { public TarArchiveEntry convert(ArchiveEntry entry) { TarArchiveEntry src = (TarArchiveEntry) entry; TarArchiveEntry dst = new TarArchiveEntry(src.getName(), true); dst.setSize(src.getSize()); dst.setGroupName(src.getGroupName()); dst.setGroupId(src.getGroupId()); dst.setUserId(src.getUserId()); dst.setMode(src.getMode()); dst.setModTime(src.getModTime()); return dst; } }; } else if (archiveInputStream instanceof ZipArchiveInputStream) { converter = new EntryConverter() { public TarArchiveEntry convert(ArchiveEntry entry) { ZipArchiveEntry src = (ZipArchiveEntry) entry; TarArchiveEntry dst = new TarArchiveEntry(src.getName(), true); dst.setSize(src.getSize()); dst.setMode(src.getUnixMode()); dst.setModTime(src.getTime()); return dst; } }; } else { throw new IOException("Unsupported archive format: " + archive); } try { while (true) { ArchiveEntry archiveEntry = archiveInputStream.getNextEntry(); if (archiveEntry == null) { break; } if (!isIncluded(archiveEntry.getName())) { continue; } TarArchiveEntry entry = converter.convert(archiveEntry); entry = map(entry); if (entry.isDirectory()) { pReceiver.onEachDir(entry.getName(), entry.getLinkName(), entry.getUserName(), entry.getUserId(), entry.getGroupName(), entry.getGroupId(), entry.getMode(), entry.getSize()); continue; } pReceiver.onEachFile(archiveInputStream, entry.getName(), entry.getLinkName(), entry.getUserName(), entry.getUserId(), entry.getGroupName(), entry.getGroupId(), entry.getMode(), entry.getSize()); } } finally { if (archiveInputStream != null) { archiveInputStream.close(); } } }
From source file:org.voyanttools.trombone.input.expand.ArchiveExpander.java
public List<StoredDocumentSource> getExpandedStoredDocumentSources(StoredDocumentSource storedDocumentSource) throws IOException { // first try to see if we've been here already String id = storedDocumentSource.getId(); List<StoredDocumentSource> archivedStoredDocumentSources = storedDocumentSourceStorage .getMultipleExpandedStoredDocumentSources(id); if (archivedStoredDocumentSources != null && archivedStoredDocumentSources.isEmpty() == false) { return archivedStoredDocumentSources; }/*from w w w .ja v a 2s. c o m*/ InputStream inputStream = null; try { ArchiveStreamFactory archiveStreamFactory = new ArchiveStreamFactory(); inputStream = storedDocumentSourceStorage .getStoredDocumentSourceInputStream(storedDocumentSource.getId()); BufferedInputStream bis = new BufferedInputStream(inputStream); String filename = storedDocumentSource.getMetadata().getLocation(); ArchiveInputStream archiveInputStream; if (filename.toLowerCase().endsWith("tgz") || filename.toLowerCase().endsWith("tar.gz")) { // decompress and then untar archiveInputStream = archiveStreamFactory.createArchiveInputStream(ArchiveStreamFactory.TAR, new GZIPInputStream(bis)); } else if (filename.toLowerCase().endsWith("tbz2") || filename.toLowerCase().endsWith("tar.bz2")) { // decompress and then untar archiveInputStream = archiveStreamFactory.createArchiveInputStream(ArchiveStreamFactory.TAR, new BZip2CompressorInputStream(bis)); } else { archiveInputStream = archiveStreamFactory.createArchiveInputStream(bis); } archivedStoredDocumentSources = getExpandedDocumentSources(archiveInputStream, storedDocumentSource); storedDocumentSourceStorage.setMultipleExpandedStoredDocumentSources(storedDocumentSource.getId(), archivedStoredDocumentSources); return archivedStoredDocumentSources; } catch (ArchiveException e) { throw new IOException("A problem was encountered reading this archive: " + storedDocumentSource.getMetadata().getLocation(), e); } finally { if (inputStream != null) { inputStream.close(); } } }
From source file:org.wildfly.plugin.common.Archives.java
/** * Unzips the zip file to the target directory. * <p>//from w w w .j a v a2s . c o m * Note this is specific to how WildFly is archived. The first directory is assumed to be the base home directory * and will returned. * </p> * * @param archiveFile the archive to uncompress, can be a {@code .zip} or {@code .tar.gz} * @param targetDir the directory to extract the zip file to * @param replaceIfExists if {@code true} replace the existing files if they exist * * @return the path to the extracted directory * * @throws java.io.IOException if an I/O error occurs */ @SuppressWarnings("WeakerAccess") public static Path uncompress(final Path archiveFile, final Path targetDir, final boolean replaceIfExists) throws IOException { final Path archive = getArchive(archiveFile); Path firstDir = null; try (ArchiveInputStream in = new ArchiveStreamFactory() .createArchiveInputStream(new BufferedInputStream(Files.newInputStream(archive)))) { ArchiveEntry entry; while ((entry = in.getNextEntry()) != null) { final Path extractTarget = targetDir.resolve(entry.getName()); if (!replaceIfExists && Files.exists(extractTarget)) { if (entry.isDirectory() && firstDir == null) { firstDir = extractTarget; } continue; } if (entry.isDirectory()) { final Path dir = Files.createDirectories(extractTarget); if (firstDir == null) { firstDir = dir; } } else { Files.createDirectories(extractTarget.getParent()); Files.copy(in, extractTarget); } } return firstDir == null ? targetDir : firstDir; } catch (ArchiveException e) { throw new IOException(e); } }
From source file:org.wildfly.plugin.server.Archives.java
/** * Unzips the zip file to the target directory. * * @param zipFile the zip file to unzip * @param targetDir the directory to extract the zip file to * * @throws java.io.IOException if an I/O error occurs *///from w w w. j a v a2 s. com public static void unzip(final Path zipFile, final Path targetDir) throws IOException { final Path archive = getArchive(zipFile); try (final ArchiveInputStream in = new ArchiveStreamFactory() .createArchiveInputStream(new BufferedInputStream(Files.newInputStream(archive)))) { ArchiveEntry entry; while ((entry = in.getNextEntry()) != null) { final Path extractTarget = targetDir.resolve(entry.getName()); if (entry.isDirectory()) { Files.createDirectories(extractTarget); } else { Files.createDirectories(extractTarget.getParent()); Files.copy(in, extractTarget); } } } catch (ArchiveException e) { throw new IOException(e); } }
From source file:org.xlcloud.commons.compress.CompressUtils.java
/** * Method extracts stream for a destination file. When a file with the same * name exists for an applcation it throw * {@link DuplicatedDirectoryException}. Filename is only to check stream * format.//from w w w . ja va 2 s . com * * @param stream * @param filename * @param path * @return */ public static File extractArchiveStream(InputStream stream, String path) throws IOException, ArchiveException, DuplicatedDirectoryException { File rootDir = new File(path); rootDir.mkdirs(); InputStream bufferedStream = normalizeStream(stream); ArchiveInputStream input = new ArchiveStreamFactory().createArchiveInputStream(bufferedStream); ArchiveEntry archiveEntry = null; String baseFoler = null; while ((archiveEntry = input.getNextEntry()) != null) { if (baseFoler == null) { baseFoler = archiveEntry.getName(); if (new File(path + baseFoler).exists()) { throw new DuplicatedDirectoryException("Directory with name: " + baseFoler + " already exists"); } } if (!archiveEntry.isDirectory() && archiveEntry.getSize() > 0) { File extractFile = new File(path + "/" + archiveEntry.getName()); byte[] entryContent = new byte[(int) archiveEntry.getSize()]; input.read(entryContent, 0, entryContent.length); extractFile.getParentFile().mkdirs(); extractFile.createNewFile(); IOUtils.write(entryContent, new FileOutputStream(extractFile)); } } return new File(path + baseFoler); }
From source file:org.xlcloud.commons.compress.CompressUtils.java
/** * Method lists archive files//from ww w. j a va 2s . c o m * * @param stream * @param filename * @param path * @return */ public static List<String> listArchiveFiles(InputStream stream) throws IOException, ArchiveException { InputStream bufferedStream = normalizeStream(stream); ArchiveInputStream input = new ArchiveStreamFactory().createArchiveInputStream(bufferedStream); List<String> archiveFiles = new ArrayList<String>(); ArchiveEntry archiveEntry = null; while ((archiveEntry = input.getNextEntry()) != null) { archiveFiles.add(archiveEntry.getName()); } return archiveFiles; }
From source file:org.xwiki.contrib.dokuwiki.text.internal.input.DokuWikiInputFilterStream.java
@Override protected void read(Object filter, DokuWikiFilter proxyFilter) throws FilterException { InputSource inputSource = this.properties.getSource(); if (inputSource instanceof FileInputSource) { File f = ((FileInputSource) inputSource).getFile(); if (f.exists()) { if (f.isDirectory()) { File dokuwikiDataDirectory = new File(f, "data"); readUsers(new File(f, "conf" + System.getProperty(KEY_FILE_SEPERATOR) + "users.auth.php"), proxyFilter);//from w w w . j a v a 2 s . co m //recursively parse documents proxyFilter.beginWikiSpace(KEY_MAIN_SPACE, FilterEventParameters.EMPTY); try { readDocument(new File(dokuwikiDataDirectory, KEY_PAGES_DIRECTORY), dokuwikiDataDirectory.getAbsolutePath(), proxyFilter); } catch (IOException e) { this.logger.error("couldn't read document", e); } proxyFilter.endWikiSpace(KEY_MAIN_SPACE, FilterEventParameters.EMPTY); } else { try { CompressorInputStream input = new CompressorStreamFactory().createCompressorInputStream( new BufferedInputStream(((InputStreamInputSource) inputSource).getInputStream())); ArchiveInputStream archiveInputStream = new ArchiveStreamFactory() .createArchiveInputStream(new BufferedInputStream(input)); readDataStream(archiveInputStream, filter, proxyFilter); input.close(); } catch (Exception e1) { try { FileInputSource fileInputSource = (FileInputSource) this.properties.getSource(); FileInputStream fileInputStream = FileUtils.openInputStream(fileInputSource.getFile()); ArchiveInputStream archiveInputStream = new ArchiveStreamFactory() .createArchiveInputStream(new BufferedInputStream(fileInputStream)); readDataStream(archiveInputStream, filter, proxyFilter); fileInputStream.close(); archiveInputStream.close(); } catch (IOException | ArchiveException e2) { this.logger.error("Failed to read/unarchive or unknown format from file input type", e1, e2); } } } } else { this.logger.error("File doesn't exists."); } } else if (inputSource instanceof InputStreamInputSource) { try { CompressorInputStream input = new CompressorStreamFactory() .createCompressorInputStream(((InputStreamInputSource) inputSource).getInputStream()); ArchiveInputStream archiveInputStream = new ArchiveStreamFactory() .createArchiveInputStream(new BufferedInputStream(input)); readDataStream(archiveInputStream, filter, proxyFilter); input.close(); } catch (Exception e1) { try { ArchiveInputStream archiveInputStream = new ArchiveStreamFactory().createArchiveInputStream( new BufferedInputStream(((InputStreamInputSource) inputSource).getInputStream())); readDataStream(archiveInputStream, filter, proxyFilter); archiveInputStream.close(); } catch (IOException | ArchiveException e2) { this.logger.error("Failed to read/unarchive or unknown format from stream input", e1, e2); } } } else { throw new FilterException("Unsupported input source [" + inputSource.getClass() + "]"); } }
From source file:server.Folder.java
/** * Create a zipped folder containing those OSDs and subfolders (recursively) which the * validator allows. <br/>/*from w w w .j a v a2 s . c o m*/ * Zip file encoding compatibility is difficult to achieve.<br/> * Using Cp437 as encoding will generate zip archives which can be unpacked with MS Windows XP * system utilities and also with the Linux unzip tool v6.0 (although the unzip tool will list them * as corrupted filenames with "?" in place for the special characters, it should unpack them * correctly). In tests, 7zip was unable to unpack those archives without messing up the filenames * - it requires UTF8 as encoding, as far as I can tell.<br/> * see: http://commons.apache.org/compress/zip.html#encoding<br/> * to manually test this, use: https://github.com/dewarim/GrailsBasedTesting * @param folderDao data access object for Folder objects * @param latestHead if set to true, only add objects with latestHead=true, if set to false include only * objects with latestHead=false, if set to null: include everything regardless of * latestHead status. * @param latestBranch if set to true, only add objects with latestBranch=true, if set to false include only * objects with latestBranch=false, if set to null: include everything regardless of * latestBranch status. * @param validator a Validator object which should be configured for the current user to check if access * to objects and folders inside the given folder is allowed. The content of this folder * will be filtered before it is added to the archive. * @return the zip archive of the given folder */ public ZippedFolder createZippedFolder(FolderDAO folderDao, Boolean latestHead, Boolean latestBranch, Validator validator) { String repositoryName = HibernateSession.getLocalRepositoryName(); final File sysTempDir = new File(System.getProperty("java.io.tmpdir")); File tempFolder = new File(sysTempDir, UUID.randomUUID().toString()); if (!tempFolder.mkdirs()) { throw new CinnamonException(("error.create.tempFolder.fail")); } List<Folder> folders = new ArrayList<Folder>(); folders.add(this); folders.addAll(folderDao.getSubfolders(this, true)); folders = validator.filterUnbrowsableFolders(folders); log.debug("# of folders found: " + folders.size()); // create zip archive: ZippedFolder zippedFolder; try { File zipFile = File.createTempFile("cinnamonArchive", "zip"); zippedFolder = new ZippedFolder(zipFile, this); final OutputStream out = new FileOutputStream(zipFile); ZipArchiveOutputStream zos = (ZipArchiveOutputStream) new ArchiveStreamFactory() .createArchiveOutputStream(ArchiveStreamFactory.ZIP, out); String encoding = ConfThreadLocal.getConf().getField("zipFileEncoding", "Cp437"); log.debug("current file.encoding: " + System.getProperty("file.encoding")); log.debug("current Encoding for ZipArchive: " + zos.getEncoding() + "; will now set: " + encoding); zos.setEncoding(encoding); zos.setFallbackToUTF8(true); zos.setCreateUnicodeExtraFields(ZipArchiveOutputStream.UnicodeExtraFieldPolicy.ALWAYS); for (Folder folder : folders) { String path = folder.fetchPath().replace(fetchPath(), name); // do not include the parent folders up to root. log.debug("zipFolderPath: " + path); File currentFolder = new File(tempFolder, path); if (!currentFolder.mkdirs()) { // log.warn("failed to create folder for: "+currentFolder.getAbsolutePath()); } List<ObjectSystemData> osds = validator.filterUnbrowsableObjects( folderDao.getFolderContent(folder, false, latestHead, latestBranch)); if (osds.size() > 0) { zippedFolder.addToFolders(folder); // do not add empty folders as they are excluded automatically. } for (ObjectSystemData osd : osds) { if (osd.getContentSize() == null) { continue; } zippedFolder.addToObjects(osd); File outFile = osd.createFilenameFromName(currentFolder); // the name in the archive should be the path without the temp folder part prepended. String zipEntryPath = outFile.getAbsolutePath().replace(tempFolder.getAbsolutePath(), ""); if (zipEntryPath.startsWith(File.separator)) { zipEntryPath = zipEntryPath.substring(1); } log.debug("zipEntryPath: " + zipEntryPath); zipEntryPath = zipEntryPath.replaceAll("\\\\", "/"); zos.putArchiveEntry(new ZipArchiveEntry(zipEntryPath)); IOUtils.copy(new FileInputStream(osd.getFullContentPath(repositoryName)), zos); zos.closeArchiveEntry(); } } zos.close(); } catch (Exception e) { log.debug("Failed to create zipFolder:", e); throw new CinnamonException("error.zipFolder.fail", e.getLocalizedMessage()); } return zippedFolder; }
From source file:tikatest.Investigation.java
/** * Takes a file which has already been detected as a supported archive and * displays the contents./*from w w w .j a v a2 s .c om*/ * <p>This method makes use of code which has been publicly available through * the Apache website. * @param The file to be inspected * @see java.io.BufferedInputStream */ private void handleGeneric(BufferedInputStream bis) { try { // File type is a known archive type and we can work with it (fingers crossed) ArchiveInputStream aisInput = new ArchiveStreamFactory().createArchiveInputStream(bis); ArchiveEntry aeFile = aisInput.getNextEntry(); System.out.println("ArchiveInputStream: " + aisInput.getClass().getName()); System.out.println("Archive Entry - Type: " + aeFile.getClass().getName()); while (aeFile != null) { if (!aeFile.isDirectory()) { String[] segments = aeFile.getName().split("\\/"); String filename = ""; for (String segment : segments) { filename = segment; } System.out.println("Archive Entry - Name: " + filename); } aeFile = aisInput.getNextEntry(); } } catch (ArchiveException aX) { aX.printStackTrace(); } catch (IOException ioX) { ioX.printStackTrace(); } }