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

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

Introduction

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

Prototype

public TarArchiveEntry getNextTarEntry() throws IOException 

Source Link

Document

Get the next entry in this tar archive.

Usage

From source file:org.soulwing.credo.service.archive.TarGzipArchiveBuilderTest.java

@Test
public void testBuildArchiveWithMultipleEntries() throws Exception {
    byte[] archive = builder.beginEntry("file1.txt", "UTF-8").addContent(new StringReader("content1"))
            .endEntry().beginEntry("file2.txt", "UTF-8").addContent(new StringReader("content2")).endEntry()
            .build();/*from w w  w  . ja v  a 2s  .  co m*/
    TarArchiveInputStream tis = new TarArchiveInputStream(
            new GzipCompressorInputStream(new ByteArrayInputStream(archive)));
    TarArchiveEntry entry = tis.getNextTarEntry();
    assertThat(entry.getName(), is(equalTo("file1.txt")));
    assertThat(readContent(tis), is(equalTo("content1")));
    entry = tis.getNextTarEntry();
    assertThat(entry.getName(), is(equalTo("file2.txt")));
    assertThat(readContent(tis), is(equalTo("content2")));
    assertThat(tis.getNextEntry(), is(nullValue()));
}

From source file:org.soulwing.credo.service.archive.TarGzipArchiveBuilderTest.java

@Test
public void testBuildArchiveEntryWithMultipleContent() throws Exception {
    byte[] archive = builder.beginEntry("file.txt", "UTF-8").addContent(new StringReader("content1"))
            .addContent(new StringReader("content2")).endEntry().build();
    TarArchiveInputStream tis = new TarArchiveInputStream(
            new GzipCompressorInputStream(new ByteArrayInputStream(archive)));
    TarArchiveEntry entry = tis.getNextTarEntry();
    assertThat(entry.getName(), is(equalTo("file.txt")));
    assertThat(readContent(tis), is(equalTo("content1content2")));
    assertThat(tis.getNextEntry(), is(nullValue()));
}

From source file:org.torproject.collector.bridgedescs.BridgeSnapshotReader.java

/**
 * Reads the half-hourly snapshots of bridge descriptors from Bifroest.
 *///from   ww  w  .  ja  v a 2 s. co m
