org.apache.commons.compress.archivers.ArchiveStreamFactory Java Examples

The following examples show how to use org.apache.commons.compress.archivers.ArchiveStreamFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TarfileTest.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
    final String encoding = "utf-8";

    byte[] body;

    ExtractableResponse response = RestAssured.given() //
            .contentType(ContentType.TEXT + "; charset=" + encoding).body("Hello World").post("/tarfile/post") //
            .then().extract();

    body = response.body().asByteArray();
    Assertions.assertNotNull(body);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ByteArrayInputStream bis = new ByteArrayInputStream(body);
    TarArchiveInputStream tis = (TarArchiveInputStream) new ArchiveStreamFactory()
            .createArchiveInputStream(ArchiveStreamFactory.TAR, bis);

    TarArchiveEntry entry = tis.getNextTarEntry();
    if (entry != null) {
        IOHelper.copy(tis, bos);
    }

    String str = bos.toString(encoding);
    Assertions.assertEquals("Hello World", str);
}
 
Example #2
Source File: LogUtils.java    From konduit-serving with Apache License 2.0 6 votes vote down vote up
public static File getZippedLogs() throws ArchiveException, IOException {
    File zippedFile = new File(DirectoryFetcher.getEndpointLogsDir(), "logs.zip");

    try (BufferedOutputStream archiveStream = new BufferedOutputStream(new FileOutputStream(zippedFile))) {
        try (ArchiveOutputStream archive = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP, archiveStream)) {
            File logsFile = getEndpointLogsFile();

            if(logsFile != null) {
                ZipArchiveEntry entry = new ZipArchiveEntry(logsFile.getName());
                archive.putArchiveEntry(entry);

                try (BufferedInputStream input = new BufferedInputStream(new FileInputStream(logsFile))) {
                    IOUtils.copy(input, archive);
                    archive.closeArchiveEntry();
                    archive.finish();
                }
            } else {
                throw new FileNotFoundException("No logs file found!");
            }
        }
    }

    return zippedFile;
}
 
Example #3
Source File: ComposerJsonExtractor.java    From nexus-repository-composer with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Extracts the contents for the first matching {@code composer.json} file (of which there should only be one) as a
 * map representing the parsed JSON content. If no such file is found then an empty map is returned.
 */
public Map<String, Object> extractFromZip(final Blob blob) throws IOException {
  try (InputStream is = blob.getInputStream()) {
    try (ArchiveInputStream ais = archiveStreamFactory.createArchiveInputStream(ArchiveStreamFactory.ZIP, is)) {
      ArchiveEntry entry = ais.getNextEntry();
      while (entry != null) {
        Map<String, Object> contents = processEntry(ais, entry);
        if (!contents.isEmpty()) {
          return contents;
        }
        entry = ais.getNextEntry();
      }
    }
    return Collections.emptyMap();
  }
  catch (ArchiveException e) {
    throw new IOException("Error reading from archive", e);
  }
}
 
Example #4
Source File: RDescriptionUtils.java    From nexus-repository-r with Eclipse Public License 1.0 6 votes vote down vote up
private static Map<String, String> extractMetadataFromArchive(final String archiveType, final InputStream is) {
  final ArchiveStreamFactory archiveFactory = new ArchiveStreamFactory();
  try (ArchiveInputStream ais = archiveFactory.createArchiveInputStream(archiveType, is)) {
    ArchiveEntry entry = ais.getNextEntry();
    while (entry != null) {
      if (!entry.isDirectory() && DESCRIPTION_FILE_PATTERN.matcher(entry.getName()).matches()) {
        return parseDescriptionFile(ais);
      }
      entry = ais.getNextEntry();
    }
  }
  catch (ArchiveException | IOException e) {
    throw new RException(null, e);
  }
  throw new IllegalStateException("No metadata file found");
}
 
