Example usage for java.util.zip ZipEntry isDirectory

List of usage examples for java.util.zip ZipEntry isDirectory

Introduction

In this page you can find the example usage for java.util.zip ZipEntry isDirectory.

Prototype

public boolean isDirectory() 

Source Link

Document

Returns true if this is a directory entry.

Usage

From source file:nl.strohalm.cyclos.themes.ThemeHandlerImpl.java

@Override
protected void doSelect(final String fileName) {
    ZipFile zipFile = null;//from   ww w .ja  v  a2  s . c  o m
    final LocalSettings settings = settingsService.getLocalSettings();
    final String charset = settings.getCharset();
    try {
        final File file = realFile(fileName);
        if (!file.exists()) {
            throw new ThemeNotFoundException(fileName);
        }
        zipFile = new ZipFile(file);

        // Ensure the properties entry exists
        properties(zipFile);

        // Find all currently used images by style
        final Map<String, Collection<String>> imagesByFile = new HashMap<String, Collection<String>>();
        final File imageDir = webImageHelper.imagePath(Image.Nature.STYLE);
        final File[] cssFiles = imageDir.listFiles(STYLE_FILTER);
        for (final File css : cssFiles) {
            final String contents = FileUtils.readFileToString(css, charset);
            final List<String> urls = CSSHelper.resolveURLs(contents);
            imagesByFile.put(css.getName(), urls);
        }

        // Read the files
        final Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            // We will not handle directories
            if (entry.isDirectory()) {
                continue;
            }
            final String name = entry.getName();
            final String entryFileName = new File(name).getName();
            if (name.startsWith("images/")) {
                final ImageType type = ImageType.getByFileName(entryFileName);
                // Save the image
                final Image image = imageService.save(Image.Nature.STYLE, type, entryFileName,
                        zipFile.getInputStream(entry));
                // Update the physical image
                webImageHelper.update(image);
            } else if (name.startsWith("styles/")) {
                // Save the style sheet
                CustomizedFile customizedFile = new CustomizedFile();
                customizedFile.setName(entryFileName);
                customizedFile.setType(CustomizedFile.Type.STYLE);
                final String contents = IOUtils.toString(zipFile.getInputStream(entry), charset);
                customizedFile.setContents(contents);
                final File originalFile = customizationHelper.originalFileOf(Type.STYLE, entryFileName);
                if (originalFile.exists()) {
                    customizedFile.setOriginalContents(FileUtils.readFileToString(originalFile, charset));
                }
                customizedFile = customizedFileService.saveForTheme(customizedFile);

                // Update the physical file
                final File physicalFile = customizationHelper.customizedFileOf(CustomizedFile.Type.STYLE,
                        entryFileName);
                customizationHelper.updateFile(physicalFile, customizedFile);

                // Remove images that are no longer used
                final List<String> newImages = CSSHelper.resolveURLs(contents);
                final Collection<String> oldImages = imagesByFile.get(entryFileName);
                if (CollectionUtils.isNotEmpty(oldImages)) {
                    for (final String imageName : oldImages) {
                        if (!newImages.contains(imageName)) {
                            // No longer used. Remove it
                            imageService.removeStyleImage(imageName);
                            // Remove the physical file
                            final File imageFile = new File(imageDir, imageName);
                            customizationHelper.deleteFile(imageFile);
                        }
                    }
                }
            }
        }
    } catch (final ThemeException e) {
        throw e;
    } catch (final Exception e) {
        throw new ThemeException(e);
    } finally {
        try {
            zipFile.close();
        } catch (final Exception e) {
            // Ignore
        }
    }
}

From source file:edu.indiana.d2i.htrc.dataapi.DataAPIWrapper.java

