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:org.devproof.portal.core.module.theme.service.ThemeServiceImpl.java

@Override
public void install(File themeArchive) {
    String uuid = UUID.randomUUID().toString();
    try {//w  w  w.jav  a2  s. co m
        File folder = new File(servletContext.getRealPath("/WEB-INF/themes"));
        folder = new File(folder.toString() + File.separator + uuid);
        FileUtils.forceMkdir(folder);
        ZipFile zipFile = new ZipFile(themeArchive);

        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File out = new File(folder.getAbsolutePath() + File.separator + entry.getName());
            if (entry.isDirectory()) {
                FileUtils.forceMkdir(out);
            } else {
                FileUtils.touch(out);
                FileOutputStream fos = new FileOutputStream(out, false);
                IOUtils.copy(zipFile.getInputStream(entry), fos);
                fos.close();
            }
        }
        zipFile.close();
        logger.info("New theme installed: " + uuid);
    } catch (MalformedURLException e) {
        logger.warn("Unknown error", e);
    } catch (IOException e) {
        logger.warn("Unknown error", e);
    }
}

From source file:com.ning.maven.plugins.duplicatefinder.DuplicateFinderMojo.java

/**
 * Calculates the SHA256 Hash of a class in a file.
 * //from   w  w  w.  j  a  v  a2s.c om
 * @param file the archive contains the class
 * @param resourcePath the name of the class
 * @return the MD% Hash as Hex-Value
 * @throws IOException if any error occurs on reading class in archive
 */
private String getSHA256HexOfElement(final File file, final String resourcePath) throws IOException {
    class Sha256CacheKey {
        final File file;
        final String resourcePath;

        Sha256CacheKey(File file, String resourcePath) {
            this.file = file;
            this.resourcePath = resourcePath;
        }

        public boolean equals(Object o) {
            if (this == o)
                return true;
            if (o == null || getClass() != o.getClass())
                return false;

            Sha256CacheKey key = (Sha256CacheKey) o;

            return file.equals(key.file) && resourcePath.equals(key.resourcePath);
        }

        public int hashCode() {
            return 31 * file.hashCode() + resourcePath.hashCode();
        }
    }

    final Sha256CacheKey key = new Sha256CacheKey(file, resourcePath);
    if (CACHED_SHA256.containsKey(key)) {
        return (String) CACHED_SHA256.get(key);
    }

    ZipFile zip = new ZipFile(file);
    ZipEntry zipEntry = zip.getEntry(resourcePath);
    if (zipEntry == null) {
        throw new IOException("Could not found Zip-Entry for " + resourcePath + " in file " + file);
    }

    String sha256;

    InputStream in = zip.getInputStream(zipEntry);
    try {
        sha256 = DigestUtils.sha256Hex(in);
    } finally {
        IOUtils.closeQuietly(in);
    }

    CACHED_SHA256.put(key, sha256);

    return sha256;
}

From source file:de.dfki.km.perspecting.obie.corpus.LabeledTextCorpus.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.getEntry(URLDecoder.decode(entryName[entryName.length - 1], "utf-8"));

        if (entry != null) {
            log.info("found labels for: " + uri.toString());
        } else {/*from  w  ww .  ja v a  2s .c  om*/
            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:com.github.chenxiaolong.dualbootpatcher.switcher.service.BootUIActionTask.java

/**
 * Get currently installed version of boot UI
 *
 * @param iface Mbtool interface//from   w  w w  . j  av  a2 s  .c  o  m
 * @return The {@link Version} installed or null if an error occurs or the version number is
 *         invalid
 * @throws IOException
 * @throws MbtoolException
 */
@Nullable
private Version getCurrentVersion(MbtoolInterface iface) throws IOException, MbtoolException {
    String mountPoint = getCacheMountPoint(iface);
    String zipPath = mountPoint + MAPPINGS[0].target;

    File tempZip = new File(getContext().getCacheDir() + "/bootui.zip");
    tempZip.delete();

    try {
        iface.pathCopy(zipPath, tempZip.getAbsolutePath());
        iface.pathChmod(tempZip.getAbsolutePath(), 0644);

        // Set SELinux label
        try {
            String label = iface.pathSelinuxGetLabel(tempZip.getParent(), false);
            iface.pathSelinuxSetLabel(tempZip.getAbsolutePath(), label, false);
        } catch (MbtoolCommandException e) {
            Log.w(TAG, tempZip + ": Failed to set SELinux label", e);
        }
    } catch (MbtoolCommandException e) {
        return null;
    }

    ZipFile zf = null;
    String versionStr = null;
    String gitVersionStr = null;

    try {
        zf = new ZipFile(tempZip);

        final Enumeration<? extends ZipEntry> entries = zf.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry ze = entries.nextElement();

            if (ze.getName().equals(PROPERTIES_FILE)) {
                Properties prop = new Properties();
                prop.load(zf.getInputStream(ze));
                versionStr = prop.getProperty(PROP_VERSION);
                gitVersionStr = prop.getProperty(PROP_GIT_VERSION);
                break;
            }
        }
    } catch (IOException e) {
        Log.e(TAG, "Failed to read bootui.zip", e);
    } finally {
        if (zf != null) {
            try {
                zf.close();
            } catch (IOException e) {
                // Ignore
            }
        }

        tempZip.delete();
    }

    Log.d(TAG, "Boot UI version: " + versionStr);
    Log.d(TAG, "Boot UI git version: " + gitVersionStr);

    if (versionStr != null) {
        return Version.from(versionStr);
    } else {
        return null;
    }
}

