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

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

Introduction

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

Prototype

public int read(byte b[]) throws IOException 

Source Link

Document

Reads some number of bytes from the input stream and stores them into the buffer array b.

Usage

From source file:com.foreignreader.util.WordNetExtractor.java

@Override
protected Void doInBackground(InputStream... streams) {
    assert streams.length == 1;

    try {/*from   ww  w  .  j  av  a2  s .c  o m*/

        BufferedInputStream in = new BufferedInputStream(streams[0]);
        GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);

        TarArchiveInputStream tar = new TarArchiveInputStream(gzIn);

        TarArchiveEntry tarEntry;

        File dest = LongTranslationHelper.getWordNetDict().getParentFile();

        while ((tarEntry = tar.getNextTarEntry()) != null) {
            File destPath = new File(dest, tarEntry.getName());
            if (tarEntry.isDirectory()) {
                destPath.mkdirs();
            } else {
                destPath.createNewFile();
                byte[] btoRead = new byte[1024 * 10];

                BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath));
                int len = 0;

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

                bout.close();

            }
        }

        tar.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:frameworks.Masken.java

public static void uncompressTarGZ(File tarFile, File dest) throws IOException {
    dest.mkdir();/*ww w.  j  av a 2 s  .  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:com.wenzani.maven.mongodb.TarUtils.java

private void unpackEntries(TarArchiveInputStream tis, TarArchiveEntry entry, File outputDir)
        throws IOException {
    if (entry.isDirectory()) {
        createDir(new File(outputDir, entry.getName()));
        File subDir = new File(outputDir, entry.getName());

        for (TarArchiveEntry e : entry.getDirectoryEntries()) {
            unpackEntries(tis, e, subDir);
        }/*from  w  w  w.ja  v  a2 s .co  m*/

        return;
    }

    File outputFile = new File(outputDir, entry.getName());

    if (!outputFile.getParentFile().exists()) {
        createDir(outputFile.getParentFile());
    }

    BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

    try {
        byte[] content = new byte[(int) entry.getSize()];

        tis.read(content);

        if (content.length > 0) {
            IOUtils.copy(new ByteArrayInputStream(content), outputStream);
        }
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
}

From source file:com.github.nethad.clustermeister.integration.JPPFTestNode.java

private void untar(File tarFile) throws IOException {
    logger.info("Untar {}.", tarFile.getAbsolutePath());
    TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(new FileInputStream(tarFile));
    try {//from   w w w. j  a  va 2s. c  o m
        ArchiveEntry tarEntry = tarArchiveInputStream.getNextEntry();
        while (tarEntry != null) {
            File destPath = new File(libDir, tarEntry.getName());
            logger.info("Unpacking {}.", destPath.getAbsoluteFile());
            if (!tarEntry.isDirectory()) {
                FileOutputStream fout = new FileOutputStream(destPath);
                final byte[] buffer = new byte[8192];
                int n = 0;
                while (-1 != (n = tarArchiveInputStream.read(buffer))) {
                    fout.write(buffer, 0, n);
                }
                fout.close();

            } else {
                destPath.mkdir();
            }
            tarEntry = tarArchiveInputStream.getNextEntry();
        }
    } finally {
        tarArchiveInputStream.close();
    }
}

From source file:com.renard.ocr.help.OCRLanguageInstallService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (!intent.hasExtra(DownloadManager.EXTRA_DOWNLOAD_ID)) {
        return;/*from  w  w w . j  a  v  a2s .c o  m*/
    }
    final long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
    if (downloadId != 0) {

        DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        ParcelFileDescriptor file;
        try {
            file = dm.openDownloadedFile(downloadId);
            FileInputStream fin = new FileInputStream(file.getFileDescriptor());
            BufferedInputStream in = new BufferedInputStream(fin);
            FileOutputStream out = openFileOutput("tess-lang.tmp", Context.MODE_PRIVATE);
            GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);
            final byte[] buffer = new byte[2048 * 2];
            int n = 0;
            while (-1 != (n = gzIn.read(buffer))) {
                out.write(buffer, 0, n);
            }
            out.close();
            gzIn.close();
            FileInputStream fileIn = openFileInput("tess-lang.tmp");
            TarArchiveInputStream tarIn = new TarArchiveInputStream(fileIn);

            TarArchiveEntry entry = tarIn.getNextTarEntry();

            while (entry != null && !(entry.getName().endsWith(".traineddata")
                    && !entry.getName().endsWith("_old.traineddata"))) {
                entry = tarIn.getNextTarEntry();
            }
            if (entry != null) {
                File tessDir = Util.getTrainingDataDir(this);
                final String langName = entry.getName().substring("tesseract-ocr/tessdata/".length());
                File trainedData = new File(tessDir, langName);
                FileOutputStream fout = new FileOutputStream(trainedData);
                int len;
                while ((len = tarIn.read(buffer)) != -1) {
                    fout.write(buffer, 0, len);
                }
                fout.close();
                String lang = langName.substring(0, langName.length() - ".traineddata".length());
                notifyReceivers(lang);
            }
            tarIn.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            String tessDir = Util.getTessDir(this);
            File targetFile = new File(tessDir, OCRLanguageActivity.DOWNLOADED_TRAINING_DATA);
            if (targetFile.exists()) {
                targetFile.delete();
            }
        }

    }
}

