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

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this stream.

Usage

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

protected boolean downloadNetbootFiles() {
    if (System.currentTimeMillis() - lastChecked < 50 * 60 * 1000) {
        return false;
    }/*from   w ww .  j a  v  a  2s .  co  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:org.zaproxy.libs.DownloadTools.java

public static void downloadDriver(String urlStr, String destDir, String destFile) {
    File dest = new File(destDir + destFile);
    if (dest.exists()) {
        System.out.println("Already exists: " + dest.getAbsolutePath());
        return;/*ww  w  .j av a  2  s  . co m*/
    }
    File parent = dest.getParentFile();
    if (!parent.exists() && !parent.mkdirs()) {
        System.out.println("Failed to create directory : " + dest.getParentFile().getAbsolutePath());
    }
    byte[] buffer = new byte[1024];
    if (urlStr.endsWith(".zip")) {
        try {
            URL url = new URL(urlStr);
            ZipInputStream zipIn = new ZipInputStream(url.openStream());
            ZipEntry entry;

            boolean isFound = false;
            while ((entry = zipIn.getNextEntry()) != null) {
                if (destFile.equals(entry.getName())) {
                    isFound = true;
                    FileOutputStream out = new FileOutputStream(dest);
                    int read = 0;
                    while ((read = zipIn.read(buffer)) != -1) {
                        out.write(buffer, 0, read);
                    }
                    out.close();
                    System.out.println("Updated: " + dest.getAbsolutePath());

                } else {
                    System.out.println("Found " + entry.getName());
                }
                zipIn.closeEntry();
                entry = zipIn.getNextEntry();
            }

            zipIn.close();

            if (!isFound) {
                System.out.println("Failed to find " + destFile);
                System.exit(1);
            }

        } catch (IOException ex) {
            ex.printStackTrace();
            System.exit(1);
        }
    } else if (urlStr.endsWith(".tar.gz")) {
        try {
            URL url = new URL(urlStr);
            GZIPInputStream gzis = new GZIPInputStream(url.openStream());

            File tarFile = new File(dest.getAbsolutePath() + ".tar");
            FileOutputStream out = new FileOutputStream(tarFile);

            int len;
            while ((len = gzis.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }

            gzis.close();
            out.close();

            TarArchiveInputStream tar = new TarArchiveInputStream(new FileInputStream(tarFile));
            ArchiveEntry entry;
            boolean isFound = false;
            while ((entry = tar.getNextEntry()) != null) {
                if (destFile.equals(entry.getName())) {
                    out = new FileOutputStream(dest);
                    isFound = true;

                    int read = 0;
                    while ((read = tar.read(buffer)) != -1) {
                        out.write(buffer, 0, read);
                    }
                    out.close();
                    System.out.println("Updated: " + dest.getAbsolutePath());
                }
            }
            tar.close();
            tarFile.delete();
            if (!isFound) {
                System.out.println("Failed to find " + destFile);
                System.exit(1);
            }

        } catch (IOException ex) {
            ex.printStackTrace();
            System.exit(1);
        }
    }
}

From source file:plptool.gui.ProjectDriver.java

/**
 * Open plp file specified by path.//  w  w w.j  a v a 2  s.  co  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:uk.ac.ebi.intact.dataexchange.psimi.exporter.archive.Compressor.java

private void untar(File compressedFile, File destinationDir) throws IOException {
    InputStream is = new FileInputStream(compressedFile);
    TarArchiveInputStream tais = new TarArchiveInputStream(is);

    ArchiveEntry te;/*from   w  ww.  jav a2  s.c  o  m*/

    while ((te = tais.getNextEntry()) != null) {
        File dest = new File(destinationDir, te.getName());

        FileOutputStream os = new FileOutputStream(dest);

        try {
            IOUtils.copy(tais, os);
        } finally {
            os.close();
        }
    }

    tais.close();
}

From source file:uk.ac.man.cs.mdsd.webgen.ui.wizards.NewWebgenProjectOperation.java

@SuppressWarnings("unused")
private void extractTGZ(final URL sourceURL, final IPath rootPath, final int removeSegemntsCount,
        final IPath[] ignoreFilter, final Map<IPath, IPath> renames) {

    try {/*from  w  w w . j  a v a2  s . co  m*/
        final File tgzPath = new File(FileLocator.resolve(sourceURL).toURI());
        final TarArchiveInputStream tarIn = new TarArchiveInputStream(
                new GzipCompressorInputStream(new BufferedInputStream(new FileInputStream(tgzPath))));
        TarArchiveEntry entry = (TarArchiveEntry) tarIn.getNextEntry();
        while (entry != null) {
            IPath path = new Path(entry.getName()).removeFirstSegments(removeSegemntsCount);
            if (renames.containsKey(path)) {
                path = renames.get(path);
            }
            if (rootPath != null) {
                path = new Path(rootPath.toString() + path.toString());
            }
            if (!path.isEmpty() && !ignoreEntry(path, ignoreFilter)) {
                if (entry.isDirectory()) {
                    final IFolder folder = projectHandle.getFolder(path);
                    if (!folder.exists()) {
                        folder.create(false, true, null);
                    }
                } else {
                    byte[] contents = new byte[(int) entry.getSize()];
                    tarIn.read(contents);
                    final IFile file = projectHandle.getFile(path);
                    file.create(new ByteArrayInputStream(contents), false, null);
                }
            }
            entry = (TarArchiveEntry) tarIn.getNextEntry();
        }
        tarIn.close();
    } catch (URISyntaxException | IOException | CoreException e) {
        WebgenUiPlugin.log(e);
    }
}