Example #5
Source File: AzkabanJobHelper.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@edu.umd.cs.findbugs.annotations.SuppressWarnings(
    value = "OBL_UNSATISFIED_OBLIGATION",
    justification = "Lombok construct of @Cleanup is handing this, but not detected by FindBugs")
private static void addFilesToZip(File zipFile, List<File> filesToAdd) throws IOException {
  try {
    @Cleanup
    OutputStream archiveStream = new FileOutputStream(zipFile);
    @Cleanup
    ArchiveOutputStream archive =
        new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP, archiveStream);

    for (File fileToAdd : filesToAdd) {
      ZipArchiveEntry entry = new ZipArchiveEntry(fileToAdd.getName());
      archive.putArchiveEntry(entry);

      @Cleanup
      BufferedInputStream input = new BufferedInputStream(new FileInputStream(fileToAdd));
      IOUtils.copy(input, archive);
      archive.closeArchiveEntry();
    }

    archive.finish();
  } catch (ArchiveException e) {
    throw new IOException("Issue with creating archive", e);
  }
}
 
Example #6
Source File: PdpProcessor.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public AssemblyTemplate registerPdpFromArchive(InputStream archiveInput) {
    try {
        ArchiveInputStream input = new ArchiveStreamFactory()
            .createArchiveInputStream(archiveInput);
        
        while (true) {
            ArchiveEntry entry = input.getNextEntry();
            if (entry==null) break;
            // TODO unpack entry, create a space on disk holding the archive ?
        }

        // use yaml...
        throw new UnsupportedOperationException("in progress");
        
    } catch (Exception e) {
        throw Exceptions.propagate(e);
    }
}
 
Example #7
Source File: FilesArchiveCompressController.java    From MyBox with Apache License 2.0 6 votes vote down vote up
@Override
public String handleDirectory(File dir) {
    try {
        if (archiver.equalsIgnoreCase(ArchiveStreamFactory.AR)) {
            return AppVariables.message("Skip");
        }
        dirFilesNumber = dirFilesHandled = 0;
        addEntry(dir, rootName);
        if (rootName == null || rootName.trim().isEmpty()) {
            handleDirectory(dir, dir.getName());
        } else {
            handleDirectory(dir, rootName + "/" + dir.getName());
        }
        return MessageFormat.format(AppVariables.message("DirHandledSummary"),
                dirFilesNumber, dirFilesHandled);
    } catch (Exception e) {
        logger.debug(e.toString());
        return AppVariables.message("Failed");
    }
}
 
Example #8
Source File: CompressExample.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
public static void makeOnlyZip() throws IOException, ArchiveException{
	File f1 = new File("D:/compresstest.txt");
       File f2 = new File("D:/test1.xml");
       
       final OutputStream out = new FileOutputStream("D:/中文名字.zip");
       ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP, out);
       
       os.putArchiveEntry(new ZipArchiveEntry(f1.getName()));
       IOUtils.copy(new FileInputStream(f1), os);
       os.closeArchiveEntry();

       os.putArchiveEntry(new ZipArchiveEntry(f2.getName()));
       IOUtils.copy(new FileInputStream(f2), os);
       os.closeArchiveEntry();
       os.close();
}
 
Example #9
Source File: FilesDecompressUnarchiveBatchController.java    From MyBox with Apache License 2.0 6 votes vote down vote up
public void unarchive(File srcFile, BufferedInputStream fileIn) {
        try {
            archiver = ArchiveStreamFactory.detect(fileIn);
            if (archiver == null) {
                return;
            }
            if (archiver.equalsIgnoreCase(ArchiveStreamFactory.SEVEN_Z)) {
                unarchive7z(srcFile);
            } else if (archiver.equalsIgnoreCase(ArchiveStreamFactory.ZIP)) {
                unarchiveZip(srcFile);
            } else {
                try ( ArchiveInputStream in
                        = aFactory.createArchiveInputStream(archiver, fileIn, encoding)) {
                    unarchive(in);
                } catch (Exception ex) {
//                            logger.debug(ex.toString());
                }
            }
        } catch (Exception e) {
//            logger.debug(e.toString());
        }
    }
 