From source file:com.amaze.filemanager.filesystem.compressed.extractcontents.helpers.GzipExtractor.java

private void extractEntry(@NonNull final Context context, TarArchiveInputStream inputStream,
        TarArchiveEntry entry, String outputDir) throws IOException {

    File outputFile = new File(outputDir, fixEntryName(entry.getName()));
    if (!outputFile.getCanonicalPath().startsWith(outputDir)) {
        throw new IOException("Incorrect ZipEntry path!");
    }//w  w w. j a  v a2 s  .com

    if (entry.isDirectory()) {
        FileUtil.mkdir(outputFile, context);
        return;
    }

    if (!outputFile.getParentFile().exists()) {
        FileUtil.mkdir(outputFile.getParentFile(), context);
    }

    BufferedOutputStream outputStream = new BufferedOutputStream(FileUtil.getOutputStream(outputFile, context));
    try {
        int len;
        byte buf[] = new byte[GenericCopyUtil.DEFAULT_BUFFER_SIZE];
        while ((len = inputStream.read(buf)) != -1) {
            if (!listener.isCancelled()) {
                outputStream.write(buf, 0, len);
                ServiceWatcherUtil.position += len;
            } else
                break;
        }
    } finally {
        outputStream.close();
    }
}

From source file:heigit.ors.routing.graphhopper.extensions.reader.borders.CountryBordersReader.java

/**
 * Method to read the geometries from a GeoJSON file that represent the boundaries of different countries. Ideally
 * it should be written using many small objects split into hierarchies.
 *
 * If the file is a .tar.gz format, it will decompress it and then store the reulting data to be read into the
 * JSON object./*from   w ww  .ja  v  a  2s  .c om*/
 *
 * @return      A (Geo)JSON object representing the contents of the file
 */
private JSONObject readBordersData() throws IOException {
    String data = "";

    InputStream is = null;
    BufferedReader buf = null;
    try {
        is = new FileInputStream(BORDER_FILE);

        if (BORDER_FILE.endsWith(".tar.gz")) {
            // We are working with a compressed file
            TarArchiveInputStream tis = new TarArchiveInputStream(
                    new GzipCompressorInputStream(new BufferedInputStream(is)));

            TarArchiveEntry entry;
            StringBuilder sb = new StringBuilder();

            while ((entry = tis.getNextTarEntry()) != null) {
                if (!entry.isDirectory()) {
                    byte[] bytes = new byte[(int) entry.getSize()];
                    tis.read(bytes);
                    String str = new String(bytes);
                    sb.append(str);
                }
            }
            data = sb.toString();
        } else {
            // Assume a normal file so read line by line

            buf = new BufferedReader(new InputStreamReader(is));

            String line = "";
            StringBuilder sb = new StringBuilder();

            while ((line = buf.readLine()) != null) {
                sb.append(line);
            }

            data = sb.toString();
        }
    } catch (IOException ioe) {
        LOGGER.warn("Cannot access borders file!");
        throw ioe;
    } finally {
        try {
            if (is != null)
                is.close();
            if (buf != null)
                buf.close();
        } catch (IOException ioe) {
            LOGGER.warn("Error closing file reader buffers!");
        } catch (NullPointerException npe) {
            // This can happen if the file itself wasn't available
            throw new IOException("Borders file " + BORDER_FILE + " not found!");
        }
    }

    JSONObject json = new JSONObject(data);

    return json;
}

From source file:com.amaze.filemanager.filesystem.compressed.extractcontents.helpers.TarExtractor.java

private void extractEntry(@NonNull final Context context, TarArchiveInputStream inputStream,
        TarArchiveEntry entry, String outputDir) throws IOException {
    File outputFile = new File(outputDir, fixEntryName(entry.getName()));

    if (!outputFile.getCanonicalPath().startsWith(outputDir)) {
        throw new IOException("Incorrect TarArchiveEntry path!");
    }//from w  w  w .ja  v a2  s  . com

    if (entry.isDirectory()) {
        FileUtil.mkdir(outputFile, context);
        return;
    }

    if (!outputFile.getParentFile().exists()) {
        FileUtil.mkdir(outputFile.getParentFile(), context);
    }

    BufferedOutputStream outputStream = new BufferedOutputStream(FileUtil.getOutputStream(outputFile, context));
    try {
        int len;
        byte buf[] = new byte[GenericCopyUtil.DEFAULT_BUFFER_SIZE];
        while ((len = inputStream.read(buf)) != -1) {
            if (!listener.isCancelled()) {
                outputStream.write(buf, 0, len);
                ServiceWatcherUtil.position += len;
            } else
                break;
        }
    } finally {
        outputStream.close();
    }
}

