Example usage for org.apache.commons.compress.archivers.tar TarArchiveInputStream TarArchiveInputStream

List of usage examples for org.apache.commons.compress.archivers.tar TarArchiveInputStream TarArchiveInputStream

Introduction

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

Prototype

public TarArchiveInputStream(InputStream is) 

Source Link

Document

Constructor for TarInputStream.

Usage

From source file:gdt.data.entity.ArchiveHandler.java

/**
 * Discover if the tar file contains the property index
 * @param  tarfile$ the path of the archive file.
 *  @return true if contains, false otherwise.
 *///from  ww  w  . j a  v a 2s.  c  o m
public static boolean hasPropertyIndexInTar(String tarfile$) {
    try {
        TarArchiveInputStream tis = new TarArchiveInputStream(new FileInputStream(new File(tarfile$)));
        return hasPropertyIndexInTarStream(tis);
    } catch (Exception e) {
        Logger.getLogger(ArchiveHandler.class.getName()).severe(e.toString());
    }
    return false;
}

From source file:gdt.data.entity.ArchiveHandler.java

/**
 * Discover if the tar.gz file contains the property index
 * @param  tgzfile$ archive file.//www  .j a va2 s .c  om
 *  @return true if contains, false otherwise.
 */
public static boolean hasPropertyIndexInTgz(String tgzfile$) {
    try {
        //FileInputStream fis = new FileInputStream(gzipFile);
        GZIPInputStream gis = new GZIPInputStream(new FileInputStream(new File(tgzfile$)));
        TarArchiveInputStream tis = new TarArchiveInputStream(gis);
        return hasPropertyIndexInTarStream(tis);
    } catch (Exception e) {
        Logger.getLogger(ArchiveHandler.class.getName()).severe(e.toString());
    }
    return false;
}

From source file:edu.harvard.iq.dvn.core.web.study.AddFilesPage.java

