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[] buf, int offset, int numToRead) throws IOException 

Source Link

Document

Reads bytes from the current tar archive entry.

Usage

From source file:org.jenkinsci.plugins.os_ci.utils.CompressUtils.java

public static void untarFile(File file) throws IOException {
    FileInputStream fileInputStream = null;
    String currentDir = file.getParent();
    try {//from  w  ww  .  j  a  va  2  s  . com
        fileInputStream = new FileInputStream(file);
        GZIPInputStream gzipInputStream = new GZIPInputStream(fileInputStream);
        TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(gzipInputStream);

        TarArchiveEntry tarArchiveEntry;

        while (null != (tarArchiveEntry = tarArchiveInputStream.getNextTarEntry())) {
            if (tarArchiveEntry.isDirectory()) {
                FileUtils.forceMkdir(new File(currentDir + File.separator + tarArchiveEntry.getName()));
            } else {
                byte[] content = new byte[(int) tarArchiveEntry.getSize()];
                int offset = 0;
                tarArchiveInputStream.read(content, offset, content.length - offset);
                FileOutputStream outputFile = new FileOutputStream(
                        currentDir + File.separator + tarArchiveEntry.getName());
                org.apache.commons.io.IOUtils.write(content, outputFile);
                outputFile.close();
            }
        }
    } catch (FileNotFoundException e) {
        throw new IOException(e.getStackTrace().toString());
    }
}

From source file:org.mulima.internal.freedb.FreeDbTarDaoImpl.java

/**
 * {@inheritDoc}//from  www.  java2s . co m
 */
@Override
public List<Disc> getAllDiscsFromOffset(int startNum, int numToRead) {
    FileInputStream fin = null;
    BufferedInputStream bfin = null;
    TarArchiveInputStream tin = null;
    List<Disc> discs = new ArrayList<Disc>();
    try {
        fin = new FileInputStream(tarArchive);
        bfin = new BufferedInputStream(fin);
        tin = new TarArchiveInputStream(bfin);

        int currentNum = 0;
        TarArchiveEntry entry = tin.getNextTarEntry();
        ProgressBar progress = new SLF4JProgressBar("TAR getDiscs", numToRead);
        while (entry != null && (numToRead < 0 || currentNum < startNum + numToRead)) {
            if (!entry.isDirectory() && currentNum >= startNum) {
                logger.debug("Loading: " + entry.getName());
                int offset = 0;
                byte[] content = new byte[(int) entry.getSize()];
                while (offset < content.length) {
                    offset += tin.read(content, offset, content.length - offset);
                }
                Disc disc = bytesToDisc(content);
                if (disc == null) {
                    logger.warn("Invalid file: " + entry.getName());
                } else {
                    logger.debug(disc.toString());
                    discs.add(disc);
                }
            }

            entry = tin.getNextTarEntry();
            currentNum++;
            progress.next();
        }

        if (entry == null) {
            progress.done();
        }
    } catch (IOException e) {
        logger.error("Problem reading tar archive.", e);
        throw new UncheckedIOException("Problem reading tar archive.", e);
    } finally {
        try {
            if (tin != null) {
                tin.close();
            } else if (bfin != null) {
                bfin.close();
            } else if (fin != null) {
                fin.close();
            }
        } catch (IOException e) {
            logger.error("Problem closing streams.", e);
        }
    }
    return discs;
}

From source file:org.nd4j.util.ArchiveUtils.java

/**
 * Extracts files to the specified destination
 *
 * @param file the file to extract to/* w  w  w  .  j  a v a 2  s  . c  o m*/
 * @param dest the destination directory
 * @throws IOException
 */
