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:com.koushikdutta.superuser.MainActivity.java

void doRecoveryInstall() {
    final ProgressDialog dlg = new ProgressDialog(this);
    dlg.setTitle(R.string.installing);/*from  w  ww . jav a 2s  .c o  m*/
    dlg.setMessage(getString(R.string.installing_superuser));
    dlg.setIndeterminate(true);
    dlg.show();
    new Thread() {
        void doEntry(ZipOutputStream zout, String entryName, String dest) throws IOException {
            ZipFile zf = new ZipFile(getPackageCodePath());
            ZipEntry ze = zf.getEntry(entryName);
            zout.putNextEntry(new ZipEntry(dest));
            InputStream in;
            StreamUtility.copyStream(in = zf.getInputStream(ze), zout);
            zout.closeEntry();
            in.close();
            zf.close();
        }

        public void run() {
            try {
                File zip = getFileStreamPath("superuser.zip");
                ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(zip));
                doEntry(zout, "assets/update-binary", "META-INF/com/google/android/update-binary");
                doEntry(zout, "assets/install-recovery.sh", "install-recovery.sh");
                zout.close();

                ZipFile zf = new ZipFile(getPackageCodePath());
                ZipEntry ze = zf.getEntry("assets/" + getArch() + "/reboot");
                InputStream in;
                FileOutputStream reboot;
                StreamUtility.copyStream(in = zf.getInputStream(ze),
                        reboot = openFileOutput("reboot", MODE_PRIVATE));
                reboot.close();
                in.close();

                final File su = extractSu();

                String command = String.format("cat %s > /cache/superuser.zip\n", zip.getAbsolutePath())
                        + String.format("cat %s > /cache/su\n", su.getAbsolutePath())
                        + String.format("cat %s > /cache/Superuser.apk\n", getPackageCodePath())
                        + "mkdir /cache/recovery\n"
                        + "echo '--update_package=CACHE:superuser.zip' > /cache/recovery/command\n"
                        + "chmod 644 /cache/superuser.zip\n" + "chmod 644 /cache/recovery/command\n" + "sync\n"
                        + String.format("chmod 755 %s\n", getFileStreamPath("reboot").getAbsolutePath())
                        + "reboot recovery\n";
                Process p = Runtime.getRuntime().exec("su");
                p.getOutputStream().write(command.getBytes());
                p.getOutputStream().close();
                File rebootScript = getFileStreamPath("reboot.sh");
                StreamUtility.writeFile(rebootScript,
                        "reboot recovery ; " + getFileStreamPath("reboot").getAbsolutePath() + " recovery ;");
                p.waitFor();
                Runtime.getRuntime().exec(new String[] { "su", "-c", ". " + rebootScript.getAbsolutePath() });
                if (p.waitFor() != 0)
                    throw new Exception("non zero result");
            } catch (Exception ex) {
                ex.printStackTrace();
                dlg.dismiss();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setPositiveButton(android.R.string.ok, null);
                        builder.setTitle(R.string.install);
                        builder.setMessage(R.string.install_error);
                        builder.create().show();
                    }
                });
            }
        }
    }.start();
}

From source file:gov.nih.nci.caarray.application.fileaccess.FileAccessUtils.java

/**
 * Unzips a .zip file, removes it from <code>files</code> and adds the extracted files to <code>files</code>.
 * //from w w w .j  a  v a 2 s.  c  o m
 * @param files the list of files to unzip and the files extracted from the zips
 * @param fileNames the list of filenames to go along with the list of files
 */
@SuppressWarnings("PMD.ExcessiveMethodLength")
public void unzipFiles(List<File> files, List<String> fileNames) {
    try {
        final Pattern p = Pattern.compile("\\.zip$");
        int index = 0;
        for (int i = 0; i < fileNames.size(); i++) {
            final Matcher m = p.matcher(fileNames.get(i).toLowerCase());

            if (m.find()) {
                final File file = files.get(i);
                final String fileName = file.getAbsolutePath();
                final String directoryPath = file.getParent();
                final ZipFile zipFile = new ZipFile(fileName);
                final Enumeration<? extends ZipEntry> entries = zipFile.entries();
                while (entries.hasMoreElements()) {
                    final ZipEntry entry = entries.nextElement();
                    final File entryFile = new File(directoryPath + "/" + entry.getName());

                    final InputStream fileInputStream = zipFile.getInputStream(entry);
                    final FileOutputStream fileOutputStream = new FileOutputStream(entryFile);
                    IOUtils.copy(fileInputStream, fileOutputStream);
                    IOUtils.closeQuietly(fileOutputStream);

                    files.add(entryFile);
                    fileNames.add(entry.getName());
                }
                zipFile.close();
                files.remove(index);
                fileNames.remove(index);
            }
            index++;
        }
    } catch (final IOException e) {
        throw new FileAccessException("Couldn't unzip archive.", e);
    }
}