private static void openZipStream(InputStream inputStream, Map<String, Map<String, String>> volPageContents,
        boolean isConcat) throws IOException {
    ZipInputStream zipInputStream = new ZipInputStream(inputStream);
    ZipEntry zipEntry = null;
    String currentVolID = null;//from  w  w  w . jav a2 s  . c  om

    if (!isConcat) {
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            String name = zipEntry.getName();

            /**
             * check whether encounter ERROR.err
             */
            if (ERROR_FNAME.equals(name)) {
                log.error("Encountered ERROR.err file in the zip stream");
                // log the content of ERROR.err file
                log.error("*************** Start of Content of ERROR.err ***************");
                StringBuilder sb = new StringBuilder();
                BufferedReader reader = new BufferedReader(new InputStreamReader(zipInputStream));
                String line = null;
                while ((line = reader.readLine()) != null)
                    sb.append(line + "\n");

                log.error(sb.toString());
                log.error("*************** End of Content of ERROR.err ***************");

                continue;
            }

            if (zipEntry.isDirectory()) {
                // get volume name
                currentVolID = name.split("/")[0];
                volPageContents.put(currentVolID, new HashMap<String, String>());

                if (log.isDebugEnabled())
                    log.debug("Encounter volueme directory : " + currentVolID);

            } else {
                String[] names = name.split("/");

                // each page is a separate entry
                //               assert names.length == 2;
                //               assert names[0].equals(currentVolID);

                // get page(s) content
                StringBuilder sb = new StringBuilder();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(zipInputStream, Charset.forName("UTF-8")));
                String line = null;
                while ((line = reader.readLine()) != null)
                    sb.append(line + "\n");

                Map<String, String> contents = volPageContents.get(currentVolID);

                int idx = names[1].indexOf(".txt");
                //               assert idx != -1;

                contents.put(names[1].substring(0, idx), sb.toString());
            }
        }
    } else {
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            assert !zipEntry.isDirectory();
            String name = zipEntry.getName();

            /**
             * check whether encounter ERROR.err
             */
            if (ERROR_FNAME.equals(name)) {
                log.error("Encountered ERROR.err file in the zip stream");
                // log the content of ERROR.err file
                log.error("*************** Start of Content of ERROR.err ***************");
                StringBuilder sb = new StringBuilder();
                BufferedReader reader = new BufferedReader(new InputStreamReader(zipInputStream));
                String line = null;
                while ((line = reader.readLine()) != null)
                    sb.append(line + "\n");

                log.error(sb.toString());
                log.error("*************** End of Content of ERROR.err ***************");

                continue;
            }

            int idx = name.indexOf(".txt");
            //            assert idx != -1;
            String cleanedVolId = name.substring(0, idx);

            if (log.isDebugEnabled())
                log.debug("Encounter volueme whole entry : " + cleanedVolId);

            StringBuilder sb = new StringBuilder();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(zipInputStream, Charset.forName("UTF-8")));
            String line = null;
            while ((line = reader.readLine()) != null)
                sb.append(line + "\n");

            HashMap<String, String> concatContent = new HashMap<String, String>();
            concatContent.put(DataAPIWrapper.WHOLE_CONTENT, sb.toString());
            volPageContents.put(cleanedVolId, concatContent);
        }
    }
}

From source file:net.minecraftforge.gradle.util.ZipFileTree.java

public void visit(FileVisitor visitor) {
    if (!zipFile.exists()) {
        DeprecationLogger.nagUserOfDeprecatedBehaviour(String.format(
                "The specified zip file %s does not exist and will be silently ignored", getDisplayName()));
        return;//from  w  ww  . j a va2 s .c  o  m
    }
    if (!zipFile.isFile()) {
        throw new InvalidUserDataException(
                String.format("Cannot expand %s as it is not a file.", getDisplayName()));
    }

    AtomicBoolean stopFlag = new AtomicBoolean();

    try {
        ZipFile zip = new ZipFile(zipFile);
        try {
            // The iteration order of zip.getEntries() is based on the hash of the zip entry. This isn't much use
            // to us. So, collect the entries in a map and iterate over them in alphabetical order.
            Map<String, ZipEntry> entriesByName = new TreeMap<String, ZipEntry>();
            Enumeration<? extends ZipEntry> entries = zip.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                entriesByName.put(entry.getName(), entry);
            }
            Iterator<ZipEntry> sortedEntries = entriesByName.values().iterator();
            while (!stopFlag.get() && sortedEntries.hasNext()) {
                ZipEntry entry = sortedEntries.next();
                if (entry.isDirectory()) {
                    visitor.visitDir(new DetailsImpl(entry, zip, stopFlag));
                } else {
                    visitor.visitFile(new DetailsImpl(entry, zip, stopFlag));
                }
            }
        } finally {
            zip.close();
        }
    } catch (Exception e) {
        throw new GradleException(String.format("Could not expand %s.", getDisplayName()), e);
    }
}

From source file:com.dbi.jmmerge.MapController.java