public static void unzipFileTo(String file, String dest) throws IOException {
    File target = new File(file);
    if (!target.exists())
        throw new IllegalArgumentException("Archive doesnt exist");
    FileInputStream fin = new FileInputStream(target);
    int BUFFER = 2048;
    byte data[] = new byte[BUFFER];

    if (file.endsWith(".zip") || file.endsWith(".jar")) {
        try (ZipInputStream zis = new ZipInputStream(fin)) {
            //get the zipped file list entry
            ZipEntry ze = zis.getNextEntry();

            while (ze != null) {
                String fileName = ze.getName();
                File newFile = new File(dest + File.separator + fileName);

                if (ze.isDirectory()) {
                    newFile.mkdirs();
                    zis.closeEntry();
                    ze = zis.getNextEntry();
                    continue;
                }

                FileOutputStream fos = new FileOutputStream(newFile);

                int len;
                while ((len = zis.read(data)) > 0) {
                    fos.write(data, 0, len);
                }

                fos.close();
                ze = zis.getNextEntry();
                log.debug("File extracted: " + newFile.getAbsoluteFile());
            }

            zis.closeEntry();
        }
    } else if (file.endsWith(".tar.gz") || file.endsWith(".tgz")) {

        BufferedInputStream in = new BufferedInputStream(fin);
        GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);
        TarArchiveInputStream tarIn = new TarArchiveInputStream(gzIn);

        TarArchiveEntry entry;
        /* Read the tar entries using the getNextEntry method **/
        while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {
            log.info("Extracting: " + entry.getName());
            /* If the entry is a directory, create the directory. */

            if (entry.isDirectory()) {
                File f = new File(dest + File.separator + entry.getName());
                f.mkdirs();
            }
            /*
             * If the entry is a file,write the decompressed file to the disk
             * and close destination stream.
             */
            else {
                int count;
                try (FileOutputStream fos = new FileOutputStream(dest + File.separator + entry.getName());
                        BufferedOutputStream destStream = new BufferedOutputStream(fos, BUFFER);) {
                    while ((count = tarIn.read(data, 0, BUFFER)) != -1) {
                        destStream.write(data, 0, count);
                    }

                    destStream.flush();
                    IOUtils.closeQuietly(destStream);
                }
            }
        }

        // Close the input stream
        tarIn.close();
    } else if (file.endsWith(".gz")) {
        File extracted = new File(target.getParent(), target.getName().replace(".gz", ""));
        if (extracted.exists())
            extracted.delete();
        extracted.createNewFile();
        try (GZIPInputStream is2 = new GZIPInputStream(fin);
                OutputStream fos = FileUtils.openOutputStream(extracted)) {
            IOUtils.copyLarge(is2, fos);
            fos.flush();
        }
    } else {
        throw new IllegalStateException(
                "Unable to infer file type (compression format) from source file name: " + file);
    }
    target.delete();
}

From source file:org.rsna.ctp.stdstages.ArchiveImportService.java

private void expandTAR(File tar, File dir) {
    try {/*www.  ja  v  a  2 s .  c o  m*/
        TarArchiveInputStream tais = new TarArchiveInputStream(new FileInputStream(tar));
        TarArchiveEntry tae;
        while ((tae = tais.getNextTarEntry()) != null) {
            if (!tae.isDirectory()) {
                FileOutputStream fos = new FileOutputStream(new File(dir, tae.getName()));
                byte[] buf = new byte[4096];
                long count = tae.getSize();
                while (count > 0) {
                    int n = tais.read(buf, 0, buf.length);
                    fos.write(buf, 0, n);
                    count -= n;
                }
                fos.flush();
                fos.close();
            }
        }
        tais.close();
    } catch (Exception ex) {
        logger.warn("Unable to expand: \"" + tar + "\"", ex);
    }
}

From source file:org.sakaiproject.vtlgen.api.PackageUtil.java