public BridgeSnapshotReader(BridgeDescriptorParser bdp, File bridgeDirectoriesDir, File statsDirectory)
        throws ConfigurationException {

    if (bdp == null || bridgeDirectoriesDir == null || statsDirectory == null) {
        throw new IllegalArgumentException();
    }

    SortedSet<String> parsed = new TreeSet<String>();
    File bdDir = bridgeDirectoriesDir;
    File pbdFile = new File(statsDirectory, "parsed-bridge-directories");
    boolean modified = false;
    if (bdDir.exists()) {
        if (pbdFile.exists()) {
            logger.debug("Reading file " + pbdFile.getAbsolutePath() + "...");
            try {
                BufferedReader br = new BufferedReader(new FileReader(pbdFile));
                String line = null;
                while ((line = br.readLine()) != null) {
                    parsed.add(line);
                }
                br.close();
                logger.debug("Finished reading file " + pbdFile.getAbsolutePath() + ".");
            } catch (IOException e) {
                logger.warn("Failed reading file " + pbdFile.getAbsolutePath() + "!", e);
                return;
            }
        }
        logger.debug("Importing files in directory " + bridgeDirectoriesDir + "/...");
        Set<String> descriptorImportHistory = new HashSet<String>();
        int parsedFiles = 0;
        int skippedFiles = 0;
        int parsedStatuses = 0;
        int parsedServerDescriptors = 0;
        int skippedServerDescriptors = 0;
        int parsedExtraInfoDescriptors = 0;
        int skippedExtraInfoDescriptors = 0;
        Stack<File> filesInInputDir = new Stack<File>();
        filesInInputDir.add(bdDir);
        while (!filesInInputDir.isEmpty()) {
            File pop = filesInInputDir.pop();
            if (pop.isDirectory()) {
                for (File f : pop.listFiles()) {
                    filesInInputDir.add(f);
                }
            } else if (!parsed.contains(pop.getName())) {
                try {
                    FileInputStream in = new FileInputStream(pop);
                    if (in.available() > 0) {
                        TarArchiveInputStream tais = null;
                        if (pop.getName().endsWith(".tar.gz")) {
                            GzipCompressorInputStream gcis = new GzipCompressorInputStream(in);
                            tais = new TarArchiveInputStream(gcis);
                        } else if (pop.getName().endsWith(".tar")) {
                            tais = new TarArchiveInputStream(in);
                        } else {
                            continue;
                        }
                        BufferedInputStream bis = new BufferedInputStream(tais);
                        String fn = pop.getName();
                        String[] fnParts = fn.split("-");
                        if (fnParts.length != 5) {
                            logger.warn("Invalid bridge descriptor tarball file name: " + fn + ".  Skipping.");
                            continue;
                        }
                        String authorityPart = String.format("%s-%s-", fnParts[0], fnParts[1]);
                        String datePart = String.format("%s-%s-%s", fnParts[2], fnParts[3], fnParts[4]);
                        String authorityFingerprint;
                        switch (authorityPart) {
                        case "from-tonga-":
                            authorityFingerprint = "4A0CCD2DDC7995083D73F5D667100C8A5831F16D";
                            break;
                        case "from-bifroest-":
                            authorityFingerprint = "1D8F3A91C37C5D1C4C19B1AD1D0CFBE8BF72D8E1";
                            break;
                        default:
                            logger.warn("Did not recognize the bridge authority that " + "generated " + fn
                                    + ".  Skipping.");
                            continue;
                        }
                        String dateTime = datePart.substring(0, 10) + " " + datePart.substring(11, 13) + ":"
                                + datePart.substring(13, 15) + ":" + datePart.substring(15, 17);
                        while ((tais.getNextTarEntry()) != null) {
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            int len;
                            byte[] data = new byte[1024];
                            while ((len = bis.read(data, 0, 1024)) >= 0) {
                                baos.write(data, 0, len);
                            }
                            byte[] allData = baos.toByteArray();
                            if (allData.length == 0) {
                                continue;
                            }
                            String fileDigest = Hex.encodeHexString(DigestUtils.sha(allData));
                            String ascii = new String(allData, "US-ASCII");
                            BufferedReader br3 = new BufferedReader(new StringReader(ascii));
                            String firstLine = null;
                            while ((firstLine = br3.readLine()) != null) {
                                if (firstLine.startsWith("@")) {
                                    continue;
                                } else {
                                    break;
                                }
                            }
                            if (firstLine == null) {
                                continue;
                            }
                            if (firstLine.startsWith("published ") || firstLine.startsWith("flag-thresholds ")
                                    || firstLine.startsWith("r ")) {
                                bdp.parse(allData, dateTime, authorityFingerprint);
                                parsedStatuses++;
                            } else if (descriptorImportHistory.contains(fileDigest)) {
                                /* Skip server descriptors or extra-info descriptors if
                                 * we parsed them before. */
                                skippedFiles++;
                                continue;
                            } else {
                                int start = -1;
                                int sig = -1;
                                int end = -1;
                                String startToken = firstLine.startsWith("router ") ? "router " : "extra-info ";
                                String sigToken = "\nrouter-signature\n";
                                String endToken = "\n-----END SIGNATURE-----\n";
                                while (end < ascii.length()) {
                                    start = ascii.indexOf(startToken, end);
                                    if (start < 0) {
                                        break;
                                    }
                                    sig = ascii.indexOf(sigToken, start);
                                    if (sig < 0) {
                                        break;
                                    }
                                    sig += sigToken.length();
                                    end = ascii.indexOf(endToken, sig);
                                    if (end < 0) {
                                        break;
                                    }
                                    end += endToken.length();
                                    byte[] descBytes = new byte[end - start];
                                    System.arraycopy(allData, start, descBytes, 0, end - start);
                                    String descriptorDigest = Hex.encodeHexString(DigestUtils.sha(descBytes));
                                    if (!descriptorImportHistory.contains(descriptorDigest)) {
                                        bdp.parse(descBytes, dateTime, authorityFingerprint);
                                        descriptorImportHistory.add(descriptorDigest);
                                        if (firstLine.startsWith("router ")) {
                                            parsedServerDescriptors++;
                                        } else {
                                            parsedExtraInfoDescriptors++;
                                        }
                                    } else {
                                        if (firstLine.startsWith("router ")) {
                                            skippedServerDescriptors++;
                                        } else {
                                            skippedExtraInfoDescriptors++;
                                        }
                                    }
                                }
                            }
                            descriptorImportHistory.add(fileDigest);
                            parsedFiles++;
                        }
                        bis.close();
                    }
                    in.close();

                    /* Let's give some memory back, or we'll run out of it. */
                    System.gc();

                    parsed.add(pop.getName());
                    modified = true;
                } catch (IOException e) {
                    logger.warn("Could not parse bridge snapshot " + pop.getName() + "!", e);
                    continue;
                }
            }
        }
        logger.debug("Finished importing files in directory " + bridgeDirectoriesDir
                + "/.  In total, we parsed " + parsedFiles + " files (skipped " + skippedFiles + ") containing "
                + parsedStatuses + " statuses, " + parsedServerDescriptors + " server descriptors (skipped "
                + skippedServerDescriptors + "), and " + parsedExtraInfoDescriptors + " extra-info descriptors "
                + "(skipped " + skippedExtraInfoDescriptors + ").");
        if (!parsed.isEmpty() && modified) {
            logger.debug("Writing file " + pbdFile.getAbsolutePath() + "...");
            pbdFile.getParentFile().mkdirs();
            try (BufferedWriter bw = new BufferedWriter(new FileWriter(pbdFile))) {
                for (String f : parsed) {
                    bw.append(f + "\n");
                }
                logger.debug("Finished writing file " + pbdFile.getAbsolutePath() + ".");
            } catch (IOException e) {
                logger.warn("Failed writing file " + pbdFile.getAbsolutePath() + "!", e);
            }
        }
    }
}

