Example usage for org.apache.commons.compress.archivers ArchiveStreamFactory ArchiveStreamFactory

List of usage examples for org.apache.commons.compress.archivers ArchiveStreamFactory ArchiveStreamFactory

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers ArchiveStreamFactory ArchiveStreamFactory.

Prototype

ArchiveStreamFactory

Source Link

Usage

From source file:ezbake.deployer.utilities.Utilities.java

public static void appendFilesInTarArchive(OutputStream output, byte[] currentArchive,
        Iterable<ArtifactDataEntry> filesToAdd) throws DeploymentException {
    ArchiveStreamFactory asf = new ArchiveStreamFactory();

    try (GZIPOutputStream gzs = new GZIPOutputStream(output)) {
        try (ArchiveOutputStream aos = asf.createArchiveOutputStream(ArchiveStreamFactory.TAR, gzs)) {
            try (GZIPInputStream gzip = new GZIPInputStream(new ByteArrayInputStream(currentArchive))) {
                try (TarArchiveInputStream tarInputStream = new TarArchiveInputStream(gzip)) {
                    TarArchiveEntry tarEntry = null;

                    while ((tarEntry = tarInputStream.getNextTarEntry()) != null) {
                        aos.putArchiveEntry(tarEntry);
                        IOUtils.copy(tarInputStream, aos);
                        aos.closeArchiveEntry();
                    }//from  w w w.j a  va 2 s.  c o  m
                }
            }

            for (ArtifactDataEntry entry : filesToAdd) {
                aos.putArchiveEntry(entry.getEntry());
                IOUtils.write(entry.getData(), aos);
                aos.closeArchiveEntry();
            }
        }
    } catch (ArchiveException e) {
        log.error(e.getMessage(), e);
        throw new DeploymentException(e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new DeploymentException(e.getMessage());
    }
}

From source file:com.github.wnameless.linereader.ArchiveLineReader.java

public ArchiveLineReader(InputStream is, String entryPath, String encoding)
        throws IOException, ArchiveException {
    ArchiveInputStream archiveIS = new ArchiveStreamFactory()
            .createArchiveInputStream(new BufferedInputStream(is));

    if (entryPath == null)
        setEntry(archiveIS);/*from  ww  w  .j  a va  2 s  . c o  m*/
    else
        setEntry(archiveIS, entryPath);

    bufferedReader = new BufferedReader(
            new InputStreamReader(archiveIS, encoding == null ? "UTF-8" : encoding));
}

From source file:com.bahmanm.karun.Utils.java

/**
 * Extracts a gzip'ed tar archive.//from   ww  w  . jav  a  2s . com
 * 
 * @param archivePath Path to archive
 * @param destDir Destination directory
 * @throws IOException 
 */
public synchronized static void extractTarGz(String archivePath, File destDir)
        throws IOException, ArchiveException {
    // copy
    File tarGzFile = File.createTempFile("karuntargz", "", destDir);
    copyFile(archivePath, tarGzFile.getAbsolutePath());

    // decompress
    File tarFile = File.createTempFile("karuntar", "", destDir);
    FileInputStream fin = new FileInputStream(tarGzFile);
    BufferedInputStream bin = new BufferedInputStream(fin);
    FileOutputStream fout = new FileOutputStream(tarFile);
    GzipCompressorInputStream gzIn = new GzipCompressorInputStream(bin);
    final byte[] buffer = new byte[1024];
    int n = 0;
    while (-1 != (n = gzIn.read(buffer))) {
        fout.write(buffer, 0, n);
    }
    bin.close();
    fin.close();
    gzIn.close();
    fout.close();

    // extract
    final InputStream is = new FileInputStream(tarFile);
    ArchiveInputStream ain = new ArchiveStreamFactory().createArchiveInputStream("tar", is);
    TarArchiveEntry entry = null;
    while ((entry = (TarArchiveEntry) ain.getNextEntry()) != null) {
        OutputStream out;
        if (entry.isDirectory()) {
            File f = new File(destDir, entry.getName());
            f.mkdirs();
            continue;
        } else
            out = new FileOutputStream(new File(destDir, entry.getName()));
        IOUtils.copy(ain, out);
        out.close();
    }
    ain.close();
    is.close();
}

From source file:big.zip.java

/**
 * /*from   w w w  .  j  ava  2s.co m*/
 * @param fileToCompress    The file that we want to compress
 * @param fileToOutput      The zip file containing the compressed file
 * @return  True if the file was compressed and created, false when something
 * went wrong
 */
public static boolean compress(final File fileToCompress, final File fileToOutput) {
    if (fileToOutput.exists()) {
        // do the first run to delete this file
        fileToOutput.delete();
        // did this worked?
        if (fileToOutput.exists()) {
            // something went wrong, the file is still here
            System.out.println("ZIP59 - Failed to delete output file: " + fileToOutput.getAbsolutePath());
            return false;
        }
    }
    // does our file to compress exist?
    if (fileToCompress.exists() == false) {
        // we have a problem here
        System.out.println("ZIP66 - Didn't found the file to compress: " + fileToCompress.getAbsolutePath());
        return false;
    }
    // all checks are done, now it is time to do the compressing
    try {
        final OutputStream outputStream = new FileOutputStream(fileToOutput);
        ArchiveOutputStream archive = new ArchiveStreamFactory().createArchiveOutputStream("zip", outputStream);
        archive.putArchiveEntry(new ZipArchiveEntry(fileToCompress.getName()));
        // create the input file stream and copy it over to the archive
        FileInputStream inputStream = new FileInputStream(fileToCompress);
        IOUtils.copy(inputStream, archive);
        // close the archive
        archive.closeArchiveEntry();
        archive.flush();
        archive.close();
        // now close the input file stream
        inputStream.close();
        // and close the output file stream too
        outputStream.flush();
        outputStream.close();

    } catch (FileNotFoundException ex) {
        Logger.getLogger(zip.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (ArchiveException ex) {
        Logger.getLogger(zip.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (IOException ex) {
        Logger.getLogger(zip.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
    return true;
}

From source file:com.github.benmanes.caffeine.cache.simulator.parser.AbstractTraceReader.java

/** Returns the input stream, decompressing if required. */
private InputStream readFile(String filePath) throws IOException {
    BufferedInputStream input = new BufferedInputStream(openFile(filePath), BUFFER_SIZE);
    input.mark(100);//from  w w w  .j  a  v  a2s.c  om
    try {
        return new XZInputStream(input);
    } catch (IOException e) {
        input.reset();
    }
    try {
        return new CompressorStreamFactory().createCompressorInputStream(input);
    } catch (CompressorException e) {
        input.reset();
    }
    try {
        return new ArchiveStreamFactory().createArchiveInputStream(input);
    } catch (ArchiveException e) {
        input.reset();
    }
    return input;
}

From source file:at.beris.virtualfile.provider.LocalArchivedFileOperationProvider.java

@Override
public Boolean exists(FileModel model) throws IOException {
    String archivePath = getArchivePath(model);
    String targetArchiveEntryPath = model.getUrl().getPath().substring(archivePath.length() + 1);

    ArchiveInputStream ais = null;//from w  ww  .  j a  va  2s .c o m
    InputStream fis = null;

    try {
        ArchiveStreamFactory factory = new ArchiveStreamFactory();
        fis = new BufferedInputStream(new FileInputStream(new java.io.File(archivePath)));
        ais = factory.createArchiveInputStream(fis);
        ArchiveEntry archiveEntry;

        while ((archiveEntry = ais.getNextEntry()) != null) {
            String archiveEntryPath = archiveEntry.getName();

            if (archiveEntryPath.equals(targetArchiveEntryPath)) {
                model.setSize(archiveEntry.getSize());
                model.setLastModifiedTime(FileTime.fromMillis(archiveEntry.getLastModifiedDate().getTime()));

                if (model.getUrl().toString().endsWith("/") && (!archiveEntry.isDirectory())) {
                    String urlString = model.getUrl().toString();
                    model.setUrl(UrlUtils.newUrl(urlString.substring(0, urlString.length() - 1)));
                } else if (!model.getUrl().toString().endsWith("/") && (archiveEntry.isDirectory())) {
                    String urlString = model.getUrl().toString() + "/";
                    model.setUrl(UrlUtils.newUrl(urlString));
                }
                break;
            }
        }
    } catch (ArchiveException e) {
        throw new IOException(e);
    } finally {
        if (ais != null)
            ais.close();
        if (fis != null)
            fis.close();
    }
    return false;
}

From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.profile.RegistryBackedArchiveProfileBuilder.java

public List<Profile> build(DeploymentConfiguration deploymentConfiguration, String baseOutputPath,
        SpinnakerArtifact artifact, String archiveName) {
    String version = artifactService.getArtifactVersion(deploymentConfiguration.getName(), artifact);
    String archiveObjectName = ProfileRegistry.profilePath(artifact.getName(), version,
            archiveName + ".tar.gz");

    InputStream is;/*  w  w  w  .  ja v  a2s .  com*/
    try {
        is = profileRegistry.getObjectContents(archiveObjectName);
    } catch (IOException e) {
        throw new HalException(Problem.Severity.FATAL,
                "Error retrieving contents of archive " + archiveObjectName, e);
    }

    TarArchiveInputStream tis;
    try {
        tis = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar", is);
    } catch (ArchiveException e) {
        throw new HalException(Problem.Severity.FATAL, "Failed to unpack tar archive", e);
    }

    try {
        List<Profile> result = new ArrayList<>();

        ArchiveEntry profileEntry = tis.getNextEntry();
        while (profileEntry != null) {
            if (profileEntry.isDirectory()) {
                profileEntry = tis.getNextEntry();
                continue;
            }

            String entryName = profileEntry.getName();
            String profileName = String.join("/", artifact.getName(), archiveName, entryName);
            String outputPath = Paths.get(baseOutputPath, archiveName, entryName).toString();
            String contents = IOUtils.toString(tis);

            result.add((new ProfileFactory() {
                @Override
                protected void setProfile(Profile profile, DeploymentConfiguration deploymentConfiguration,
                        SpinnakerRuntimeSettings endpoints) {
                    profile.setContents(profile.getBaseContents());
                }

                @Override
                protected Profile getBaseProfile(String name, String version, String outputFile) {
                    return new Profile(name, version, outputFile, contents);
                }

                @Override
                protected boolean showEditWarning() {
                    return false;
                }

                @Override
                protected ArtifactService getArtifactService() {
                    return artifactService;
                }

                @Override
                public SpinnakerArtifact getArtifact() {
                    return artifact;
                }

                @Override
                protected String commentPrefix() {
                    return null;
                }
            }).getProfile(profileName, outputPath, deploymentConfiguration, null));

            profileEntry = tis.getNextEntry();
        }

        return result;
    } catch (IOException e) {
        throw new HalException(Problem.Severity.FATAL, "Failed to read profile entry", e);
    }

}

From source file:io.covert.binary.analysis.BuildTarBzSequenceFile.java

@Override
public int run(String[] args) throws Exception {

    File inDir = new File(args[0]);
    Path name = new Path(args[1]);

    Text key = new Text();
    BytesWritable val = new BytesWritable();

    Configuration conf = getConf();
    FileSystem fs = FileSystem.get(conf);
    if (!fs.exists(name)) {
        fs.mkdirs(name);/*from w w  w .  ja va2 s  .  c  om*/
    }
    for (File file : inDir.listFiles()) {
        Path sequenceName = new Path(name, file.getName() + ".seq");
        System.out.println("Writing to " + sequenceName);
        SequenceFile.Writer writer = SequenceFile.createWriter(fs, conf, sequenceName, Text.class,
                BytesWritable.class, CompressionType.RECORD);
        if (!file.isFile()) {
            System.out.println("Skipping " + file + " (not a file) ...");
            continue;
        }

        final InputStream is = new FileInputStream(file);
        final TarArchiveInputStream debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory()
                .createArchiveInputStream("tar", is);
        TarArchiveEntry entry = null;
        while ((entry = (TarArchiveEntry) debInputStream.getNextEntry()) != null) {
            if (!entry.isDirectory()) {

                final ByteArrayOutputStream outputFileStream = new ByteArrayOutputStream();
                IOUtils.copy(debInputStream, outputFileStream);
                outputFileStream.close();
                byte[] outputFile = outputFileStream.toByteArray();
                val.set(outputFile, 0, outputFile.length);

                MessageDigest md = MessageDigest.getInstance("MD5");
                md.update(outputFile);
                byte[] digest = md.digest();
                String hexdigest = "";
                for (int i = 0; i < digest.length; i++) {
                    hexdigest += Integer.toString((digest[i] & 0xff) + 0x100, 16).substring(1);
                }
                key.set(hexdigest);
                writer.append(key, val);
            }
        }
        debInputStream.close();
        writer.close();
    }

    return 0;
}

From source file:algorithm.ZipPackaging.java

@Override
public File encapsulate(File carrier, List<File> payloadList) throws IOException {
    String outputName = getOutputFileName(carrier);
    int dotIndex = outputName.lastIndexOf('.');
    if (dotIndex > 0) {
        outputName = outputName.substring(0, dotIndex) + ".zip";
    }//www.  java2 s .c o m
    File zipFile = new File(outputName);
    try {
        FileOutputStream outputStream = new FileOutputStream(zipFile);
        ArchiveOutputStream archiveOutputStream = new ArchiveStreamFactory()
                .createArchiveOutputStream(ArchiveStreamFactory.ZIP, outputStream);
        archiveFile(archiveOutputStream, carrier);
        for (File payload : payloadList) {
            archiveFile(archiveOutputStream, payload);
        }
        archiveOutputStream.close();
        outputStream.close();
    } catch (ArchiveException e) {
    }
    return zipFile;
}

From source file:com.zenome.bundlebus.Util.java

public static List<File> unTar(@NonNull final File tarFile, @NonNull final File outputDir)
        throws FileNotFoundException, IOException, ArchiveException {
    //        Log.d(TAG, "tar filename : " + tarFile);
    //        Log.d(TAG, "output folder : " + outputDir);

    final List<File> untaredFiles = new LinkedList<File>();
    final InputStream is = new FileInputStream(tarFile);
    final TarArchiveInputStream debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory()
            .createArchiveInputStream("tar", is);

    TarArchiveEntry entry = null;//from  ww  w  .java  2 s  .co  m
    while ((entry = (TarArchiveEntry) debInputStream.getNextEntry()) != null) {
        String name = entry.getName();
        if (name.startsWith("./")) {
            name = entry.getName().substring(2);
        }

        final File outputFile = new File(outputDir, name);
        if (entry.isDirectory()) {
            //                Log.d(TAG, "Attempting to write output directory " + outputFile.getAbsolutePath());
            if (!outputFile.exists()) {
                Log.d(TAG, "Attempting to create output directory " + outputFile.getAbsolutePath());
                if (!outputFile.mkdirs()) {
                    throw new IllegalStateException(
                            "Couldn't create directory " + outputFile.getAbsolutePath());
                }
            }
        } else {
            //                Log.d(TAG, "Creating output file " + outputFile.getAbsolutePath());
            final OutputStream outputFileStream = new FileOutputStream(outputFile);
            Log.d(TAG, "IOUtils.copy : " + IOUtils.copy(debInputStream, outputFileStream));
            outputFileStream.close();
        }

        //            Log.d(TAG, "Filename : " + outputFile);
        //            Log.d(TAG, "is exist : " + outputFile.exists());
        untaredFiles.add(outputFile);
    }
    debInputStream.close();

    return untaredFiles;
}