From source file:io.github.jeremgamer.preview.actions.Download.java

private void download() {

    GeneralSave gs = new GeneralSave();
    try {//from   www  .java 2  s  .  c om
        gs.load(new File("projects/" + Editor.getProjectName() + "/general.rbd"));
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    name = gs.getString("name");
    new Thread(new Runnable() {

        @Override
        public void run() {
            if (url == null) {

            } else {
                File archive = new File(System.getProperty("user.home") + "/AppData/Roaming/.rocketbuilder/"
                        + name + "/data.zip");
                File outputFolder = new File(
                        System.getProperty("user.home") + "/AppData/Roaming/.rocketbuilder/" + name);

                new File(System.getProperty("user.home") + "/AppData/Roaming/.rocketbuilder/" + name).mkdirs();
                URL webFile;
                try {
                    webFile = new URL(url);
                    ReadableByteChannel rbc = Channels.newChannel(webFile.openStream());
                    fos = new FileOutputStream(System.getProperty("user.home")
                            + "/AppData/Roaming/.rocketbuilder/" + name + "/data.zip");
                    HttpURLConnection httpConn = (HttpURLConnection) webFile.openConnection();
                    totalBytes = httpConn.getContentLength();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                while (bytesCopied < totalBytes) {
                                    for (CustomProgressBar bar : barList) {
                                        bytesCopied = fos.getChannel().size();
                                        progressValue = (int) (100 * bytesCopied / totalBytes);
                                        bar.setValue(progressValue);
                                        if (bar.isStringPainted()) {
                                            bar.setString(progressValue + "%     " + bytesCopied / 1000 + "/"
                                                    + totalBytes / 1000 + "Kb     tape " + step + "/2");
                                        }
                                    }
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }

                    }).start();
                    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
                    fos.close();
                    step = 2;
                    for (CustomProgressBar bar : barList) {
                        if (bar.isStringPainted()) {
                            bar.setString("tape " + step + "/2 : Extraction");
                        }
                    }

                    for (int timeout = 100; timeout > 0; timeout--) {
                        RandomAccessFile ran = null;

                        try {
                            ran = new RandomAccessFile(archive, "rw");
                            break;
                        } catch (Exception ex) {
                        } finally {
                            if (ran != null)
                                try {
                                    ran.close();
                                } catch (IOException ex) {
                                }

                            ran = null;
                        }

                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException ex) {
                        }
                    }

                    ZipFile zipFile = new ZipFile(archive, Charset.forName("Cp437"));
                    Enumeration<? extends ZipEntry> entries = zipFile.entries();
                    while (entries.hasMoreElements()) {
                        ZipEntry entry = entries.nextElement();
                        File entryDestination = new File(outputFolder, entry.getName());
                        entryDestination.getParentFile().mkdirs();
                        if (entry.isDirectory())
                            entryDestination.mkdirs();
                        else {
                            InputStream in = zipFile.getInputStream(entry);
                            OutputStream out = new FileOutputStream(entryDestination);
                            IOUtils.copy(in, out);
                            IOUtils.closeQuietly(in);
                            IOUtils.closeQuietly(out);
                            in.close();
                            out.close();
                        }
                    }

                    for (CustomProgressBar bar : barList) {
                        bar.setString("");
                    }

                    zipFile.close();
                    archive.delete();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }).start();
}

From source file:biz.c24.io.spring.batch.writer.C24ItemWriterTests.java

@Test
public void testZipFileWrite() throws Exception {

    // Get somewhere temporary to write out to
    File outputFile = File.createTempFile("ItemWriterTest-", ".csv.zip");
    outputFile.deleteOnExit();/*from   ww w. ja  va 2  s.c o  m*/
    String outputFileName = outputFile.getAbsolutePath();

    // Configure the ItemWriter
    C24ItemWriter itemWriter = new C24ItemWriter();
    itemWriter.setSink(new TextualSink());
    itemWriter.setWriterSource(new ZipFileWriterSource());
    itemWriter.setup(getStepExecution(outputFileName));
    // Write the employees out
    itemWriter.write(employees);
    // Close the file
    itemWriter.cleanup();

    // Check that we wrote out what was expected
    ZipFile zipFile = new ZipFile(outputFileName);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    assertNotNull(entries);
    // Make sure there's at least one entry
    assertTrue(entries.hasMoreElements());
    ZipEntry entry = entries.nextElement();
    // Make sure that the trailing .zip has been removed and the leading path has been removed
    assertFalse(entry.getName().contains(System.getProperty("file.separator")));
    assertFalse(entry.getName().endsWith(".zip"));
    // Make sure that there aren't any other entries
    assertFalse(entries.hasMoreElements());

    try {
        compareCsv(zipFile.getInputStream(entry), employees);
    } finally {
        if (zipFile != null) {
            zipFile.close();
        }
    }
}

From source file:UnpackedJarFile.java

public static void unzipToDirectory(ZipFile zipFile, File destDir) throws IOException {
    Enumeration entries = zipFile.entries();
    try {/*from   w  w  w  .ja  v a2 s.  c o m*/
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            if (entry.isDirectory()) {
                File dir = new File(destDir, entry.getName());
                createDirectory(dir);
            } else {
                File file = new File(destDir, entry.getName());
                createDirectory(file.getParentFile());
                OutputStream out = null;
                InputStream in = null;
                try {
                    out = new BufferedOutputStream(new FileOutputStream(file));
                    in = zipFile.getInputStream(entry);
                    writeAll(in, out);
                } finally {
                    if (null != out) {
                        out.close();
                    }
                    if (null != in) {
                        in.close();
                    }
                }
            }
        }
    } finally {
        zipFile.close();
    }
}