From source file:io.wcm.maven.plugins.nodejs.installation.TarUnArchiver.java

/**
 * Unarchives the arvive into the pBaseDir
 * @param baseDir/* w w w. j  a  v a  2s .  c  om*/
 * @throws MojoExecutionException
 */
public void unarchive(String baseDir) throws MojoExecutionException {
    try {
        FileInputStream fis = new FileInputStream(archive);

        // TarArchiveInputStream can be constructed with a normal FileInputStream if
        // we ever need to extract regular '.tar' files.
        final TarArchiveInputStream tarIn = new TarArchiveInputStream(new GzipCompressorInputStream(fis));

        TarArchiveEntry tarEntry = tarIn.getNextTarEntry();
        while (tarEntry != null) {
            // Create a file for this tarEntry
            final File destPath = new File(baseDir + File.separator + tarEntry.getName());
            if (tarEntry.isDirectory()) {
                destPath.mkdirs();
            } else {
                destPath.createNewFile();
                destPath.setExecutable(true);
                //byte [] btoRead = new byte[(int)tarEntry.getSize()];
                byte[] btoRead = new byte[8024];
                final BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath));
                int len = 0;

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

                bout.close();
            }
            tarEntry = tarIn.getNextTarEntry();
        }
        tarIn.close();
    } catch (IOException e) {
        throw new MojoExecutionException("Could not extract archive: '" + archive.getAbsolutePath() + "'", e);
    }

}

From source file:air.AirRuntimeGenerator.java