Example #10
Source File: CompressExample.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
public static void makeOnlyUnZip() throws ArchiveException, IOException{
		final InputStream is = new FileInputStream("D:/中文名字.zip");
		ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.ZIP, is);
		ZipArchiveEntry entry = entry = (ZipArchiveEntry) in.getNextEntry();
		
		String dir = "D:/cnname";
		File filedir = new File(dir);
		if(!filedir.exists()){
			filedir.mkdir();
		}
//		OutputStream out = new FileOutputStream(new File(dir, entry.getName()));
		OutputStream out = new FileOutputStream(new File(filedir, entry.getName()));
		IOUtils.copy(in, out);
		out.close();
		in.close();
	}
 
Example #11
Source File: ZipTest.java    From document-management-system with GNU General Public License v2.0 6 votes vote down vote up
public void testApache() throws IOException, ArchiveException {
	log.debug("testApache()");
	File zip = File.createTempFile("apache_", ".zip");
	
	// Create zip
	FileOutputStream fos = new FileOutputStream(zip);
	ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream("zip", fos);
	aos.putArchiveEntry(new ZipArchiveEntry("coñeta"));
	aos.closeArchiveEntry();
	aos.close();
	
	// Read zip
	FileInputStream fis = new FileInputStream(zip);
	ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream("zip", fis);
	ZipArchiveEntry zae = (ZipArchiveEntry) ais.getNextEntry();
	assertEquals(zae.getName(), "coñeta");
	ais.close();
}
 
Example #12
Source File: NpmPackageParser.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Parses the package.json in the supplied tar.gz if present and extractable. In all other situations, an empty map
 * will be returned indicating the absence of (or inability to extract) a valid package.json file and its contents.
 */
public Map<String, Object> parsePackageJson(final Supplier<InputStream> supplier) {
  try (InputStream is = new BufferedInputStream(supplier.get())) {
    final CompressorStreamFactory compressorStreamFactory = new CompressorStreamFactory();
    try (InputStream cis = compressorStreamFactory.createCompressorInputStream(GZIP, is)) {
      final ArchiveStreamFactory archiveFactory = new ArchiveStreamFactory();
      try (ArchiveInputStream ais = archiveFactory.createArchiveInputStream(TAR, cis)) {
        return parsePackageJsonInternal(ais);
      }
    }
  }
  catch (Exception e) {
    log.debug("Error occurred while processing package.json, returning empty map to continue", e);
    return emptyMap();
  }
}
 
Example #13
Source File: ModelExtractor.java    From tensorflow with Apache License 2.0 5 votes vote down vote up
/**
 * Detect the Archive and the Compressor from the file extension
 *
 * @param fileName File name with extension
 * @return Returns a tuple of the detected (Archive, Compressor). Null stands for not available archive or detector.
 * The (null, null) response stands for no Archive or Compressor discovered.
 */
private String[] detectArchiveAndCompressor(String fileName) {

	String normalizedFileName = fileName.trim().toLowerCase();

	if (normalizedFileName.endsWith(".tar.gz")
			|| normalizedFileName.endsWith(".tgz")
			|| normalizedFileName.endsWith(".taz")) {
		return new String[] { ArchiveStreamFactory.TAR, CompressorStreamFactory.GZIP };
	}
	else if (normalizedFileName.endsWith(".tar.bz2")
			|| normalizedFileName.endsWith(".tbz2")
			|| normalizedFileName.endsWith(".tbz")) {
		return new String[] { ArchiveStreamFactory.TAR, CompressorStreamFactory.BZIP2 };
	}
	else if (normalizedFileName.endsWith(".cpgz")) {
		return new String[] { ArchiveStreamFactory.CPIO, CompressorStreamFactory.GZIP };
	}
	else if (hasArchive(normalizedFileName)) {
		return new String[] { findArchive(normalizedFileName).get(), null };
	}
	else if (hasCompressor(normalizedFileName)) {
		return new String[] { null, findCompressor(normalizedFileName).get() };
	}
	else if (normalizedFileName.endsWith(".gzip")) {
		return new String[] { null, CompressorStreamFactory.GZIP };
	}
	else if (normalizedFileName.endsWith(".bz2")
			|| normalizedFileName.endsWith(".bz")) {
		return new String[] { null, CompressorStreamFactory.BZIP2 };
	}

	// No archived/compressed
	return new String[] { null, null };
}
 