From source file:org.torproject.ernie.db.BridgeSnapshotReader.java

public BridgeSnapshotReader(BridgeDescriptorParser bdp, String bridgeDirectoriesDir) {
    Logger logger = Logger.getLogger(BridgeSnapshotReader.class.getName());
    SortedSet<String> parsed = new TreeSet<String>();
    File bdDir = new File(bridgeDirectoriesDir);
    File pbdFile = new File("stats/parsed-bridge-directories");
    boolean modified = false;
    if (bdDir.exists()) {
        if (pbdFile.exists()) {
            logger.fine("Reading file " + pbdFile.getAbsolutePath() + "...");
            try {
                BufferedReader br = new BufferedReader(new FileReader(pbdFile));
                String line = null;
                while ((line = br.readLine()) != null) {
                    parsed.add(line);//from   w  w w  . j a v  a2 s  .c o m
                }
                br.close();
                logger.fine("Finished reading file " + pbdFile.getAbsolutePath() + ".");
            } catch (IOException e) {
                logger.log(Level.WARNING, "Failed reading file " + pbdFile.getAbsolutePath() + "!", e);
                return;
            }
        }
        logger.fine("Importing files in directory " + bridgeDirectoriesDir + "/...");
        Stack<File> filesInInputDir = new Stack<File>();
        filesInInputDir.add(bdDir);
        while (!filesInInputDir.isEmpty()) {
            File pop = filesInInputDir.pop();
            if (pop.isDirectory()) {
                for (File f : pop.listFiles()) {
                    filesInInputDir.add(f);
                }
            } else if (!parsed.contains(pop.getName())) {
                try {
                    FileInputStream in = new FileInputStream(pop);
                    if (in.available() > 0) {
                        GzipCompressorInputStream gcis = new GzipCompressorInputStream(in);
                        TarArchiveInputStream tais = new TarArchiveInputStream(gcis);
                        BufferedInputStream bis = new BufferedInputStream(tais);
                        String fn = pop.getName();
                        String dateTime = fn.substring(11, 21) + " " + fn.substring(22, 24) + ":"
                                + fn.substring(24, 26) + ":" + fn.substring(26, 28);
                        while ((tais.getNextTarEntry()) != null) {
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            int len;
                            byte[] data = new byte[1024];
                            while ((len = bis.read(data, 0, 1024)) >= 0) {
                                baos.write(data, 0, len);
                            }
                            byte[] allData = baos.toByteArray();
                            if (allData.length == 0) {
                                continue;
                            }
                            String ascii = new String(allData, "US-ASCII");
                            BufferedReader br3 = new BufferedReader(new StringReader(ascii));
                            String firstLine = null;
                            while ((firstLine = br3.readLine()) != null) {
                                if (firstLine.startsWith("@")) {
                                    continue;
                                } else {
                                    break;
                                }
                            }
                            if (firstLine.startsWith("r ")) {
                                bdp.parse(allData, dateTime, false);
                            } else {
                                int start = -1, sig = -1, end = -1;
                                String startToken = firstLine.startsWith("router ") ? "router " : "extra-info ";
                                String sigToken = "\nrouter-signature\n";
                                String endToken = "\n-----END SIGNATURE-----\n";
                                while (end < ascii.length()) {
                                    start = ascii.indexOf(startToken, end);
                                    if (start < 0) {
                                        break;
                                    }
                                    sig = ascii.indexOf(sigToken, start);
                                    if (sig < 0) {
                                        break;
                                    }
                                    sig += sigToken.length();
                                    end = ascii.indexOf(endToken, sig);
                                    if (end < 0) {
                                        break;
                                    }
                                    end += endToken.length();
                                    byte[] descBytes = new byte[end - start];
                                    System.arraycopy(allData, start, descBytes, 0, end - start);
                                    bdp.parse(descBytes, dateTime, false);
                                }
                            }
                        }
                    }
                    in.close();

                    /* Let's give some memory back, or we'll run out of it. */
                    System.gc();

                    parsed.add(pop.getName());
                    modified = true;
                } catch (IOException e) {
                    logger.log(Level.WARNING, "Could not parse bridge snapshot " + pop.getName() + "!", e);
                    continue;
                }
            }
        }
        logger.fine("Finished importing files in directory " + bridgeDirectoriesDir + "/.");
        if (!parsed.isEmpty() && modified) {
            logger.fine("Writing file " + pbdFile.getAbsolutePath() + "...");
            try {
                pbdFile.getParentFile().mkdirs();
                BufferedWriter bw = new BufferedWriter(new FileWriter(pbdFile));
                for (String f : parsed) {
                    bw.append(f + "\n");
                }
                bw.close();
                logger.fine("Finished writing file " + pbdFile.getAbsolutePath() + ".");
            } catch (IOException e) {
                logger.log(Level.WARNING, "Failed writing file " + pbdFile.getAbsolutePath() + "!", e);
            }
        }
    }
}