private Map<String, File> extractFilesFromZipUpload(MultipartFile file) throws IOException {
    Map<String, File> ret = new HashMap<>();
    String baseDirName = null;//  ww  w  . j  a  va  2s.  c om
    //First catalog it, to see what we've got.
    File temp = File.createTempFile("map", null);
    temp.deleteOnExit();
    file.transferTo(temp);
    ZipInputStream zipin = new ZipInputStream(new FileInputStream(temp));
    ZipEntry entry = zipin.getNextEntry();
    byte[] buf = new byte[1024];
    do {
        FileOutputStream out = null;
        String filename = entry.getName();
        if (isJunkEntry(entry.getName()) || entry.isDirectory()) {
            continue;
        }
        try {
            ret.put(filename, File.createTempFile(filename, null));
            LOG.debug("Incoming timestamp on zip - " + filename + " - " + entry.getTime());
            ret.get(filename).deleteOnExit();
            out = new FileOutputStream(ret.get(filename));
            IOUtils.copy(zipin, out);
            ret.get(filename).setLastModified(entry.getTime());
        } finally {
            // we must always close the output file
            if (out != null)
                out.close();
        }
    } while ((entry = zipin.getNextEntry()) != null);
    baseDirName = tryToGuessBaseDir(ret.keySet());
    if (baseDirName != null) {
        for (String key : new HashSet<String>(ret.keySet())) {
            ret.put(key.replace(baseDirName + "/", ""), ret.remove(key));
        }
    }
    return ret;
}

From source file:com.yunmel.syncretic.utils.io.IOUtils.java

/**
 * ZIPZIPdescFileName//from   w ww.j  a v  a 2 s .  c  o m
 * 
 * @param zipFileName ?ZIP
 * @param descFileName 
 */
public static boolean unZipFiles(String zipFileName, String descFileName) {
    String descFileNames = descFileName;
    if (!descFileNames.endsWith(File.separator)) {
        descFileNames = descFileNames + File.separator;
    }
    try {
        // ?ZIPZipFile
        ZipFile zipFile = new ZipFile(zipFileName);
        ZipEntry entry = null;
        String entryName = null;
        String descFileDir = null;
        byte[] buf = new byte[4096];
        int readByte = 0;
        // ?ZIPentry
        @SuppressWarnings("rawtypes")
        Enumeration enums = zipFile.entries();
        // ??entry
        while (enums.hasMoreElements()) {
            entry = (ZipEntry) enums.nextElement();
            // entry??
            entryName = entry.getName();
            descFileDir = descFileNames + entryName;
            if (entry.isDirectory()) {
                // entry
                new File(descFileDir).mkdirs();
                continue;
            } else {
                // entry
                new File(descFileDir).getParentFile().mkdirs();
            }
            File file = new File(descFileDir);
            // ?
            OutputStream os = new FileOutputStream(file);
            // ZipFileentry?
            InputStream is = zipFile.getInputStream(entry);
            while ((readByte = is.read(buf)) != -1) {
                os.write(buf, 0, readByte);
            }
            os.close();
            is.close();
        }
        zipFile.close();
        log.debug("?!");
        return true;
    } catch (Exception e) {
        log.debug("" + e.getMessage());
        return false;
    }
}

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

private boolean unzipFileIntoDirectory(File file, File dest) {
    try {/*from w w  w. ja  v a  2 s  . c  om*/
        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.esminis.server.library.service.server.installpackage.InstallerPackage.java

private void install(Context context, File file, File targetDirectory) throws Throwable {
    sendBroadcast(context, STATE_INSTALL, 0);
    InputStream input = null;/*w  w w  .  j a v a 2s .  c o  m*/
    ZipInputStream zip = null;
    try {
        zip = new ZipInputStream(input = new FileInputStream(file));
        ZipEntry entry;
        int totalEntries = 0;
        while (zip.getNextEntry() != null) {
            totalEntries++;
        }
        zip.close();
        input.close();
        zip = new ZipInputStream(input = new FileInputStream(file));
        int position = 0;
        while ((entry = zip.getNextEntry()) != null) {
            if (entry.isDirectory()) {
                final File directory = new File(targetDirectory, entry.getName());
                if (!directory.isDirectory() && !directory.mkdirs()) {
                    throw new IOException("Cannot create directory: " + directory.getAbsolutePath());
                }
            } else {
                install(targetDirectory, entry.getName(), zip);
            }
            sendBroadcast(context, STATE_INSTALL, ((float) ++position / (float) totalEntries) * 0.99f);
        }
    } finally {
        if (zip != null) {
            try {
                zip.close();
            } catch (IOException ignored) {
            }
        }
        if (input != null) {
            try {
                input.close();
            } catch (IOException ignored) {
            }
        }
    }
    onInstallComplete(context);
    sendBroadcast(context, STATE_INSTALL, 1);
}

From source file:com.izforge.izpack.util.SelfModifier.java

/**
 * @throws IOException if an error occured
 *///from   ww  w.  j a va 2  s  .  c  o m
private void extractJarFile() throws IOException {
    int extracted = 0;
    InputStream in = null;
    String MANIFEST = "META-INF/MANIFEST.MF";
    JarFile jar = new JarFile(jarFile, true);

    try {
        Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                continue;
            }

            String pathname = entry.getName();
            if (MANIFEST.equals(pathname.toUpperCase())) {
                continue;
            }

            in = jar.getInputStream(entry);
            FileUtils.copyToFile(in, new File(sandbox, pathname));

            extracted++;
        }
        log("Extracted " + extracted + " file" + (extracted > 1 ? "s" : "") + " into " + sandbox.getPath());
    } finally {
        try {
            jar.close();
        } catch (IOException ignore) {
        }
        IOUtils.closeQuietly(in);
    }
}