Example #14
Source File: ZipFileUtils.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
public static void compressZipFile(String sourceDir, String zipFileName) throws IOException, ArchiveException {
    if (!validateZipFilename(zipFileName)) {
        throw new RuntimeException("Zip file must end with .zip");
    }
    Archiver archiver = new Archiver();
    archiver.create(ArchiveStreamFactory.ZIP, new File(zipFileName), new File(sourceDir));
}
 
Example #15
Source File: RNNodeService.java    From react-native-node with MIT License 5 votes vote down vote up
private static List<File> unTar(final File inputFile, final File outputDir) throws FileNotFoundException, IOException, ArchiveException {
    Log.i(TAG, String.format("Untaring %s to dir %s", inputFile.getAbsolutePath(), outputDir.getAbsolutePath()));

    if (!outputDir.exists()) {
        outputDir.mkdirs();
    }
    final List<File> untaredFiles = new LinkedList<File>();
    final InputStream is = new FileInputStream(inputFile);
    final TarArchiveInputStream debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar", is);
    TarArchiveEntry entry = null;
    while ((entry = (TarArchiveEntry)debInputStream.getNextEntry()) != null) {
        final File outputFile = new File(outputDir, entry.getName());
        if (entry.isDirectory()) {
            if (!outputFile.exists()) {
                if (!outputFile.mkdirs()) {
                    throw new IllegalStateException(String.format("Couldn't create directory %s.", outputFile.getAbsolutePath()));
                }
            }
        } else {
            final OutputStream outputFileStream = new FileOutputStream(outputFile);
            IOUtils.copy(debInputStream, outputFileStream);
            outputFileStream.close();
        }
        untaredFiles.add(outputFile);
    }
    debInputStream.close();

    return untaredFiles;
}
 
Example #16
Source File: CompressExample.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
public static void makeZip() throws IOException, ArchiveException{
		File f1 = new File("D:/compresstest.txt");
        File f2 = new File("D:/test1.xml");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        
        //ArchiveOutputStream ostemp = new ArchiveStreamFactory().createArchiveOutputStream("zip", baos);
        ZipArchiveOutputStream ostemp = new ZipArchiveOutputStream(baos);
        ostemp.setEncoding("GBK");
        ostemp.putArchiveEntry(new ZipArchiveEntry(f1.getName()));
        IOUtils.copy(new FileInputStream(f1), ostemp);
        ostemp.closeArchiveEntry();
        ostemp.putArchiveEntry(new ZipArchiveEntry(f2.getName()));
        IOUtils.copy(new FileInputStream(f2), ostemp);
        ostemp.closeArchiveEntry();
        ostemp.finish();
        ostemp.close();

//      final OutputStream out = new FileOutputStream("D:/testcompress.zip");
        final OutputStream out = new FileOutputStream("D:/中文名字.zip");
        ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);
        os.putArchiveEntry(new ZipArchiveEntry("打包.zip"));
        baos.writeTo(os);
        os.closeArchiveEntry();
        baos.close();
        os.finish();
        os.close();
	}
 
Example #17
Source File: PyPiInfoUtils.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Extracts metadata from an archive directly (such as for tar and zip formats).
 */