private List<StudyFileEditBean> createStudyFilesFromTar(File uploadedInputFile) {
    List<StudyFileEditBean> fbList = new ArrayList<StudyFileEditBean>();

    File dir = new File(uploadedInputFile.getParentFile(), study.getId().toString());
    if (!dir.exists()) {
        dir.mkdir();/*  w w w  .ja  va 2  s .c o m*/
    }

    List<File> directoriesToDelete = new ArrayList<File>();
    File unzippedFile = null;
    TarArchiveInputStream tiStream = null;
    FileOutputStream tempOutStream = null;
    String unzipError = "";
    if (GzipUtils.isCompressedFilename(uploadedInputFile.getName())) {
        try {
            GZIPInputStream zippedInput = new GZIPInputStream(new FileInputStream(uploadedInputFile));
            unzippedFile = new File(dir, "unzipped-file-" + UUID.randomUUID());
            FileOutputStream unzippedOutput = new FileOutputStream(unzippedFile);
            byte[] dataBuffer = new byte[8192];
            int i = 0;
            while ((i = zippedInput.read(dataBuffer)) > 0) {
                unzippedOutput.write(dataBuffer, 0, i);
                unzippedOutput.flush();
            }
            tiStream = new TarArchiveInputStream(new FileInputStream(unzippedFile));
        } catch (Exception ex) {
            unzipError = " A common gzip extension was found but is the file corrupt?";
        }
    } else if (BZip2Utils.isCompressedFilename(uploadedInputFile.getName())) {
        try {
            BZip2CompressorInputStream zippedInput = new BZip2CompressorInputStream(
                    new FileInputStream(uploadedInputFile));
            unzippedFile = new File(dir, "unzipped-file-" + UUID.randomUUID());
            FileOutputStream unzippedOutput = new FileOutputStream(unzippedFile);
            byte[] dataBuffer = new byte[8192];
            int i = 0;
            while ((i = zippedInput.read(dataBuffer)) > 0) {
                unzippedOutput.write(dataBuffer, 0, i);
                unzippedOutput.flush();
            }
            tiStream = new TarArchiveInputStream(new FileInputStream(unzippedFile));
        } catch (Exception ex) {
            unzipError = " A common bzip2 extension was found but is the file corrupt?";
        }
    } else {
        try {
            // no need to decompress, carry on
            tiStream = new TarArchiveInputStream(new FileInputStream(uploadedInputFile));
        } catch (FileNotFoundException ex) {
            unzipError = " Is the tar file corrupt?";
        }
    }

    TarArchiveEntry tEntry = null;

    if (tiStream == null) {
        String msg = "Problem reading uploaded file." + unzipError;
        setTarValidationErrorMessage(msg);
        uploadedInputFile.delete();
        fbList = new ArrayList<StudyFileEditBean>();
        return fbList;
    }
    try {
        while ((tEntry = tiStream.getNextTarEntry()) != null) {

            String fileEntryName = tEntry.getName();

            if (!tEntry.isDirectory()) {

                if (fileEntryName != null && !fileEntryName.equals("")) {

                    String dirName = null;
                    String finalFileName = fileEntryName;

                    int ind = fileEntryName.lastIndexOf('/');

                    if (ind > -1) {
                        finalFileName = fileEntryName.substring(ind + 1);
                        if (ind > 0) {
                            dirName = fileEntryName.substring(0, ind);
                            dirName = dirName.replace('/', '-');
                        }
                    } else {
                        finalFileName = fileEntryName;
                    }

                    // only process normal tar entries, not the ones that start with "._" because they were created on a mac:
                    // http://superuser.com/questions/61185/why-do-i-get-files-like-foo-in-my-tarball-on-os-x
                    // http://superuser.com/questions/212896/is-there-any-way-to-prevent-a-mac-from-creating-dot-underscore-files
                    if (!finalFileName.startsWith("._")) {

                        File tempUploadedFile = null;
                        try {
                            tempUploadedFile = FileUtil.createTempFile(dir, finalFileName);
                        } catch (Exception ex) {
                            Logger.getLogger(AddFilesPage.class.getName()).log(Level.SEVERE, null, ex);
                            String msg = "Problem creating temporary file.";
                            setTarValidationErrorMessage(msg);
                        }

                        tempOutStream = new FileOutputStream(tempUploadedFile);

                        byte[] dataBuffer = new byte[8192];
                        int i = 0;

                        while ((i = tiStream.read(dataBuffer)) > 0) {
                            tempOutStream.write(dataBuffer, 0, i);
                            tempOutStream.flush();
                        }

                        tempOutStream.close();

                        try {
                            StudyFileEditBean tempFileBean = new StudyFileEditBean(tempUploadedFile,
                                    studyService.generateFileSystemNameSequence(), study);
                            tempFileBean.setSizeFormatted(tempUploadedFile.length());
                            if (dirName != null) {
                                tempFileBean.getFileMetadata().setCategory(dirName);
                            }
                            fbList.add(tempFileBean);
                            setTarValidationErrorMessage(null);
                        } catch (Exception ex) {
                            String msg = "Problem preparing files for ingest. Is the tar file corrupt?";
                            setTarValidationErrorMessage(msg);
                            uploadedInputFile.delete();
                            tempUploadedFile.delete();
                            fbList = new ArrayList<StudyFileEditBean>();
                        }
                    }
                }
            } else {
                File directory = new File(dir, fileEntryName);
                directory.mkdir();
                directoriesToDelete.add(directory);
            }
        }
    } catch (IOException ex) {
        String msg = "Problem reading tar file. Is it corrupt?";
        setTarValidationErrorMessage(msg);
    }

    // teardown and cleanup
    try {
        tiStream.close();
    } catch (IOException ex) {
        Logger.getLogger(AddFilesPage.class.getName()).log(Level.SEVERE, null, ex);
    }
    if (tiStream != null) {
        try {
            tiStream.close();
        } catch (IOException ex) {
            Logger.getLogger(AddFilesPage.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    if (tempOutStream != null) {
        try {
            tempOutStream.close();
        } catch (IOException ex) {
            Logger.getLogger(AddFilesPage.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    uploadedInputFile.delete();
    if (unzippedFile != null) {
        unzippedFile.delete();
    }
    for (File dirToDelete : directoriesToDelete) {
        if (dirToDelete.exists()) {
            try {
                FileUtils.forceDelete(dirToDelete);
            } catch (IOException ex) {
                Logger.getLogger(AddFilesPage.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    return fbList;
}

From source file:frameworks.Masken.java

public static void uncompressTarGZ(File tarFile, File dest) throws IOException {
    dest.mkdir();/*from  w w w .  j av  a2s. com*/
    TarArchiveInputStream tarIn = null;

    tarIn = new TarArchiveInputStream(
            new GzipCompressorInputStream(new BufferedInputStream(new FileInputStream(tarFile))));

    TarArchiveEntry tarEntry = tarIn.getNextTarEntry();
    // tarIn is a TarArchiveInputStream
    while (tarEntry != null) {// create a file with the same name as the tarEntry
        File destPath = new File(dest, tarEntry.getName());
        System.out.println("working: " + destPath.getCanonicalPath());
        if (tarEntry.isDirectory()) {
            destPath.mkdirs();
        } else {
            if (!destPath.getParentFile().exists()) {
                destPath.getParentFile().mkdirs();
            }
            destPath.createNewFile();
            //byte [] btoRead = new byte[(int)tarEntry.getSize()];
            byte[] btoRead = new byte[1024];
            //FileInputStream fin 
            //  = new FileInputStream(destPath.getCanonicalPath());
            BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath));
            int len = 0;

            while ((len = tarIn.read(btoRead)) != -1) {
                bout.write(btoRead, 0, len);
            }

            bout.close();
            btoRead = null;

        }
        tarEntry = tarIn.getNextTarEntry();
    }
    tarIn.close();
}

From source file:bb.io.TarUtil.java

/**
* Extracts the contents of tarFile to directoryExtraction.
* <p>//from  w w  w. ja  va2 s  .  c  om
* It is an error if tarFile does not exist, is not a normal file, or is not in the proper TAR format.
* In contrast, directoryExtraction need not exist, since it (and any parent directories) will be created if necessary.
* <p>
* Optional GZIP decompression may also be done.
* Normally, tarFile must be a path which ends in a ".tar" (case insensitive) extension.
* However, this method will also accept either ".tar.gz" or ".tgz" extensions,
* in which case it will perform GZIP decompression on tarFile as part of extracting.
* <p>
* @param tarFile the TAR archive file
* @param directoryExtraction the directory that will extract the contents of tarFile into
* @param overwrite specifies whether or not extraction is allowed to overwrite an existing normal file inside directoryExtraction
* @throws IllegalArgumentException if tarFile is {@link Check#validFile not valid};
* if directoryExtraction fails {@link DirUtil#ensureExists DirUtil.ensureExists};
* tarFile has an invalid extension
* @throws SecurityException if a security manager exists and its SecurityManager.checkRead method
* denies read access to tarFile or directoryExtraction
* @throws IllegalStateException if directoryExtraction failed to be created or is not an actual directory but is some other type of file
* @throws IOException if an I/O problem occurs
*/
public static void extract(File tarFile, File directoryExtraction, boolean overwrite)
        throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {
    Check.arg().validFile(tarFile);
    DirUtil.ensureExists(directoryExtraction);

    TarArchiveInputStream tais = null;
    try {
        tais = new TarArchiveInputStream(getInputStream(tarFile));

        for (TarArchiveEntry entry = (TarArchiveEntry) tais
                .getNextEntry(); entry != null; entry = (TarArchiveEntry) tais.getNextEntry()) {
            File path = new File(directoryExtraction, entry.getName());
            if (path.exists() && path.isFile() && !overwrite)
                throw new IllegalStateException(
                        path.getPath() + " is an existing normal file, but overwrite == false");

            if (entry.isDirectory()) {
                DirUtil.ensureExists(path);
            } else {
                DirUtil.ensureExists(path.getParentFile()); // CRITICAL: the TAR format does not necessarily store all the directories as entries, so must make sure that they are created    http://forum.java.sun.com/thread.jspa?threadID=573800&messageID=3115774
                writeOutFile(tais, path);
            }
        }
    } finally {
        StreamUtil.close(tais);
    }
}

From source file:gdt.jgui.entity.procedure.JProcedurePanel.java

/**
 * Restore the default procedure code./*w  w  w. j av a2 s . c  o m*/
 * @param console the main console.
 * @param entihome$ the database directory.
 */
public static void refreshListProcedure(JMainConsole console, String entihome$) {
    try {
        InputStream is = JProcedurePanel.class.getResourceAsStream("list.tar");
        TarArchiveInputStream tis = new TarArchiveInputStream(is);
        ArchiveHandler.extractEntitiesFromTar(entihome$, tis);
        Entigrator entigrator = console.getEntigrator(entihome$);
        Sack procedure = entigrator.getEntityAtKey(PROCEDURE_LIST_KEY);
        String procedureLocator$ = EntityHandler.getEntityLocator(entigrator, procedure);
        JEntityPrimaryMenu.reindexEntity(console, procedureLocator$);
    } catch (Exception e) {
        Logger.getLogger(JQueryPanel.class.getName()).severe(e.toString());
    }
}

From source file:com.spotify.docker.client.DefaultDockerClientTest.java

@Test
public void testExportContainer() throws Exception {
    // Pull image
    sut.pull(BUSYBOX_LATEST);/* ww  w  . jav a  2s.co m*/

    // Create container
    final ContainerConfig config = ContainerConfig.builder().image(BUSYBOX_LATEST).build();
    final String name = randomName();
    final ContainerCreation creation = sut.createContainer(config, name);
    final String id = creation.id();

    ImmutableSet.Builder<String> files = ImmutableSet.builder();
    try (TarArchiveInputStream tarStream = new TarArchiveInputStream(sut.exportContainer(id))) {
        TarArchiveEntry entry;
        while ((entry = tarStream.getNextTarEntry()) != null) {
            files.add(entry.getName());
        }
    }

    // Check that some common files exist
    assertThat(files.build(), both(hasItem("bin/")).and(hasItem("bin/sh")));
}

From source file:com.spotify.docker.client.DefaultDockerClientTest.java

@Test
public void testCopyContainer() throws Exception {
    // Pull image
    sut.pull(BUSYBOX_LATEST);/*from w  w  w  .j  a v a  2  s  .co m*/

    // Create container
    final ContainerConfig config = ContainerConfig.builder().image(BUSYBOX_LATEST).build();
    final String name = randomName();
    final ContainerCreation creation = sut.createContainer(config, name);
    final String id = creation.id();

    ImmutableSet.Builder<String> files = ImmutableSet.builder();
    try (TarArchiveInputStream tarStream = new TarArchiveInputStream(sut.copyContainer(id, "/bin"))) {
        TarArchiveEntry entry;
        while ((entry = tarStream.getNextTarEntry()) != null) {
            files.add(entry.getName());
        }
    }

    // Check that some common files exist
    assertThat(files.build(), both(hasItem("bin/")).and(hasItem("bin/wc")));
}

From source file:gdt.data.entity.ArchiveHandler.java

private static void extractEntitiesFromTar(String targetDirectory$, String tarfile$) {
    try {/*from  ww w  . j av  a2s.  co m*/
        //   System.out.println("ArchiveHandler:extractEntitiesFromTar.dir="+targetDirectory$);
        TarArchiveInputStream tis = new TarArchiveInputStream(new FileInputStream(new File(tarfile$)));
        extractEntitiesFromTar(targetDirectory$, tis);
    } catch (Exception e) {
        Logger.getLogger(ArchiveHandler.class.getName()).severe(e.toString());
    }
}

From source file:gdt.data.entity.ArchiveHandler.java

private static void extractEntitiesFromTgz(String targetDirectory$, String tgzfile$) {
    try {/*from w  w  w.  java  2 s.  com*/
        GZIPInputStream gis = new GZIPInputStream(new FileInputStream(new File(tgzfile$)));
        TarArchiveInputStream tis = new TarArchiveInputStream(gis);
        extractEntitiesFromTar(targetDirectory$, tis);
    } catch (Exception e) {
        Logger.getLogger(ArchiveHandler.class.getName()).severe(e.toString());
    }
}