From source file:org.vafer.jdeb.DataBuilderTestCase.java

public void testCreateParentDirectories() throws Exception {
    File archive = new File("target/data.tar");
    if (archive.exists()) {
        archive.delete();/*from  w  w  w  .ja  v  a  2s  . c o m*/
    }

    DataBuilder builder = new DataBuilder(new NullConsole());

    DataProducer producer = new DataProducerFile(new File("pom.xml"), "/usr/share/myapp/pom.xml", null, null,
            null);

    builder.buildData(Arrays.asList(producer), archive, new StringBuilder(), Compression.NONE);

    int count = 0;
    TarArchiveInputStream in = null;
    try {
        in = new TarArchiveInputStream(new FileInputStream(archive));
        while (in.getNextTarEntry() != null) {
            count++;
        }
    } finally {
        if (in != null) {
            in.close();
        }
    }

    assertEquals("entries", 4, count);
}

From source file:org.waarp.common.tar.TarUtility.java

/**
 * Extract all files from Tar into the specified directory
 * //from  w  ww.j ava2s  .c o m
 * @param tarFile
 * @param directory
 * @return the list of extracted filenames
 * @throws IOException
 */
public static List<String> unTar(File tarFile, File directory) throws IOException {
    List<String> result = new ArrayList<String>();
    InputStream inputStream = new FileInputStream(tarFile);
    TarArchiveInputStream in = new TarArchiveInputStream(inputStream);
    TarArchiveEntry entry = in.getNextTarEntry();
    while (entry != null) {
        if (entry.isDirectory()) {
            entry = in.getNextTarEntry();
            continue;
        }
        File curfile = new File(directory, entry.getName());
        File parent = curfile.getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();
        }
        OutputStream out = new FileOutputStream(curfile);
        IOUtils.copy(in, out);
        out.close();
        result.add(entry.getName());
        entry = in.getNextTarEntry();
    }
    in.close();
    return result;
}