protected void processFlashRuntime(File sdkSourceDirectory, File sdkTargetDirectory) throws Exception {
    final File runtimeDirectory = new File(sdkSourceDirectory, "runtimes");
    final File flashPlayerDirectory = new File(runtimeDirectory, "player");

    File[] versions = flashPlayerDirectory.listFiles(new FileFilter() {
        public boolean accept(File pathname) {
            return pathname.isDirectory() && !"win".equalsIgnoreCase(pathname.getName())
                    && !"lnx".equalsIgnoreCase(pathname.getName())
                    && !"mac".equalsIgnoreCase(pathname.getName());
        }/*from  www . jav a 2s  .co m*/
    });
    // The flash-player 9 is installed directly in the player directory.
    if (new File(flashPlayerDirectory, "win").exists()) {
        final File[] extendedVersions = new File[versions.length + 1];
        System.arraycopy(versions, 0, extendedVersions, 0, versions.length);
        extendedVersions[versions.length] = flashPlayerDirectory;
        versions = extendedVersions;
    }

    if (versions != null) {
        for (final File versionDir : versions) {
            // If the versionDir is called "player", then this is the home of the flash-player version 9.
            final String playerVersionString = "player".equalsIgnoreCase(versionDir.getName()) ? "9.0"
                    : versionDir.getName();
            final double playerVersion = Double.valueOf(playerVersionString);
            final NumberFormat doubleFormat = NumberFormat.getInstance(Locale.US);
            doubleFormat.setMinimumFractionDigits(1);
            doubleFormat.setMaximumFractionDigits(1);
            final String version = doubleFormat.format(playerVersion);

            final File targetDir = new File(sdkTargetDirectory, "com/adobe/flash/runtime/" + version);

            // Deploy Windows binaries.
            final File windowsDirectory = new File(versionDir, "win");
            if (windowsDirectory.exists()) {
                // Find out if a flash-player binary exists.
                File flashPlayerBinary = null;
                if (new File(windowsDirectory, "FlashPlayerDebugger.exe").exists()) {
                    flashPlayerBinary = new File(windowsDirectory, "FlashPlayerDebugger.exe");
                } else if (new File(windowsDirectory, "FlashPlayer.exe").exists()) {
                    flashPlayerBinary = new File(windowsDirectory, "FlashPlayer.exe");
                }

                // If a binary exists, copy it to the target and create a pom for it.
                if (flashPlayerBinary != null) {
                    if (!targetDir.exists()) {
                        if (!targetDir.mkdirs()) {
                            throw new RuntimeException(
                                    "Could not create directory: " + targetDir.getAbsolutePath());
                        }
                    }
                    final File targetFile = new File(targetDir, "/runtime-" + version + "-win.exe");
                    copyFile(flashPlayerBinary, targetFile);
                }
            }

            // Deploy Mac binaries.
            final File macDirectory = new File(versionDir, "mac");
            if (macDirectory.exists()) {
                // Find out if a flash-player binary exists.
                File flashPlayerBinary = null;
                if (new File(macDirectory, "Flash Player.app.zip").exists()) {
                    flashPlayerBinary = new File(macDirectory, "Flash Player.app.zip");
                } else if (new File(macDirectory, "Flash Player Debugger.app.zip").exists()) {
                    flashPlayerBinary = new File(macDirectory, "Flash Player Debugger.app.zip");
                }

                // If a binary exists, copy it to the target and create a pom for it.
                if (flashPlayerBinary != null) {
                    if (!targetDir.exists()) {
                        if (!targetDir.mkdirs()) {
                            throw new RuntimeException(
                                    "Could not create directory: " + targetDir.getAbsolutePath());
                        }
                    }
                    final File targetFile = new File(targetDir, "/runtime-" + version + "-mac.zip");
                    copyFile(flashPlayerBinary, targetFile);
                }
            }

            // Deploy Linux binaries.
            final File lnxDirectory = new File(versionDir, "lnx");
            if (lnxDirectory.exists()) {
                // Find out if a flash-player binary exists.
                File flashPlayerBinary = null;
                if (new File(lnxDirectory, "flashplayer.tar.gz").exists()) {
                    flashPlayerBinary = new File(lnxDirectory, "flashplayer.tar.gz");
                } else if (new File(lnxDirectory, "flashplayerdebugger.tar.gz").exists()) {
                    flashPlayerBinary = new File(lnxDirectory, "flashplayerdebugger.tar.gz");
                }

                // Decompress the archive.
                // First unzip it.
                final FileInputStream fin = new FileInputStream(flashPlayerBinary);
                final BufferedInputStream in = new BufferedInputStream(fin);
                final File tempTarFile = File.createTempFile("flex-sdk-linux-flashplayer-binary-" + version,
                        ".tar");
                final FileOutputStream out = new FileOutputStream(tempTarFile);
                final GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);
                final byte[] buffer = new byte[1024];
                int n;
                while (-1 != (n = gzIn.read(buffer))) {
                    out.write(buffer, 0, n);
                }
                out.close();
                gzIn.close();

                // Then untar it.
                File uncompressedBinary = null;
                final FileInputStream tarFileInputStream = new FileInputStream(tempTarFile);
                final TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(
                        tarFileInputStream);
                ArchiveEntry entry;
                while ((entry = tarArchiveInputStream.getNextEntry()) != null) {
                    if ("flashplayer".equals(entry.getName())) {
                        uncompressedBinary = File.createTempFile("flex-sdk-linux-flashplayer-binary-" + version,
                                ".uexe");
                        final FileOutputStream uncompressedBinaryOutputStream = new FileOutputStream(
                                uncompressedBinary);
                        while (-1 != (n = tarArchiveInputStream.read(buffer))) {
                            uncompressedBinaryOutputStream.write(buffer, 0, n);
                        }
                        uncompressedBinaryOutputStream.close();
                    } else if ("flashplayerdebugger".equals(entry.getName())) {
                        uncompressedBinary = File.createTempFile("flex-sdk-linux-flashplayer-binary-" + version,
                                ".uexe");
                        final FileOutputStream uncompressedBinaryOutputStream = new FileOutputStream(
                                uncompressedBinary);
                        while (-1 != (n = tarArchiveInputStream.read(buffer))) {
                            uncompressedBinaryOutputStream.write(buffer, 0, n);
                        }
                        uncompressedBinaryOutputStream.close();
                    }
                }
                tarFileInputStream.close();

                // If a binary exists, copy it to the target and create a pom for it.
                if (uncompressedBinary != null) {
                    if (!targetDir.exists()) {
                        if (!targetDir.mkdirs()) {
                            throw new RuntimeException(
                                    "Could not create directory: " + targetDir.getAbsolutePath());
                        }
                    }
                    final File targetFile = new File(targetDir, "/runtime-" + version + "-linux.uexe");
                    copyFile(uncompressedBinary, targetFile);

                    // Clean up in the temp directory.
                    if (!uncompressedBinary.delete()) {
                        System.out.println("Could not delete: " + uncompressedBinary.getAbsolutePath());
                    }
                }

                // Clean up in the temp directory.
                if (!tempTarFile.delete()) {
                    System.out.println("Could not delete: " + tempTarFile.getAbsolutePath());
                }
            }

            final MavenMetadata playerArtifact = new MavenMetadata();
            playerArtifact.setGroupId("com.adobe.flash");
            playerArtifact.setArtifactId("runtime");
            playerArtifact.setVersion(version);
            playerArtifact.setPackaging("exe");

            writeDocument(createPomDocument(playerArtifact),
                    new File(targetDir, "runtime-" + version + ".pom"));
        }
    }
}