From source file:gov.nasa.jpl.mudrod.main.MudrodEngine.java

private String decompressSVMWithSGDModel(String archiveName) throws IOException {

    URL scmArchive = getClass().getClassLoader().getResource(archiveName);
    if (scmArchive == null) {
        throw new IOException("Unable to locate " + archiveName + " as a classpath resource.");
    }/*from w  w  w. ja  va  2s  .c om*/
    File tempDir = Files.createTempDirectory("mudrod").toFile();
    assert tempDir.setWritable(true);
    File archiveFile = new File(tempDir, archiveName);
    FileUtils.copyURLToFile(scmArchive, archiveFile);

    // Decompress archive
    int BUFFER_SIZE = 512000;
    ZipInputStream zipIn = new ZipInputStream(new FileInputStream(archiveFile));
    ZipEntry entry;
    while ((entry = zipIn.getNextEntry()) != null) {
        File f = new File(tempDir, entry.getName());
        // If the entry is a directory, create the directory.
        if (entry.isDirectory() && !f.exists()) {
            boolean created = f.mkdirs();
            if (!created) {
                LOG.error("Unable to create directory '{}', during extraction of archive contents.",
                        f.getAbsolutePath());
            }
        } else if (!entry.isDirectory()) {
            boolean created = f.getParentFile().mkdirs();
            if (!created && !f.getParentFile().exists()) {
                LOG.error("Unable to create directory '{}', during extraction of archive contents.",
                        f.getParentFile().getAbsolutePath());
            }
            int count;
            byte data[] = new byte[BUFFER_SIZE];
            FileOutputStream fos = new FileOutputStream(new File(tempDir, entry.getName()), false);
            try (BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE)) {
                while ((count = zipIn.read(data, 0, BUFFER_SIZE)) != -1) {
                    dest.write(data, 0, count);
                }
            }
        }
    }

    return new File(tempDir, StringUtils.removeEnd(archiveName, ".zip")).toURI().toString();
}

From source file:org.apache.reef.runtime.azbatch.evaluator.EvaluatorShim.java

private void extractFiles(final File zipFile) throws IOException {
    try (ZipFile zipFileHandle = new ZipFile(zipFile)) {
        Enumeration<? extends ZipEntry> zipEntries = zipFileHandle.entries();
        while (zipEntries.hasMoreElements()) {
            ZipEntry zipEntry = zipEntries.nextElement();
            File file = new File(this.reefFileNames.getREEFFolderName() + '/' + zipEntry.getName());
            if (file.exists()) {
                LOG.log(Level.INFO, "Skipping entry {0} because the file already exists.", zipEntry.getName());
            } else {
                if (zipEntry.isDirectory()) {
                    if (file.mkdirs()) {
                        LOG.log(Level.INFO, "Creating directory {0}.", zipEntry.getName());
                    } else {
                        LOG.log(Level.INFO, "Directory {0} already exists. Ignoring.", zipEntry.getName());
                    }/*from w w  w.j av  a 2 s  .  c  o m*/
                } else {
                    try (InputStream inputStream = zipFileHandle.getInputStream(zipEntry)) {
                        LOG.log(Level.INFO, "Extracting {0}.", zipEntry.getName());
                        Files.copy(inputStream,
                                Paths.get(this.reefFileNames.getREEFFolderName() + '/' + zipEntry.getName()));
                        LOG.log(Level.INFO, "Extracting {0} completed.", zipEntry.getName());
                    }
                }
            }
        }
    }
}