From source file:org.whitesource.docker.DockerAgent.java

/**
 * Extract matching files from the tar archive.
 *///from  ww w.j av  a 2s. c  o m
public void extractTarArchive(File containerTarFile, File containerTarExtractDir) {
    TarArchiveInputStream tais = null;
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(containerTarFile);
        tais = new TarArchiveInputStream(fis);
        ArchiveEntry entry = tais.getNextEntry();
        while (entry != null) {
            if (!entry.isDirectory()) {
                String entryName = entry.getName();
                String lowerCaseName = entryName.toLowerCase();
                if (lowerCaseName.matches(SOURCE_FILE_PATTERN) || lowerCaseName.matches(BINARY_FILE_PATTERN)
                        || lowerCaseName.matches(ARCHIVE_FILE_PATTERN)) {
                    File file = new File(containerTarExtractDir, entryName);
                    File parent = file.getParentFile();
                    if (!parent.exists()) {
                        parent.mkdirs();
                    }
                    OutputStream out = new FileOutputStream(file);
                    IOUtils.copy(tais, out);
                    out.close();
                }
            }
            entry = tais.getNextTarEntry();
        }
    } catch (FileNotFoundException e) {
        logger.warn("Error extracting files from {}: {}", containerTarFile.getPath(), e.getMessage());
    } catch (IOException e) {
        logger.warn("Error extracting files from {}: {}", containerTarFile.getPath(), e.getMessage());
    } finally {
        IOUtils.closeQuietly(tais);
        IOUtils.closeQuietly(fis);
    }
}

From source file:org.xenmaster.setup.debian.Bootstrapper.java