From source file:ccm.pay2spawn.types.MusicType.java

@Override
public void printHelpList(File configFolder) {
    musicFolder = new File(configFolder, "music");
    if (musicFolder.mkdirs()) {
        new Thread(new Runnable() {
            @Override/*from   w  ww  .j  a  v a 2 s  . com*/
            public void run() {
                try {
                    File zip = new File(musicFolder, "music.zip");
                    FileUtils.copyURLToFile(new URL(Constants.MUSICURL), zip);
                    ZipFile zipFile = new ZipFile(zip);
                    Enumeration<? extends ZipEntry> entries = zipFile.entries();
                    while (entries.hasMoreElements()) {
                        ZipEntry entry = entries.nextElement();
                        File entryDestination = new File(musicFolder, entry.getName());
                        entryDestination.getParentFile().mkdirs();
                        InputStream in = zipFile.getInputStream(entry);
                        OutputStream out = new FileOutputStream(entryDestination);
                        IOUtils.copy(in, out);
                        IOUtils.closeQuietly(in);
                        IOUtils.closeQuietly(out);
                    }
                    zipFile.close();
                    zip.delete();
                } catch (IOException e) {
                    Pay2Spawn.getLogger()
                            .warn("Error downloading music file. Get from github and unpack yourself please.");
                    e.printStackTrace();
                }
            }
        }, "Pay2Spawn music download and unzip").start();
    }
}

From source file:de.tudarmstadt.ukp.clarin.webanno.project.page.ImportUtil.java

/**
 * copy Project META_INF from the exported project
 * @param zip the ZIP file./*from  w w  w  . j  av  a  2 s . c om*/
 * @param aProject the project.
 * @param aRepository the repository service.
 * @throws IOException if an I/O error occurs.
 */
@SuppressWarnings("rawtypes")
public static void createProjectMetaInf(ZipFile zip, Project aProject, RepositoryService aRepository)
        throws IOException {
    for (Enumeration zipEnumerate = zip.entries(); zipEnumerate.hasMoreElements();) {
        ZipEntry entry = (ZipEntry) zipEnumerate.nextElement();

        // Strip leading "/" that we had in ZIP files prior to 2.0.8 (bug #985)
        String entryName = normalizeEntryName(entry);

        if (entryName.startsWith(META_INF)) {
            File metaInfDir = new File(aRepository.getMetaInfFolder(aProject),
                    FilenameUtils.getPath(entry.getName().replace(META_INF, "")));
            // where the file reside in the META-INF/... directory
            FileUtils.forceMkdir(metaInfDir);
            FileUtils.copyInputStreamToFile(zip.getInputStream(entry),
                    new File(metaInfDir, FilenameUtils.getName(entry.getName())));

            LOG.info("Imported META-INF for project [" + aProject.getName() + "] with id [" + aProject.getId()
                    + "]");
        }
    }
}

From source file:org.alfresco.repo.web.scripts.custommodel.CustomModelImportTest.java

public void testNotZipFileUpload() throws Exception {
    File file = getResourceFile("validModel.zip");
    ZipFile zipFile = new ZipFile(file);
    ZipEntry zipEntry = zipFile.entries().nextElement();

    File unzippedModelFile = TempFileProvider.createTempFile(zipFile.getInputStream(zipEntry), "validModel",
            ".xml");
    tempFiles.add(unzippedModelFile);//from  www  .  j a v a2  s  .c  om
    zipFile.close();

    PostRequest postRequest = buildMultipartPostRequest(unzippedModelFile);
    sendRequest(postRequest, 400); // CMM upload supports only zip file.
}

From source file:com.krawler.esp.fileparser.wordparser.DocxParser.java

