Example usage for java.util.zip ZipFile getInputStream

List of usage examples for java.util.zip ZipFile getInputStream

Introduction

In this page you can find the example usage for java.util.zip ZipFile getInputStream.

Prototype

public InputStream getInputStream(ZipEntry entry) throws IOException 

Source Link

Document

Returns an input stream for reading the contents of the specified zip file entry.

Usage

From source file:apim.restful.exportimport.utils.APIImportUtil.java

/**
 * This method decompresses the archive//from  ww  w.  jav  a  2 s .c o m
 *
 * @param sourceFile           the archive containing the API
 * @param destinationDirectory location of the archive to be extracted
 * @return extractedFolder the name of the zip
 */
public static String unzipArchive(File sourceFile, File destinationDirectory) throws APIManagementException {

    InputStream inputStream = null;
    FileOutputStream fileOutputStream = null;
    File destinationFile;
    ZipFile zipfile = null;
    String extractedFolder = null;

    try {
        zipfile = new ZipFile(sourceFile);
        Enumeration zipEntries = null;
        if (zipfile != null) {
            zipEntries = zipfile.entries();
        }
        if (zipEntries != null) {
            int index = 0;
            while (zipEntries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) zipEntries.nextElement();

                if (entry.isDirectory()) {

                    //This index variable is used to get the extracted folder name; that is root directory
                    if (index == 0) {

                        //Get the folder name without the '/' character at the end
                        extractedFolder = entry.getName().substring(0, entry.getName().length() - 1);
                    }
                    index = -1;
                    new File(destinationDirectory, entry.getName()).mkdir();
                    continue;
                }
                inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
                destinationFile = new File(destinationDirectory, entry.getName());
                fileOutputStream = new FileOutputStream(destinationFile);
                copyStreams(inputStream, fileOutputStream);
            }
        }
    } catch (ZipException e) {
        log.error("Error in retrieving archive files.");
        throw new APIManagementException("Error in retrieving archive files.", e);
    } catch (IOException e) {
        log.error("Error in decompressing API archive files.");
        throw new APIManagementException("Error in decompressing API archive files.", e);
    } finally {
        try {
            if (zipfile != null) {
                zipfile.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            if (fileOutputStream != null) {
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        } catch (IOException e) {
            log.error("Error in closing streams while decompressing files.");
        }
    }
    return extractedFolder;
}

From source file:com.dclab.preparation.ReadTest.java

public String handleZip(final ZipFile zf, final ZipEntry ze) throws IOException {

    if (ze.isDirectory()) {
        System.out.println(ze.getName() + " is folder ");
    } else if (ze.getName().endsWith(".xml")) {
        Logger.getAnonymousLogger().info("process file " + ze.getName());

        String s = ze.toString();

        // ByteBuffer bb = ByteBuffer.allocate(MAX_CAPACITY);
        InputStream is = zf.getInputStream(ze);

        byte[] bytes = IOUtils.toByteArray(is);

        return extract(new String(bytes));

        //scan( sr );
    }//www  .j av  a2s  . c  o  m
    return null;
}

From source file:ch.entwine.weblounge.maven.MyGengoI18nImport.java

/**
 * {@inheritDoc}/*from www  . j av a 2s.  c  om*/
 * 
 * @see org.apache.maven.plugin.Mojo#execute()
 */
public void execute() throws MojoExecutionException, MojoFailureException {
    log.info("Start importing i18n files from myGengo.");
    URLConnection conn = getMyGengoConn();
    ZipFile zip = extractZipFileFromConn(conn);

    if (zip != null) {
        Enumeration<? extends ZipEntry> entries = zip.entries();
        ZipEntry entry;
        while (entries.hasMoreElements()) {
            try {
                entry = entries.nextElement();
                importLanguageFile(entry.getName(), zip.getInputStream(entry));
            } catch (FileNotFoundException e) {
                log.error("Error while reading zip file.");
            } catch (IOException e) {
                log.error("Error while reading zip file.");
            }
        }
    }
    log.info("Importing i18n files from myGengo finished.");
}

From source file:dpfmanager.shell.modules.client.core.ClientService.java

private boolean unzipFileIntoDirectory(File file, File dest) {
    try {/* ww w  . ja v a  2  s .  co m*/
        ZipFile zipFile = new ZipFile(file);
        Enumeration files = zipFile.entries();
        while (files.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) files.nextElement();
            InputStream eis = zipFile.getInputStream(entry);
            byte[] buffer = new byte[1024];
            int bytesRead = 0;

            File f = new File(dest.getAbsolutePath() + File.separator + entry.getName());

            if (entry.isDirectory()) {
                f.mkdirs();
                continue;
            } else {
                f.getParentFile().mkdirs();
                f.createNewFile();
            }

            FileOutputStream fos = new FileOutputStream(f);

            while ((bytesRead = eis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            fos.close();
        }
    } catch (IOException e) {
        return false;
    }
    return true;
}

From source file:com.replaymod.replaystudio.launcher.ReverseLauncher.java

public void launch(CommandLine cmd) throws Exception {
    ZipFile file = new ZipFile(cmd.getArgs()[0]);
    ZipEntry entry = file.getEntry("recording.tmcpr");
    if (entry == null) {
        throw new IOException("Input file is not a valid replay file.");
    }//from  w  w  w. ja  va  2  s  .  c  om
    long size = entry.getSize();
    if (size == -1) {
        throw new IOException("Uncompressed size of recording.tmcpr not set.");
    }

    InputStream from = file.getInputStream(entry);
    RandomAccessFile to = new RandomAccessFile(cmd.getArgs()[1], "rw");

    to.setLength(size);
    int nRead;
    long pos = size;
    byte[] buffer = new byte[8192];

    long lastUpdate = -1;
    while (true) {
        long pct = 100 - pos * 100 / size;
        if (lastUpdate != pct) {
            System.out.print("Reversing " + size + " bytes... " + pct + "%\r");
            lastUpdate = pct;
        }
        int next = readInt(from);
        int length = readInt(from);
        if (next == -1 || length == -1) {
            break; // reached end of stream
        }
        // Increase buffer if necessary
        if (length + 8 > buffer.length) {
            buffer = new byte[length + 8];
        }
        buffer[0] = (byte) ((next >>> 24) & 0xFF);
        buffer[1] = (byte) ((next >>> 16) & 0xFF);
        buffer[2] = (byte) ((next >>> 8) & 0xFF);
        buffer[3] = (byte) (next & 0xFF);
        buffer[4] = (byte) ((length >>> 24) & 0xFF);
        buffer[5] = (byte) ((length >>> 16) & 0xFF);
        buffer[6] = (byte) ((length >>> 8) & 0xFF);
        buffer[7] = (byte) (length & 0xFF);

        nRead = 0;
        while (nRead < length) {
            nRead += from.read(buffer, 8 + nRead, length - nRead);
        }

        pos -= length + 8;
        to.seek(pos);
        to.write(buffer, 0, length + 8);
    }

    from.close();
    to.close();

    System.out.println("\nDone!");
}

From source file:com.heliosdecompiler.helios.transformers.disassemblers.KrakatauDisassembler.java

public boolean disassembleClassNode(ClassNode cn, byte[] b, StringBuilder output) {
    if (Helios.ensurePython2Set()) {
        File inputJar = null;//from  w w w .ja  v  a  2 s .  c o  m
        File outputZip = null;
        String processLog = null;

        try {
            inputJar = Files.createTempFile("kdisin", ".jar").toFile();
            outputZip = Files.createTempFile("kdisout", ".zip").toFile();

            Map<String, byte[]> data = Helios.getAllLoadedData();
            data.put(cn.name + ".class", b);

            Utils.saveClasses(inputJar, data);

            Process process = Helios.launchProcess(new ProcessBuilder(
                    com.heliosdecompiler.helios.Settings.PYTHON2_LOCATION.get().asString(), "-O",
                    "disassemble.py", "-path", inputJar.getAbsolutePath(), "-out", outputZip.getAbsolutePath(),
                    cn.name + ".class", Settings.ROUNDTRIP.isEnabled() ? "-roundtrip" : "")
                            .directory(Constants.KRAKATAU_DIR));

            processLog = Utils.readProcess(process);

            ZipFile zipFile = new ZipFile(outputZip);
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            byte[] disassembled = null;
            while (entries.hasMoreElements()) {
                ZipEntry next = entries.nextElement();
                if (next.getName().equals(cn.name + ".j")) {
                    disassembled = IOUtils.toByteArray(zipFile.getInputStream(next));
                }
            }
            zipFile.close();
            output.append(new String(disassembled, "UTF-8"));
            return true;
        } catch (Exception e) {
            output.append(parseException(e)).append(processLog);
            return false;
        } finally {
            FileUtils.deleteQuietly(inputJar);
            FileUtils.deleteQuietly(outputZip);
        }
    } else {
        output.append("You need to set the location of Python 2.x");
    }
    return false;
}

From source file:hudson.model.DirectoryBrowserSupportTest.java

@Issue("JENKINS-19752")
@Test/*from   w  ww .ja  v  a  2 s  .  com*/
public void zipDownload() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject();
    p.setScm(new SingleFileSCM("artifact.out", "Hello world!"));
    p.getPublishersList().add(new ArtifactArchiver("*", "", true));
    assertEquals(Result.SUCCESS, p.scheduleBuild2(0).get().getResult());

    HtmlPage page = j.createWebClient().goTo("job/" + p.getName() + "/lastSuccessfulBuild/artifact/");
    Page download = page.getAnchorByHref("./*zip*/archive.zip").click();
    File zipfile = download((UnexpectedPage) download);

    ZipFile readzip = new ZipFile(zipfile);

    InputStream is = readzip.getInputStream(readzip.getEntry("archive/artifact.out"));

    // ZipException in case of JENKINS-19752
    assertFalse("Downloaded zip file must not be empty", is.read() == -1);

    is.close();
    readzip.close();
    zipfile.delete();
}

From source file:com.samczsun.helios.transformers.disassemblers.KrakatauDisassembler.java

public boolean disassembleClassNode(ClassNode cn, byte[] b, StringBuilder output) {
    if (Helios.ensurePython2Set()) {
        File inputJar = null;//from   w ww .  ja va  2  s .c  om
        File outputZip = null;
        String processLog = null;

        try {
            inputJar = Files.createTempFile("kdisin", ".jar").toFile();
            outputZip = Files.createTempFile("kdisout", ".zip").toFile();

            Map<String, byte[]> data = Helios.getAllLoadedData();
            data.put(cn.name + ".class", b);

            Utils.saveClasses(inputJar, data);

            Process process = Helios.launchProcess(new ProcessBuilder(
                    com.samczsun.helios.Settings.PYTHON2_LOCATION.get().asString(), "-O", "disassemble.py",
                    "-path", inputJar.getAbsolutePath(), "-out", outputZip.getAbsolutePath(),
                    cn.name + ".class", Settings.ROUNDTRIP.isEnabled() ? "-roundtrip" : "")
                            .directory(Constants.KRAKATAU_DIR));

            processLog = Utils.readProcess(process);

            ZipFile zipFile = new ZipFile(outputZip);
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            byte[] disassembled = null;
            while (entries.hasMoreElements()) {
                ZipEntry next = entries.nextElement();
                if (next.getName().equals(cn.name + ".j")) {
                    disassembled = IOUtils.toByteArray(zipFile.getInputStream(next));
                }
            }
            zipFile.close();
            output.append(new String(disassembled, "UTF-8"));
            return true;
        } catch (Exception e) {
            output.append(parseException(e)).append(processLog);
            return false;
        } finally {
            FileUtils.deleteQuietly(inputJar);
            FileUtils.deleteQuietly(outputZip);
        }
    } else {
        output.append("You need to set the location of Python 2.x");
    }
    return false;
}

From source file:org.jboss.dashboard.ui.resources.GraphicElementPreview.java

protected void initDataStructures(File f) throws IOException {
    ZipFile zfile = new ZipFile(f);
    ZipEntry descriptorEntry = zfile.getEntry(getDescriptorFilename());
    if (descriptorEntry == null) {
        status = STATUS_MISSING_DESCRIPTOR;
        return;//from w  ww  .j a  v a 2s  . c  om
    }
    Properties prop = new Properties();
    try {
        prop.load(zfile.getInputStream(descriptorEntry));
    } catch (IOException ioe) {
        log.warn("Error processing descriptor file. ", ioe);
        status = STATUS_DESCRIPTOR_CORRUPT;
        return;
    }
    description = new Properties();
    resources = new Properties();
    Enumeration properties = prop.propertyNames();
    while (properties.hasMoreElements()) {
        String propName = (String) properties.nextElement();
        if (propName.startsWith("name.")) {
            String lang = propName.substring(propName.lastIndexOf(".") + 1);
            setDescription(prop.getProperty(propName), lang);
            log.debug("Element preview name (" + lang + "): " + prop.getProperty(propName));
        } else if (propName.startsWith("resource.")) {
            String resourceName = propName.substring("resource.".length());
            String resourcePath = prop.getProperty(propName);
            resources.setProperty(resourceName, resourcePath);
        } else {
            log.warn("Unknown property in element " + propName);
        }
    }
    log.debug("Resources inside zip = " + resources);
    resourcesDeployed = new HashMap();
    for (Enumeration en = resources.propertyNames(); en.hasMoreElements();) {
        String resName = (String) en.nextElement();
        String resPath = resources.getProperty(resName);
        log.debug("Deploying property " + resName + "=" + resPath);
        ZipEntry resourceEntry = zfile.getEntry(resPath);
        if (resourceEntry != null) {
            resourcesDeployed.put(resName, toByteArray(zfile.getInputStream(resourceEntry)));
        }
    }
}

From source file:com.phonegap.plugin.files.ExtractZipFilePlugin.java

@Override
public boolean execute(String action, JSONArray args, CallbackContext cbc) {
    PluginResult.Status status = PluginResult.Status.OK;
    try {/*from w  w w.ja  v a 2  s . c o m*/
        String filename = args.getString(0);
        URL url;
        try {
            url = new URL(filename);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
        File file = new File(url.getFile());
        String[] dirToSplit = url.getFile().split(File.separator);
        String dirToInsert = "";
        for (int i = 0; i < dirToSplit.length - 1; i++) {
            dirToInsert += dirToSplit[i] + File.separator;
        }

        ZipEntry entry;
        ZipFile zipfile;
        try {
            zipfile = new ZipFile(file);
            Enumeration e = zipfile.entries();
            while (e.hasMoreElements()) {
                entry = (ZipEntry) e.nextElement();
                BufferedInputStream is = null;
                try {
                    is = new BufferedInputStream(zipfile.getInputStream(entry));
                    int count;
                    byte data[] = new byte[102222];
                    String fileName = dirToInsert + entry.getName();
                    File outFile = new File(fileName);
                    if (entry.isDirectory()) {
                        if (!outFile.exists() && !outFile.mkdirs()) {
                            Log.v("info", "Unable to create directories: " + outFile.getAbsolutePath());
                            cbc.sendPluginResult(new PluginResult(IO_EXCEPTION));
                            return false;
                        }
                    } else {
                        File parent = outFile.getParentFile();
                        if (parent.mkdirs()) {
                            Log.v("info", "created directory leading to file");
                        }
                        FileOutputStream fos = null;
                        BufferedOutputStream dest = null;
                        try {
                            fos = new FileOutputStream(outFile);
                            dest = new BufferedOutputStream(fos, 102222);
                            while ((count = is.read(data, 0, 102222)) != -1) {
                                dest.write(data, 0, count);
                            }
                        } finally {
                            if (dest != null) {
                                dest.flush();
                                dest.close();
                            }
                            if (fos != null) {
                                fos.close();
                            }
                        }
                    }
                } finally {
                    if (is != null) {
                        is.close();
                    }
                }
            }
        } catch (ZipException e1) {
            Log.v("error", e1.getMessage(), e1);
            cbc.sendPluginResult(new PluginResult(MALFORMED_URL_EXCEPTION));
            return false;
        } catch (IOException e1) {
            Log.v("error", e1.getMessage(), e1);
            cbc.sendPluginResult(new PluginResult(IO_EXCEPTION));
            return false;
        }

    } catch (JSONException e) {
        cbc.sendPluginResult(new PluginResult(JSON_EXCEPTION));
        return false;
    }
    cbc.sendPluginResult(new PluginResult(status));
    return true;
}