protected boolean downloadNetbootFiles() {
    if (System.currentTimeMillis() - lastChecked < 50 * 60 * 1000) {
        return false;
    }/*from www  .j  a  v  a  2s  .  c o m*/

    File localVersionFile = new File(Settings.getInstance().getString("StorePath") + "/netboot/version");
    int localVersion = -1;
    try (FileInputStream fis = new FileInputStream(localVersionFile)) {
        localVersion = Integer.parseInt(IOUtils.toString(fis));
    } catch (IOException | NumberFormatException ex) {
        Logger.getLogger(getClass()).error("Failed to retrieve local version file", ex);
    }

    int remoteVersion = -1;
    try {
        remoteVersion = Integer.parseInt(IOUtils.toString(XenMasterSite.getFileAsStream("/netboot/version")));
    } catch (IOException | NumberFormatException ex) {
        Logger.getLogger(getClass()).error("Failed to retrieve remote version file", ex);
    }

    lastChecked = System.currentTimeMillis();

    if (localVersion < remoteVersion) {
        Logger.getLogger(getClass())
                .info("New version " + remoteVersion + " found. Please hold while downloading netboot data");
        try {
            TarArchiveInputStream tais = new TarArchiveInputStream(
                    new GZIPInputStream(XenMasterSite.getFileAsStream("/netboot/netboot.tar.gz")));
            TarArchiveEntry tae = null;
            FileOutputStream fos = null;
            while ((tae = tais.getNextTarEntry()) != null) {
                if (tais.canReadEntryData(tae)) {
                    String target = Settings.getInstance().getString("StorePath") + "/" + tae.getName();

                    if (tae.isSymbolicLink()) {
                        Path targetFile = FileSystems.getDefault().getPath(tae.getLinkName());
                        Path linkName = FileSystems.getDefault().getPath(target);

                        // Link might already have been written as null file
                        if (targetFile.toFile().exists()) {
                            targetFile.toFile().delete();
                        }

                        Files.createSymbolicLink(linkName, targetFile);
                        Logger.getLogger(getClass()).info(
                                "Created sym link " + linkName.toString() + " -> " + targetFile.toString());
                    } else if (tae.isDirectory()) {
                        new File(target).mkdir();

                        Logger.getLogger(getClass()).info("Created dir " + target);
                    } else if (tae.isFile()) {
                        fos = new FileOutputStream(target);
                        byte[] b = new byte[1024];
                        int curPos = 0;
                        while (tais.available() > 0) {
                            tais.read(b, curPos, 1024);
                            fos.write(b, curPos, 1024);
                        }

                        fos.flush();
                        fos.close();

                        Logger.getLogger(getClass()).info("Wrote file " + target);
                    }
                }
            }

            tais.close();
            // Write local version
            IOUtils.write("" + remoteVersion, new FileOutputStream(localVersionFile));
        } catch (IOException ex) {
            Logger.getLogger(getClass()).error("Failed to download netboot files", ex);
        }
    } else {
        return false;
    }

    return true;
}

From source file:plptool.gui.ProjectDriver.java

/**
 * Open plp file specified by path.//w  w w  . j a va2s . c o m
 *
 * @param path Path to project file to load.
 * @param assemble Attempt to assemble after opening (if dirty is not set)
 * @return PLP_OK on successful operation, error code otherwise
 */