private static Map<String, String> extractMetadataFromArchive(final String archiveType,
                                                              final InputStream is)
    throws Exception
{
  checkNotNull(archiveType);
  checkNotNull(is);

  final ArchiveStreamFactory archiveFactory = new ArchiveStreamFactory();
  try (ArchiveInputStream ais = archiveFactory.createArchiveInputStream(archiveType, is)) {
    return processArchiveEntries(ais);
  }
}
 
Example #18
Source File: TraceImportOperationTest.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
private static void createArchive(String sourcePath, File archive) throws FileNotFoundException, IOException, ArchiveException {
    try (OutputStream out = new FileOutputStream(archive);
            ArchiveOutputStream archiveOutputStream = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP, out)) {
        for (File file : FileUtils.listFiles(new File(sourcePath), null, true)) {
            String name = file.getAbsolutePath().substring(sourcePath.length());
            archiveOutputStream.putArchiveEntry(new ZipArchiveEntry(name));
            try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) {
                IOUtils.copy(in, archiveOutputStream);
            }
            archiveOutputStream.closeArchiveEntry();
        }
        archiveOutputStream.finish();
    }
}
 
Example #19
Source File: CompressionDataParser.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public InputStream getNextInputStream() throws IOException {
  if(archiveInputStream == null) {
    // Very first call to getNextInputStream, initialize archiveInputStream using the wrappedOffset
    wrappedOffset = wrappedOffset.equals(ZERO) ? wrapOffset(wrappedOffset) : wrappedOffset;
    Map<String, Object> archiveInputOffset = objectMapper.readValue(wrappedOffset, Map.class);
    try {
      archiveInputStream = new ArchiveStreamFactory().createArchiveInputStream(
          new BufferedInputStream(compressionInput.getNextInputStream()));
    } catch (ArchiveException e) {
      throw new IOException(e);
    }
    seekToOffset(archiveInputOffset);
    nextInputStream = archiveInputStream;
  }

  if (nextInputStream == null) {
    // this means reached end of a compressed file within the archive. seek to the next eligible entry
    seekToNextEligibleEntry();
    if (currentEntry != null) {
      // Not end of archive
      nextInputStream = archiveInputStream;
    }
  }
  InputStream temp = nextInputStream;
  nextInputStream = null;
  return temp;
}
 
Example #20
Source File: ZipFileUtils.java    From kylin with Apache License 2.0 5 votes vote down vote up
public static void compressZipFile(String sourceDir, String zipFileName) throws IOException, ArchiveException {
    if (!validateZipFilename(zipFileName)) {
        throw new RuntimeException("Zip file must end with .zip");
    }
    Archiver archiver = new Archiver();
    archiver.create(ArchiveStreamFactory.ZIP, new File(zipFileName), new File(sourceDir));
}
 
Example #21
Source File: ZipFiles.java    From ankush with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Zip file.
 *
 * @param filePath the file path
 * @return the string
 */
public String zipFile(String filePath) {
	try {
		/* Create Output Stream that will have final zip files */
		OutputStream zipOutput = new FileOutputStream(new File(filePath
				+ ".zip"));
		/*
		 * Create Archive Output Stream that attaches File Output Stream / and
		 * specifies type of compression
		 */
		ArchiveOutputStream logicalZip = new ArchiveStreamFactory()
				.createArchiveOutputStream(ArchiveStreamFactory.ZIP, zipOutput);
		/* Create Archieve entry - write header information */
		logicalZip.putArchiveEntry(new ZipArchiveEntry(FilenameUtils.getName(filePath)));
		/* Copy input file */
		IOUtils.copy(new FileInputStream(new File(filePath)), logicalZip);
		/* Close Archieve entry, write trailer information */
		logicalZip.closeArchiveEntry();

		/* Finish addition of entries to the file */
		logicalZip.finish();
		/* Close output stream, our files are zipped */
		zipOutput.close();
	} catch (Exception e) {
		System.err.println(e.getMessage());
		return null;
	}
	return filePath + ".zip";
}
 