From source file:biz.c24.io.spring.batch.writer.C24ItemWriterTests.java

@Test
public void testResourceZipFileWrite() throws Exception {

    // Get somewhere temporary to write out to
    File outputFile = File.createTempFile("ItemWriterTest-", ".csv.zip");
    outputFile.deleteOnExit();//from   w ww.ja v a 2 s. c o m
    String outputFileName = outputFile.getAbsolutePath();

    ZipFileWriterSource source = new ZipFileWriterSource();
    source.setResource(new FileSystemResource(outputFileName));

    // Configure the ItemWriter
    C24ItemWriter itemWriter = new C24ItemWriter();
    itemWriter.setSink(new TextualSink());
    itemWriter.setWriterSource(source);
    itemWriter.setup(getStepExecution(null));
    // Write the employees out
    itemWriter.write(employees);
    // Close the file
    itemWriter.cleanup();

    // Check that we wrote out what was expected
    ZipFile zipFile = new ZipFile(outputFileName);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    assertNotNull(entries);
    // Make sure there's at least one entry
    assertTrue(entries.hasMoreElements());
    ZipEntry entry = entries.nextElement();
    // Make sure that the trailing .zip has been removed and the leading path has been removed
    assertFalse(entry.getName().contains(System.getProperty("file.separator")));
    assertFalse(entry.getName().endsWith(".zip"));
    // Make sure that there aren't any other entries
    assertFalse(entries.hasMoreElements());

    try {
        compareCsv(zipFile.getInputStream(entry), employees);
    } finally {
        if (zipFile != null) {
            zipFile.close();
        }
    }
}

From source file:edu.cmu.tetrad.util.TetradSerializableUtils.java

/**
 * Deserializes examplars stored in archives in getArchiveDirectory().
 *
 * @throws RuntimeException if clazz cannot be serialized. This exception
 *                          has an informative message and wraps the
 *                          originally thrown exception as root cause.
 * @see #getArchiveDirectory()/*from  ww w . ja  va  2 s .  c  om*/
 */