public static void untar(String fileName, String targetPath) throws IOException {
    File tarArchiveFile = new File(fileName);
    BufferedOutputStream dest = null;
    FileInputStream tarArchiveStream = new FileInputStream(tarArchiveFile);
    TarArchiveInputStream tis = new TarArchiveInputStream(new BufferedInputStream(tarArchiveStream));
    TarArchiveEntry entry = null;//  w w w. ja va2 s  .  c  om
    try {
        while ((entry = tis.getNextTarEntry()) != null) {
            int count;
            File outputFile = new File(targetPath, entry.getName());

            if (entry.isDirectory()) { // entry is a directory
                if (!outputFile.exists()) {
                    outputFile.mkdirs();
                }
            } else { // entry is a file
                byte[] data = new byte[BUFFER_MAX];
                FileOutputStream fos = new FileOutputStream(outputFile);
                dest = new BufferedOutputStream(fos, BUFFER_MAX);
                while ((count = tis.read(data, 0, BUFFER_MAX)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (dest != null) {
            dest.flush();
            dest.close();
        }
        tis.close();
    }
}

From source file:org.sead.sda.LandingPage.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getParameter("tag") != null || request.getRequestURI().contains("/sda/list")) {
        String tag = "";

        if (request.getParameter("tag") != null) {
            tag = request.getParameter("tag");
        } else {/*from w  ww. j  a  va  2 s  .  com*/
            tag = request.getRequestURI().split("/sda/list=")[1];
        }

        // here we check whether the BagIt zip file for this RO exists in SDA
        SFTP sftp = new SFTP();
        String bagName = getBagNameFromId(tag);
        if (sftp.doesFileExist(Constants.sdaPath + bagName + "/" + bagName + ".zip")) {
            System.out.println("Bag Exists in SDA...");
            request.setAttribute("bagExists", "true");
        }
        sftp.disConnectSessionAndChannel();

        request.setAttribute("obTag", tag);
        request.setAttribute("landingPageUrl", Constants.landingPage);

        String keyList_cp = "@id|status|message|preferences";

        String keyList_ore = "keyword|contact|creator|publication date|title|abstract|license|is version of|similarto|title|describes|@context|aggregates|has part|identifier|label|size";
        //

        keyMapList = new HashMap<String, String>();

        Shimcalls shim = new Shimcalls();
        // Fix: accessing RO from c3pr here is wrong. we have to access the ore map in the
        // published package and read properties from that.
        JSONObject cp = shim.getResearchObject(tag);

        if (cp.isEmpty()) {
            RequestDispatcher dispatcher = request.getRequestDispatcher("/ro.jsp");
            request.setAttribute("roExists", "false");
            dispatcher.forward(request, response);
            return;
        }

        request.setAttribute("roExists", "true");
        SeadMon.addLog(MonConstants.Components.LANDING_PAGE, tag, MonConstants.EventType.ACCESS);

        keyMap(cp, keyList_cp);

        shim.getObjectID(cp, "@id");
        String oreUrl = shim.getID();
        JSONObject oreFile = shim.getResearchObjectORE(oreUrl);
        keyMap(oreFile, keyList_ore);

        JSONObject describes = (JSONObject) oreFile.get(keyMapList.get("describes"));
        Map<String, List<String>> roProperties = new HashMap<String, List<String>>();
        Map<String, String> downloadList = new HashMap<String, String>();
        Map<String, String> linkedHashMap = new LinkedHashMap<String, String>();
        Map<String, String> linkedHashMapTemp = new LinkedHashMap<String, String>();
        Map<String, String> newDownloadList = new LinkedHashMap<String, String>();

        // extract properties from ORE
        JSONArray status = (JSONArray) cp.get(keyMapList.get("Status".toLowerCase()));
        String doi = "No DOI Found"; // handle this as an exception
        String pubDate = null;
        for (Object st : status) {
            JSONObject jsonStatus = (JSONObject) st;
            String stage = (String) jsonStatus.get("stage");
            if ("Success".equals(stage)) {
                doi = (String) jsonStatus.get("message");
                pubDate = (String) jsonStatus.get("date");
            }
        }
        roProperties.put("DOI", Arrays.asList(doi));
        roProperties.put("Publication Date", Arrays.asList(pubDate));
        roProperties.put("Full Metadata",
                Arrays.asList(Constants.landingPage + "/metadata/" + tag + "/oremap"));
        addROProperty("Creator", describes, roProperties);
        //            addROProperty("Publication Date", describes, roProperties);
        addROProperty("Title", describes, roProperties);
        addROProperty("Abstract", describes, roProperties);
        addROProperty("Contact", describes, roProperties);
        addROProperty("Keyword", describes, roProperties);

        JSONObject preferences = (JSONObject) cp.get(keyMapList.get("Preferences".toLowerCase()));

        //addROProperty_License("License", preferences, cp, roProperties);
        addROProperty("License", preferences, roProperties);

        // check access rights
        if (isRORestricted(preferences)) {
            request.setAttribute("accessRestricted", "true");
            List<String> rights = new ArrayList<String>();
            rights.add("Restricted");
            roProperties.put("Access Rights", rights);
        }

        //Map<String, String> properties = new HashMap<String, String>();
        //String Label = properties.get("Label");

        // extract Live Data Links from ORE
        String liveCopy = null;
        if (describes.get(keyMapList.get("Is Version Of".toLowerCase())) != null) {
            String versionOf = describes.get(keyMapList.get("Is Version Of".toLowerCase())).toString();
            if (versionOf.startsWith("http")) {
                liveCopy = versionOf;
            } else if (describes.get(keyMapList.get("similarTo".toLowerCase())) != null) {
                String similar = describes.get(keyMapList.get("similarTo".toLowerCase())).toString();
                similar = similar.substring(0, similar.indexOf("/resteasy") + 1);
                liveCopy = similar + "#collection?uri=" + versionOf;
            }
        }
        if (liveCopy != null) {
            List<String> liveCopyList = new ArrayList<String>();
            if (shim.validUrl(liveCopy)) {
                liveCopyList.add(liveCopy);
            } else {
                liveCopyList.add("Not Available");
            }
            roProperties.put("Live Data Links", liveCopyList);
        }

        // set properties as an attribute
        request.setAttribute("roProperties", roProperties);

        // String title = describes.get(keyMapList.get("Title".toLowerCase())).toString();

        // extract file names from tar archive in SDA
        String requestURI = request.getRequestURI();

        if (requestURI.contains("/sda/list")) {
            int c = 0;
            String[] requestURIsda = requestURI.split("/");
            for (String item : requestURIsda) {
                if (item.equals("sda")) {
                    c++;
                }
            }
            if (c % 2 != 0) {

                //extract RO hierarchy
                try {
                    NewOREmap oreMap = new NewOREmap(oreFile, keyMapList);
                    downloadList = oreMap.getHierarchy();

                    Set<String> nameList = downloadList.keySet();

                    for (String name : nameList) {
                        String[] name_split = name.split("/");
                        String size = null;
                        if (downloadList.get(name) != null) {
                            int bytes = Integer.parseInt(downloadList.get(name));

                            int kb = bytes / 1024;
                            int mb = kb / 1024;
                            int gb = mb / 1024;
                            if (bytes <= 1024) {
                                size = bytes + " Bytes";
                            } else if (kb <= 1024) {
                                size = kb + " KB";
                            } else if (mb <= 1024) {
                                size = mb + " MB";
                            } else {
                                size = gb + " GB";
                            }
                        }

                        String temp = null;
                        if (name_split.length <= 2 && size != null) {

                            temp = "<span style='padding-left:" + 30 * (name_split.length - 2) + "px'>"
                                    + name_split[name_split.length - 1] + "</span>";
                            linkedHashMap.put(name, temp);
                        } else {

                            temp = "<span style='padding-left:" + 30 * (name_split.length - 2) + "px'>" + "|__"
                                    + name_split[name_split.length - 1] + "</span>";
                            linkedHashMapTemp.put(name, temp);
                        }

                        newDownloadList.put(name, size);

                    }

                    for (String key : linkedHashMapTemp.keySet()) {
                        linkedHashMap.put(key, linkedHashMapTemp.get(key));
                    }
                } catch (Exception e) {
                    System.err.println("Landing Page OREmap error: inaccurate keys");
                }

            }

            // set download list as an attribute
            // set linkedHashMap as an attribute
        }
        request.setAttribute("downloadList", newDownloadList);
        request.setAttribute("linkedHashMap", linkedHashMap);

        // forward the user to get_id UI
        RequestDispatcher dispatcher = request.getRequestDispatcher("/ro.jsp");
        dispatcher.forward(request, response);

    } else if (!request.getRequestURI().contains("bootstrap")) {

        // collection title is the last part of the request URI
        String requestURI = request.getRequestURI();
        String newURL = requestURI.substring(requestURI.lastIndexOf("sda/") + 4);
        String title = null;
        String filename = null;

        if (!newURL.contains("/")) {
            title = newURL;
        } else {
            title = newURL.split("/")[0];
            filename = newURL.substring(newURL.indexOf("/") + 1);
        }
        title = URLDecoder.decode(title, "UTF-8");
        newURL = URLDecoder.decode(newURL, "UTF-8");

        // don't allow downloads for restricted ROs
        // Fix: use ORE from package
        Shimcalls shim = new Shimcalls();
        JSONObject ro = shim.getResearchObject(title);

        String keyList_cp = "@id|status|message|preferences";
        keyMapList = new HashMap<String, String>();
        keyMap(ro, keyList_cp);

        if (isRORestricted((JSONObject) ro.get(keyMapList.get("Preferences".toLowerCase())))) {
            return;
        }

        SFTP sftp = new SFTP();
        String bgName = getBagNameFromId(title);
        String target = Constants.sdaPath + bgName + "/" + bgName + ".zip";
        if (!sftp.doesFileExist(target)) {
            target = Constants.sdaPath + title + "/" + title + ".tar";
        }

        System.out.println("title " + title);
        System.out.println("filename " + filename);

        if (!title.equals("*")) {
            InputStream inStream = sftp.downloadFile(target);

            String mimeType = "application/octet-stream";
            response.setContentType(mimeType);

            String headerKey = "Content-Disposition";

            String headerValue = null;
            if (filename != null) {
                if (filename.contains("/")) {
                    filename = filename.substring(filename.lastIndexOf("/") + 1);
                }
                headerValue = String.format("attachment; filename=\"%s\"", filename);
            } else {
                headerValue = String.format("attachment; filename=\"%s\"",
                        target.substring(target.lastIndexOf("/") + 1));
            }
            response.setHeader(headerKey, headerValue);

            OutputStream outStream = response.getOutputStream();
            if (newURL.equals(title)) {
                //download tar file
                SeadMon.addLog(MonConstants.Components.LANDING_PAGE, title, MonConstants.EventType.DOWNLOAD);
                System.out.println("SDA download path: " + target);
                byte[] buffer = new byte[4096];
                int bytesRead;

                while ((bytesRead = inStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                }
            } else {
                //download individual files
                if (target.contains(".tar")) {
                    System.out.println("SDA download path: " + Constants.sdaPath + newURL);
                    TarArchiveInputStream myTarFile = new TarArchiveInputStream(inStream);

                    TarArchiveEntry entry = null;
                    String individualFiles;
                    int offset;

                    while ((entry = myTarFile.getNextTarEntry()) != null) {
                        individualFiles = entry.getName();

                        if (individualFiles.equals(newURL)) {
                            byte[] content = new byte[(int) entry.getSize()];
                            offset = 0;
                            myTarFile.read(content, offset, content.length - offset);
                            outStream.write(content);
                        }
                    }
                    myTarFile.close();
                } else {
                    System.out.println("SDA download path: " + Constants.sdaPath + bgName + "/" + bgName
                            + ".zip/" + bgName + "/" + newURL.substring(newURL.indexOf("/") + 1));
                    BufferedInputStream bin = new BufferedInputStream(inStream);
                    ZipInputStream myZipFile = new ZipInputStream(bin);

                    ZipEntry ze = null;
                    while ((ze = myZipFile.getNextEntry()) != null) {
                        if (ze.getName().equals(bgName + "/" + newURL.substring(newURL.indexOf("/") + 1))) {
                            byte[] buffer = new byte[4096];
                            int len;
                            while ((len = myZipFile.read(buffer)) != -1) {
                                outStream.write(buffer, 0, len);
                            }
                            break;
                        }
                    }
                }
            }
            inStream.close();
            outStream.close();
        }

        sftp.disConnectSessionAndChannel();
    }

}

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

protected boolean downloadNetbootFiles() {
    if (System.currentTimeMillis() - lastChecked < 50 * 60 * 1000) {
        return false;
    }/*from w w w. j  av a2 s.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:plptool.gui.ProjectDriver.java

/**
 * Open plp file specified by path.//  ww  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:Tools.Untargz.java

/**
 * Check if the form of file is correct, Tar.gz file need a svg file, xml file and png file
 * @param archive// w  ww. j  a  v a2 s  . com
 * @param dest
 * @return
 * @throws IOException 
 */
public static LinkedList<FileObject> checkValityOfFile(TarArchiveInputStream archive, String dest)
        throws IOException {

    LinkedList<FileObject> fileObject = new LinkedList<FileObject>();
    ArchiveEntry next;
    int i = 0;

    boolean viewXml = false;
    boolean viewSvg = false;
    boolean viewPng = false;

    while (((next = archive.getNextTarEntry()) != null) && i <= 3) {
        i++;
        String[] str = next.getName().split("[.]+");
        byte[] content = new byte[(int) next.getSize()];
        archive.read(content, 0, content.length);
        FileObject o = new FileObject(content, dest + "/" + next.getName());
        if (str.length == 2) {
            if ((viewSvg == false) && str[1].equals(svgForm)) {
                viewSvg = true;
                fileObject.add(o);
            } else if ((viewPng == false) && str[1].equals(pngForm)) {
                viewPng = true;
                fileObject.add(o);
            } else if ((viewXml == false) && str[1].equals(xmlForm)) {
                viewXml = true;
                fileObject.add(o);
            }
        }
    }

    if ((next == null) && (i == 3) && viewXml && viewPng && viewSvg) {
        return fileObject;
    } else {
        return null;
    }

}