Example #22
Source File: Archives.java    From wildfly-maven-plugin with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Unzips the zip file to the target directory.
 * <p>
 * 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);
    }
}
 
Example #23
Source File: CompressUtil.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method that attempts to automatically identify an archive and its type,
 * extract the contents as a byte array. If this fails, it will gracefully return
 * the original input byte array without exception. If the input was not an archive
 * or compressed, it will return the original byte array.
 * @param input the
 * @return a byte array
 */
public static byte[] optionallyDecompress(final byte[] input) {
    try (final ByteArrayInputStream bis = new ByteArrayInputStream(input);
         final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(bis)) {
        final ArchiveEntry entry = ais.getNextEntry();
        if (ais.canReadEntryData(entry)) {
            return IOUtils.toByteArray(ais);
        }
    } catch (ArchiveException | IOException e) {
        // throw it away and return the original byte array
    }
    return input;
}
 
Example #24
Source File: ArchiveResource.java    From embedded-cassandra with Apache License 2.0 5 votes vote down vote up
private static ArchiveInputStreamFactory create(String archiveType, String compressorType) {
	return is -> {
		ArchiveStreamFactory af = new ArchiveStreamFactory();
		CompressorStreamFactory csf = new CompressorStreamFactory();
		return af.createArchiveInputStream(archiveType, csf.createCompressorInputStream(compressorType, is));
	};
}
 
Example #25
Source File: FilesArchiveCompressController.java    From MyBox with Apache License 2.0 5 votes vote down vote up
@Override
public void afterHandleFiles() {
    try {
        if (archiver.equalsIgnoreCase(ArchiveStreamFactory.SEVEN_Z)) {
            sevenZOutput.finish();
            sevenZOutput.close();
        } else {
            archiveOut.finish();
            archiveOut.close();
        }
        if (targetFile.exists()) {
            targetFile.delete();
        }
        if (!message("None").equals(compressor)) {
            File tmpFile = FileTools.getTempFile();
            try ( BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(archiveFile));
                  BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tmpFile));
                  CompressorOutputStream compressOut = new CompressorStreamFactory().
                         createCompressorOutputStream(compressor, out)) {
                IOUtils.copy(inputStream, compressOut);
            }
            tmpFile.renameTo(targetFile);
        } else {
            archiveFile.renameTo(targetFile);
        }
    } catch (Exception e) {
        logger.debug(e.toString());
    }
}
 
Example #26
Source File: FilesDecompressUnarchiveBatchController.java    From MyBox with Apache License 2.0 5 votes vote down vote up
@Override
public boolean beforeHandleFiles() {
    try {
        cFactory = new CompressorStreamFactory();
        aFactory = new ArchiveStreamFactory();
        archiveSuccess = archiveFail = 0;
        charsetIncorrect = false;
        return true;
    } catch (Exception e) {
        logger.debug(e.toString());
        return false;
    }
}
 
Example #27
Source File: FilesArchiveCompressController.java    From MyBox with Apache License 2.0 5 votes vote down vote up
protected void checkArchiver() {
    archiver = ((RadioButton) archiverGroup.getSelectedToggle()).getText();
    archiverLabel.setText("");
    sevenZCompressPane.setVisible(archiver.equalsIgnoreCase(ArchiveStreamFactory.SEVEN_Z));
    if (archiver.equalsIgnoreCase(ArchiveStreamFactory.AR)) {
        archiverLabel.setText(message("ARArchivesLimitation"));
    }
    pack200Radio.setDisable(!archiver.equalsIgnoreCase(ArchiveStreamFactory.ZIP)
            && !archiver.equalsIgnoreCase(ArchiveStreamFactory.JAR));
    if (pack200Radio.isDisabled() && pack200Radio.isSelected()) {
        gzRadio.fire();
    }
    checkExtension();
}
 