public String extractText(String filepath) {
    StringBuilder sb = new StringBuilder();

    ZipFile docxfile = null;
    try {//ww w  .jav  a  2 s. c om
        docxfile = new ZipFile(filepath);
    } catch (Exception e) {
        // file corrupt or otherwise could not be found
        logger.warn(e.getMessage(), e);
        return sb.toString();
    }
    InputStream in = null;
    try {
        ZipEntry ze = docxfile.getEntry("word/document.xml");
        in = docxfile.getInputStream(ze);
    } catch (NullPointerException nulle) {
        System.err.println("Expected entry word/document.xml does not exist");
        logger.warn(nulle.getMessage(), nulle);
        return sb.toString();
    } catch (IOException ioe) {
        logger.warn(ioe.getMessage(), ioe);
        return sb.toString();
    }
    Document document = null;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        document = builder.parse(in);
    } catch (ParserConfigurationException pce) {
        logger.warn(pce.getMessage(), pce);
        return sb.toString();
    } catch (SAXException sex) {
        sex.printStackTrace();
        return sb.toString();
    } catch (IOException ioe) {
        logger.warn(ioe.getMessage(), ioe);
        return sb.toString();
    } finally {
        try {
            docxfile.close();
        } catch (IOException ioe) {
            System.err.println("Exception closing file.");
            logger.warn(ioe.getMessage(), ioe);
        }
    }
    NodeList list = document.getElementsByTagName("w:t");
    List<String> content = new ArrayList<String>();
    for (int i = 0; i < list.getLength(); i++) {
        Node aNode = list.item(i);
        content.add(aNode.getFirstChild().getNodeValue());
    }
    for (String s : content) {
        sb.append(s);
    }

    return sb.toString();
}

From source file:org.apache.tez.history.parser.ATSFileParser.java

/**
 * Read zip file contents. Every file can contain "dag", "vertices", "tasks", "task_attempts"
 *
 * @param atsFile// w  w w. ja v a 2s . c  om
 * @throws IOException
 * @throws JSONException
 */
private void parseATSZipFile(File atsFile)
        throws IOException, JSONException, TezException, InterruptedException {
    final ZipFile atsZipFile = new ZipFile(atsFile);
    try {
        Enumeration<? extends ZipEntry> zipEntries = atsZipFile.entries();
        while (zipEntries.hasMoreElements()) {
            ZipEntry zipEntry = zipEntries.nextElement();
            LOG.debug("Processing " + zipEntry.getName());
            InputStream inputStream = atsZipFile.getInputStream(zipEntry);
            JSONObject jsonObject = readJson(inputStream);

            //This json can contain dag, vertices, tasks, task_attempts
            JSONObject dagJson = jsonObject.optJSONObject(Constants.DAG);
            if (dagJson != null) {
                //TODO: support for multiple dags per ATS file later.
                dagInfo = DagInfo.create(dagJson);
            }

            //Process vertex
            JSONArray vertexJson = jsonObject.optJSONArray(Constants.VERTICES);
            if (vertexJson != null) {
                processVertices(vertexJson);
            }

            //Process task
            JSONArray taskJson = jsonObject.optJSONArray(Constants.TASKS);
            if (taskJson != null) {
                processTasks(taskJson);
            }

            //Process task attempts
            JSONArray attemptsJson = jsonObject.optJSONArray(Constants.TASK_ATTEMPTS);
            if (attemptsJson != null) {
                processAttempts(attemptsJson);
            }

            //Process application (mainly versionInfo)
            JSONObject tezAppJson = jsonObject.optJSONObject(Constants.APPLICATION);
            if (tezAppJson != null) {
                processApplication(tezAppJson);
            }
        }
    } finally {
        atsZipFile.close();
    }
}

From source file:de.dfki.km.perspecting.obie.corpus.BBCNatureCorpus.java