public int open(String path, boolean assemble) {
    File plpFile = new File(path);
    CallbackRegistry.callback(CallbackRegistry.PROJECT_OPEN, plpFile);

    if (!plpFile.exists())
        return Msg.E("open(" + path + "): File not found.", Constants.PLP_BACKEND_PLP_OPEN_ERROR, null);

    boolean metafileFound = false;
    dirty = true;

    Msg.I("Opening " + path, null);

    if (arch != null) {
        arch.cleanup();
        arch = null;
    }
    asm = null;
    asms = new ArrayList<PLPAsmSource>();
    smods = null;
    watcher = null;
    pAttrSet = new HashMap<String, Object>();
    HashMap<String, Integer> asmFileOrder = new HashMap<String, Integer>();

    try {

        TarArchiveInputStream tIn = new TarArchiveInputStream(new FileInputStream(plpFile));
        TarArchiveEntry entry;
        byte[] image;
        String metaStr;

        // Find meta file first
        while ((entry = tIn.getNextTarEntry()) != null) {
            if (entry.getName().equals("plp.metafile")) {
                image = new byte[(int) entry.getSize()];
                tIn.read(image, 0, (int) entry.getSize());
                metaStr = new String(image);

                metafileFound = true;
                meta = metaStr;
                Scanner metaScanner;

                String lines[] = meta.split("\\r?\\n");
                if (lines[0].equals(Text.projectFileVersionString)) {

                } else {
                    Msg.W("This is not a " + Text.projectFileVersionString + " project file. Opening anyways.",
                            this);
                }

                metaScanner = new Scanner(meta);
                metaScanner.findWithinHorizon("DIRTY=", 0);
                if (metaScanner.nextInt() == 0)
                    dirty = false;
                if (metaScanner.findWithinHorizon("ARCH=", 0) != null) {
                    String temp = metaScanner.nextLine();
                    if (Config.cfgOverrideISA >= 0) { // ISA ID override, ignore the metafile
                        arch = ArchRegistry.getArchitecture(this, Config.cfgOverrideISA);
                        arch.init();
                    } else if (temp.equals("plpmips")) {
                        Msg.W("This project file was created by PLPTool version 3 or earlier. "
                                + "Meta data for this project will be updated "
                                + "with the default ISA (plpmips) when the project " + "file is saved.", this);
                        arch = ArchRegistry.getArchitecture(this, ArchRegistry.ISA_PLPMIPS);
                        arch.init();
                    } else {
                        arch = ArchRegistry.getArchitecture(this, Integer.parseInt(temp));
                        if (arch == null) {
                            Msg.W("Invalid ISA ID is specified in the project file: '" + temp
                                    + "'. Assuming PLPCPU.", this);
                            arch = ArchRegistry.getArchitecture(this, ArchRegistry.ISA_PLPMIPS);
                        }
                        arch.init();
                    }
                    arch.hook(this);
                }

                // get asm files order
                int asmOrder = 0;
                while (metaScanner.hasNext()) {
                    String asmName = metaScanner.nextLine();
                    if (asmName.endsWith(".asm")) {
                        asmFileOrder.put(asmName, new Integer(asmOrder));
                        asmOrder++;
                        asms.add(null);
                    }
                }
            }
        }

        if (!metafileFound)
            return Msg.E("No PLP metadata found.", Constants.PLP_BACKEND_INVALID_PLP_FILE, this);

        // reset the tar input stream
        tIn = new TarArchiveInputStream(new FileInputStream(plpFile));

        while ((entry = tIn.getNextTarEntry()) != null) {
            boolean handled = false;
            image = new byte[(int) entry.getSize()];
            tIn.read(image, 0, (int) entry.getSize());
            metaStr = new String(image);

            // Hook for project open for each entry
            Object[] eParams = { entry.getName(), image, plpFile };
            handled = CallbackRegistry.callback(CallbackRegistry.PROJECT_OPEN_ENTRY, eParams) || handled;

            if (entry.getName().endsWith("asm") && !entry.getName().startsWith("plp.")) {
                Integer order = (Integer) asmFileOrder.get(entry.getName());
                if (order == null)
                    Msg.W("The file '" + entry.getName() + "' is not listed in "
                            + "the meta file. This file will be removed when the project " + "is saved.", this);
                else {
                    asms.set(order, new PLPAsmSource(metaStr, entry.getName(), order));
                }

            } else if (entry.getName().equals("plp.metafile")) {
                // we've done reading the metafile

            } else if (entry.getName().equals("plp.image")) {
                binimage = new byte[(int) entry.getSize()];
                binimage = image;

            } else if (entry.getName().equals("plp.hex")) {
                hexstring = new String(image);

                // Restore bus modules states
            } else if (entry.getName().equals("plp.simconfig")) {
                Msg.D("simconfig:\n" + metaStr + "\n", 4, this);
                String lines[] = metaStr.split("\\r?\\n");
                int i;

                for (i = 0; i < lines.length; i++) {
                    String tokens[] = lines[i].split("::");

                    if (lines[i].startsWith("simRunnerDelay")) {
                        Config.simRunnerDelay = Integer.parseInt(tokens[1]);
                    }

                    if (lines[i].equals("MODS")) {
                        i++;
                        this.smods = new Preset();

                        while (i < lines.length && !lines[i].equals("END")) {
                            tokens = lines[i].split("::");
                            if (tokens.length > 4 && tokens[4].equals("noframe"))
                                smods.addModuleDefinition(Integer.parseInt(tokens[0]),
                                        Long.parseLong(tokens[2]), Long.parseLong(tokens[3]), false, false);
                            else if (tokens.length > 4)
                                smods.addModuleDefinition(Integer.parseInt(tokens[0]),
                                        Long.parseLong(tokens[2]), Long.parseLong(tokens[3]), true,
                                        Boolean.parseBoolean(tokens[5]));

                            i++;
                        }
                    }

                    if (lines[i].equals("WATCHER")) {
                        i++;
                        this.watcher = Watcher.getTableInitialModel();

                        while (i < lines.length && !lines[i].equals("END")) {
                            tokens = lines[i].split("::");
                            Object row[] = { tokens[0], tokens[1], null, null };
                            watcher.addRow(row);
                            i++;
                        }
                    }

                    if (lines[i].equals("ISASPECIFIC")) {
                        i++;

                        while (i < lines.length && !lines[i].equals("END")) {
                            tokens = lines[i].split("::");
                            arch.restoreArchSpecificSimStates(tokens);
                            i++;
                        }
                    }
                }
            } else if (handled) {

            } else {
                Msg.W("open(" + path + "): unable to process entry: " + entry.getName()
                        + ". This file will be removed when" + " you save the project.", this);
            }
        }

        tIn.close();

        if (asmFileOrder.isEmpty()) {
            return Msg.E("open(" + path + "): no .asm files found.", Constants.PLP_BACKEND_INVALID_PLP_FILE,
                    null);
        }

    } catch (Exception e) {
        Msg.trace(e);
        return Msg.E("open(" + path + "): Invalid PLP archive.", Constants.PLP_BACKEND_INVALID_PLP_FILE, null);
    }

    if (arch == null) {
        Msg.W("No ISA information specified in the archive, assuming plpmips", this);
        arch = ArchRegistry.getArchitecture(this, ArchRegistry.ISA_PLPMIPS);
        arch.init();
    }

    plpfile = new File(path);
    modified = false;
    open_asm = 0;

    for (int i = 0; i < asms.size(); i++)
        Msg.I(i + ": " + asms.get(i).getAsmFilePath(), null);

    if (g)
        refreshProjectView(false);
    if (!dirty && assemble) {
        assemble();
        asm_req = false;
    } else
        asm_req = true;

    if (g) {
        g_opts.restoreSavedOpts();
        desimulate();

        if (asm != null && asm.isAssembled())
            g_dev.enableSimControls();
        else
            g_dev.disableSimControls();

        this.setUnModified();
        updateWindowTitle();
        g_dev.updateDevelopRecentProjectList(plpFile.getAbsolutePath());
        if (g_asmview != null)
            g_asmview.dispose();
    }

    CallbackRegistry.callback(CallbackRegistry.PROJECT_OPEN_SUCCESSFUL, plpFile);
    return Constants.PLP_OK;
}