Example #28
Source File: CompressionUtils.java    From waterdrop with Apache License 2.0 5 votes vote down vote up
/** Untar an input file into an output file.

     * The output file is created in the output folder, having the same name
     * as the input file, minus the '.tar' extension.
     *
     * @param inputFile     the input .tar file
     * @param outputDir     the output directory file.
     * @throws IOException
     * @throws FileNotFoundException
     *
     * @return  The {@link List} of {@link File}s with the untared content.
     * @throws ArchiveException
     */
    public static List<File> unTar(final File inputFile, final File outputDir) throws FileNotFoundException, IOException, ArchiveException {

        logger.info(String.format("Untaring %s to dir %s.", inputFile.getAbsolutePath(), outputDir.getAbsolutePath()));

        final List<File> untaredFiles = new LinkedList<File>();
        final InputStream is = new FileInputStream(inputFile);
        final TarArchiveInputStream debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar", is);
        TarArchiveEntry entry = null;
        while ((entry = (TarArchiveEntry)debInputStream.getNextEntry()) != null) {
            final File outputFile = new File(outputDir, entry.getName());
            if (entry.isDirectory()) {
                logger.info(String.format("Attempting to write output directory %s.", outputFile.getAbsolutePath()));
                if (!outputFile.exists()) {
                    logger.info(String.format("Attempting to create output directory %s.", outputFile.getAbsolutePath()));
                    if (!outputFile.mkdirs()) {
                        throw new IllegalStateException(String.format("Couldn't create directory %s.", outputFile.getAbsolutePath()));
                    }
                }
            } else {
                logger.info(String.format("Creating output file %s.", outputFile.getAbsolutePath()));
                final OutputStream outputFileStream = new FileOutputStream(outputFile);
                IOUtils.copy(debInputStream, outputFileStream);
                outputFileStream.close();
            }
            untaredFiles.add(outputFile);
        }
        debInputStream.close();

        return untaredFiles;
    }
 
Example #29
Source File: FileDecompressUnarchiveController.java    From MyBox with Apache License 2.0 5 votes vote down vote up
protected void checkArchiver() {
    archiverChoice = ((RadioButton) archiverGroup.getSelectedToggle()).getText();
    sevenZCompressPane.setVisible(archiverChoice.equalsIgnoreCase(ArchiveStreamFactory.SEVEN_Z));
    if (archiverChoice.equals(message("DetectAutomatically"))) {
        archiverChoice = "auto";
    } else if (archiverChoice.equals(message("None"))) {
        archiverChoice = "none";
    }
    readFile();
}
 
Example #30
Source File: FileUtil.java    From teku with Apache License 2.0 5 votes vote down vote up
public static void unTar(final File inputTarFile, final File outputDir)
    throws IOException, ArchiveException {
  final InputStream fileStream = new FileInputStream(inputTarFile);
  try (final ArchiveInputStream archiveStream =
      new ArchiveStreamFactory().createArchiveInputStream("tar", fileStream)) {
    ArchiveEntry entry;
    while ((entry = archiveStream.getNextEntry()) != null) {
      final File outputFile = new File(outputDir, entry.getName());
      if (entry.isDirectory() && !outputFile.exists()) {
        // Create directory
        if (!outputFile.mkdirs()) {
          throw new IllegalStateException(
              "Could not create directory " + outputFile.getAbsolutePath());
        }
      } else if (!entry.isDirectory()) {
        // Make sure parent directories exist
        File parent = outputFile.getParentFile();
        if (!parent.isDirectory() && !parent.mkdirs()) {
          throw new IllegalStateException(
              "Could not create directory " + parent.getAbsolutePath());
        }
        // Create file
        try (final OutputStream outputFileStream = new FileOutputStream(outputFile)) {
          IOUtils.copy(archiveStream, outputFileStream);
        }
      }
    }
  }
}