public Reader getGroundTruth(final URI uri) throws Exception {
    if (labelFileMediaType == MediaType.DIRECTORY) {
        return new StringReader(FileUtils.readFileToString(new File(uri)));
    } else if (labelFileMediaType == MediaType.ZIP) {
        ZipFile zipFile = new ZipFile(labelFolder);
        String[] entryName = uri.toURL().getFile().split("/");
        ZipEntry entry = zipFile/*ww  w .j a  v a  2s  .c  om*/
                .getEntry(URLDecoder.decode(entryName[entryName.length - 1], "utf-8").replace("text", "rdf"));

        if (entry != null) {
            log.info("found labels for: " + uri.toString());
        } else {
            throw new Exception("did not found labels for: " + uri.toString());
        }
        return new InputStreamReader(zipFile.getInputStream(entry));
    } else {
        throw new Exception("Unsupported media format for labels: " + labelFileMediaType + ". "
                + "Please use zip or plain directories instead.");
    }
}

From source file:abfab3d.io.input.STSReader.java

/**
 * Load a STS file into a grid.//from   w w  w.  jav a  2 s . co  m
 *
 * @param file The zip file
 * @return
 * @throws java.io.IOException
 */
public AttributeGrid loadGrid(String file) throws IOException {

    ZipFile zip = null;

    try {
        zip = new ZipFile(file);

        ZipEntry entry = zip.getEntry("manifest.xml");
        if (entry == null) {
            throw new IOException("Cannot find manifest.xml in top level");
        }

        InputStream is = zip.getInputStream(entry);
        mf = parseManifest(is);

        if (mf == null) {
            throw new IOException("Could not parse manifest file");
        }
        /*
                    AttributeGrid ret_val = new ArrayAttributeGridByte(mf.getGridSizeX(),mf.getGridSizeY(),mf.getGridSizeZ(),mf.getVoxelSize(),mf.getVoxelSize());
                
                    double[] bounds = new double[6];
                
                    bounds[0] = mf.getOriginX();
                    bounds[1] = mf.getOriginX() + mf.getGridSizeX() * mf.getVoxelSize();
                    bounds[2] = mf.getOriginY();
                    bounds[3] = mf.getOriginY() + mf.getGridSizeY() * mf.getVoxelSize();
                    bounds[4] = mf.getOriginZ();
                    bounds[5] = mf.getOriginZ() + mf.getGridSizeZ() * mf.getVoxelSize();
                    ret_val.setGridBounds(bounds);
                
                    List<Channel> channels = mf.getChannels();
                
                    for(Channel chan : channels) {
        if (chan.getType().getId() == Channel.Type.DENSITY.getId()) {
            SlicesReader sr = new SlicesReader();
            sr.readSlices(ret_val,zip,chan.getSlices(),0,0,mf.getGridSizeY());
        }
                    }
        */
        return null;
    } finally {
        if (zip != null)
            zip.close();
    }
}

From source file:net.sourceforge.jweb.maven.mojo.PropertiesOverideMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (disabled) {
        this.getLog().info("plugin was disabled");
        return;//from w  ww.j  av a 2s .  c o m
    }
    processConfiguration();
    if (replacements.isEmpty()) {
        this.getLog().info("Nothing to replace with");
        return;
    }

    String name = this.builddir.getAbsolutePath() + File.separator + this.finalName + "." + this.packing;//the final package
    this.getLog().debug("final artifact: " + name);// the final package

    try {
        File finalWarFile = new File(name);
        File tempFile = File.createTempFile(finalWarFile.getName(), null);
        tempFile.delete();//check deletion
        boolean renameOk = finalWarFile.renameTo(tempFile);
        if (!renameOk) {
            getLog().error("Can not rename file, please check.");
            return;
        }

        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(finalWarFile));
        ZipFile zipFile = new ZipFile(tempFile);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (acceptMime(entry)) {
                getLog().info("applying replacements for " + entry.getName());
                InputStream inputStream = zipFile.getInputStream(entry);
                String src = IOUtils.toString(inputStream, encoding);
                //do replacement
                for (Entry<String, String> e : replacements.entrySet()) {
                    src = src.replaceAll("#\\{" + e.getKey() + "}", e.getValue());
                }
                out.putNextEntry(new ZipEntry(entry.getName()));
                IOUtils.write(src, out, encoding);
                inputStream.close();
            } else {
                //not repalce, just put entry back to out zip
                out.putNextEntry(entry);
                InputStream inputStream = zipFile.getInputStream(entry);
                byte[] buf = new byte[512];
                int len = -1;
                while ((len = inputStream.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                inputStream.close();
                continue;
            }
        }
        zipFile.close();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}