public void deserializeArchivedVersions() throws RuntimeException {
    System.out.println("Deserializing archived instances in " + getArchiveDirectory() + ".");

    File archive = new File(getArchiveDirectory());

    if (!archive.exists() || !archive.isDirectory()) {
        return;
    }

    String[] listing = archive.list();

    for (String archiveName : listing) {
        if (!(archiveName.endsWith(".zip"))) {
            continue;
        }

        try {
            File file = new File(getArchiveDirectory(), archiveName);
            ZipFile zipFile = new ZipFile(file);
            ZipEntry entry = zipFile.getEntry("class_fields.ser");
            InputStream inputStream = zipFile.getInputStream(entry);
            ObjectInputStream objectIn = new ObjectInputStream(inputStream);
            Map<String, List<String>> classFields = (Map<String, List<String>>) objectIn.readObject();
            zipFile.close();

            for (String className : classFields.keySet()) {

                //                    if (classFields.equals("HypotheticalGraph")) continue;

                List<String> fieldNames = classFields.get(className);
                Class<?> clazz = Class.forName(className);
                ObjectStreamClass streamClass = ObjectStreamClass.lookup(clazz);

                if (streamClass == null) {
                    System.out.println();
                }

                for (String fieldName : fieldNames) {
                    assert streamClass != null;
                    ObjectStreamField field = streamClass.getField(fieldName);

                    if (field == null) {
                        throw new RuntimeException("Field '" + fieldName + "' was dropped from class '"
                                + className + "' as a serializable field! Please " + "put it back!!!"
                                + "\nIt used to be in " + className + " in this archive: " + archiveName + ".");
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Could not read class_fields.ser in archive + " + archiveName + " .", e);
        } catch (IOException e) {
            throw new RuntimeException("Problem reading archive" + archiveName + "; see cause.", e);
        }

        System.out.println("...Deserializing instances in " + archiveName + "...");
        ZipEntry zipEntry = null;

        try {
            File file = new File(getArchiveDirectory(), archiveName);
            FileInputStream in = new FileInputStream(file);
            ZipInputStream zipinputstream = new ZipInputStream(in);

            while ((zipEntry = zipinputstream.getNextEntry()) != null) {
                if (!zipEntry.getName().endsWith(".ser")) {
                    continue;
                }

                ObjectInputStream objectIn = new ObjectInputStream(zipinputstream);
                objectIn.readObject();
                zipinputstream.closeEntry();
            }

            zipinputstream.close();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(
                    "Could not read object zipped file " + zipEntry.getName() + " in archive " + archiveName
                            + ". " + "Perhaps the class was renamed, moved to another package, or "
                            + "removed. In any case, please put it back where it was.",
                    e);
        } catch (IOException e) {
            throw new RuntimeException("Problem reading archive" + archiveName + "; see cause.", e);
        }
    }

    System.out.println("Finished deserializing archived instances.");
}

From source file:com.aurel.track.util.PluginUtils.java

/**
 * Unzip this file into the given directory. If the zipFile is called "zipFile.zip",
 * the files will be placed into "targetDir/zipFile".
 * @param zipFile//from  ww w  .jav a2  s  . c  om
 * @param targetDir
 */
public static void unzipFileIntoDirectory(File zipFile, File targetDir) {
    try {
        LOGGER.debug("Expanding Genji extension file " + zipFile.getName());
        int BUFFER = 2048;
        File file = zipFile;
        ZipFile zip = new ZipFile(file);
        String newPath = targetDir + File.separator
                + zipFile.getName().substring(0, zipFile.getName().length() - 4);
        new File(newPath).mkdir();
        Enumeration zipFileEntries = zip.entries();
        // Process each entry
        while (zipFileEntries.hasMoreElements()) {
            // grab a zip file entry
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            String currentEntry = entry.getName();
            File destFile = new File(newPath, currentEntry);
            //destFile = new File(newPath, destFile.getName());
            File destinationParent = destFile.getParentFile();
            // create the parent directory structure if needed
            destinationParent.mkdirs();
            if (!entry.isDirectory()) {
                BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
                int currentByte;
                // establish buffer for writing file
                byte data[] = new byte[BUFFER];
                // write the current file to disk
                LOGGER.debug("Unzipping " + destFile.getAbsolutePath());
                FileOutputStream fos = new FileOutputStream(destFile);
                BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
                // read and write until last byte is encountered
                while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, currentByte);
                }
                dest.flush();
                dest.close();
                is.close();
            }
        }
    } catch (Exception e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    }
}