From source file:rv.comm.rcssserver.TarBz2ZipUtil.java

public static Reader getTarBZ2InputStream(File file) {
    try {//from  w w w  .  j  a  v  a 2s  .c om
        // only works for the current layout of tar.bz2 files
        InputStream zStream = new BufferedInputStream(new FileInputStream(file));
        CompressorInputStream bz2InputStream = new CompressorStreamFactory()
                .createCompressorInputStream(CompressorStreamFactory.BZIP2, zStream);
        TarArchiveInputStream tarStream = new TarArchiveInputStream(bz2InputStream);
        TarArchiveEntry entry = tarStream.getNextTarEntry();

        // step into deepest directory
        while (entry != null && entry.isDirectory()) {
            TarArchiveEntry[] entries = entry.getDirectoryEntries();
            if (entries.length > 0) {
                entry = entries[0];
            } else {
                // empty directory
                entry = tarStream.getNextTarEntry();
            }
        }
        if (entry == null) {
            System.out.println("tar file does not contain logfile");
            return null;
        }

        // search for proper file
        while (entry != null && !entry.getName().endsWith("sparkmonitor.log")) {
            entry = tarStream.getNextTarEntry();
        }

        if (entry == null) {
            System.out.println("tar file does not contain logfile");
            return null;
        }

        // we have reached the proper position
        return new InputStreamReader(tarStream);

    } catch (IOException e) {
        // not a bz2 file
        System.out.println("File has bz2 ending, but seems to be not bz2");
        e.printStackTrace();
    } catch (CompressorException e) {
        e.printStackTrace();
    }
    return null;
}