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:org.apache.solr.handler.admin.ConfigSetsHandler.java

private void handleConfigUploadRequest(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
    String configSetName = req.getParams().get(NAME);
    if (StringUtils.isBlank(configSetName)) {
        throw new SolrException(ErrorCode.BAD_REQUEST,
                "The configuration name should be provided in the \"name\" parameter");
    }//from  w ww  .j ava  2  s  .  c  om

    SolrZkClient zkClient = coreContainer.getZkController().getZkClient();
    String configPathInZk = ZkConfigManager.CONFIGS_ZKNODE + Path.SEPARATOR + configSetName;

    if (zkClient.exists(configPathInZk, true)) {
        throw new SolrException(ErrorCode.BAD_REQUEST,
                "The configuration " + configSetName + " already exists in zookeeper");
    }

    Iterator<ContentStream> contentStreamsIterator = req.getContentStreams().iterator();

    if (!contentStreamsIterator.hasNext()) {
        throw new SolrException(ErrorCode.BAD_REQUEST, "No stream found for the config data to be uploaded");
    }

    InputStream inputStream = contentStreamsIterator.next().getStream();

    // Create a node for the configuration in zookeeper
    boolean trusted = getTrusted(req);
    zkClient.makePath(configPathInZk,
            ("{\"trusted\": " + Boolean.toString(trusted) + "}").getBytes(StandardCharsets.UTF_8), true);

    ZipInputStream zis = new ZipInputStream(inputStream, StandardCharsets.UTF_8);
    ZipEntry zipEntry = null;
    while ((zipEntry = zis.getNextEntry()) != null) {
        String filePathInZk = configPathInZk + "/" + zipEntry.getName();
        if (zipEntry.isDirectory()) {
            zkClient.makePath(filePathInZk, true);
        } else {
            createZkNodeIfNotExistsAndSetData(zkClient, filePathInZk, IOUtils.toByteArray(zis));
        }
    }
    zis.close();
}

From source file:at.ac.tuwien.big.testsuite.impl.task.UnzipTaskImpl.java

private void unzip(File zipFile, File baseDirectory, boolean extractContainedZipFiles,
        Collection<Exception> exceptions) {
    try (ZipFile zip = new ZipFile(zipFile)) {
        addTotalWork(zip.size());// w w  w  .  jav  a2s  .c  o  m
        Enumeration<? extends ZipEntry> entries = zip.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            String escapedEntryName = escapeFileName(entry.getName());
            File entryFile = new File(baseDirectory, escapedEntryName);

            if (entry.isDirectory()) {
                if (!contains(entryFile.getAbsolutePath(), ignoredDirectories)) {
                    entryFile.mkdir();
                }
            } else if (!endsWith(entryFile.getName(), ignoredExtensions)
                    && !contains(entryFile.getAbsolutePath(), ignoredDirectories)) {
                if (entryFile.getAbsolutePath().indexOf(File.separatorChar,
                        baseDirectory.getAbsolutePath().length()) > -1) {
                    // Only create dirs if file is not in the root dir
                    entryFile.getParentFile().mkdirs();
                }

                try (InputStream is = zip.getInputStream(entry);
                        OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(entryFile))) {
                    copyInputStream(is, outputStream);
                }

                if (extractContainedZipFiles && (escapedEntryName.toLowerCase().endsWith(".zip")
                        || escapedEntryName.toLowerCase().endsWith(".war"))) {
                    String zipFileName = escapedEntryName;
                    File zipFileBaseDir = new File(baseDirectory,
                            zipFileName.substring(0, zipFileName.length() - 4));
                    zipFileBaseDir.mkdir();

                    unzip(entryFile, zipFileBaseDir, false, exceptions);
                    entryFile.delete();
                } else if (extractContainedZipFiles && (escapedEntryName.toLowerCase().endsWith(".tar")
                        || escapedEntryName.toLowerCase().endsWith(".gz"))) {
                    String zipFileName = escapedEntryName;
                    int offset = escapedEntryName.toLowerCase().endsWith(".tar") ? 4 : 0;
                    offset = escapedEntryName.toLowerCase().endsWith(".tar.gz") ? 7 : offset;
                    File zipFileBaseDir = new File(baseDirectory,
                            zipFileName.substring(0, zipFileName.length() - offset));
                    zipFileBaseDir.mkdir();

                    untar(entryFile, zipFileBaseDir, exceptions,
                            escapedEntryName.toLowerCase().endsWith(".tar.gz"));
                    entryFile.delete();
                } else if (extractContainedZipFiles && escapedEntryName.toLowerCase().endsWith(".rar")) {
                    String zipFileName = escapedEntryName;
                    File zipFileBaseDir = new File(baseDirectory,
                            zipFileName.substring(0, zipFileName.length() - 4));
                    zipFileBaseDir.mkdir();

                    unrar(entryFile, zipFileBaseDir, exceptions);
                    entryFile.delete();
                }
            }

            addDoneWork(1);
        }
    } catch (Exception ex) {
        exceptions.add(ex);
    }
}

From source file:com.theaetetuslabs.apkmakertester.ApkMakerService.java

private boolean unpackZip(String pathToZip, String destPath) {
    new File(destPath).mkdirs();
    InputStream is;/*  ww  w . j av  a 2 s.  c  o  m*/
    ZipInputStream zis;
    try {
        String filename;
        is = new FileInputStream(pathToZip);
        zis = new ZipInputStream(new BufferedInputStream(is));
        ZipEntry ze;
        byte[] buffer = new byte[1024];
        int count;

        while ((ze = zis.getNextEntry()) != null) {
            // zapis do souboru
            filename = ze.getName();

            // Need to create directories if not exists, or
            // it will generate an Exception...
            if (ze.isDirectory()) {
                File fmd = new File(destPath, filename);
                fmd.mkdirs();
                continue;
            }

            FileOutputStream fout = new FileOutputStream(new File(destPath, filename));

            // cteni zipu a zapis
            while ((count = zis.read(buffer)) != -1) {
                fout.write(buffer, 0, count);
            }

            fout.close();
            zis.closeEntry();
        }

        zis.close();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:com.axelor.apps.base.service.imports.importer.Importer.java

protected void unZip(File file, File directory) throws ZipException, IOException {

    File extractFile = null;//  w  w  w  .j a  va  2 s . c o m
    FileOutputStream fileOutputStream = null;
    ZipFile zipFile = new ZipFile(file);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();

    while (entries.hasMoreElements()) {
        try {
            ZipEntry entry = entries.nextElement();
            InputStream entryInputStream = zipFile.getInputStream(entry);
            byte[] buffer = new byte[1024];
            int bytesRead = 0;

            extractFile = new File(directory, entry.getName());
            if (entry.isDirectory()) {
                extractFile.mkdirs();
                continue;
            } else {
                extractFile.getParentFile().mkdirs();
                extractFile.createNewFile();
            }

            fileOutputStream = new FileOutputStream(extractFile);
            while ((bytesRead = entryInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }

        } catch (IOException ioException) {
            log.error(ioException.getMessage());
            continue;
        } finally {
            if (fileOutputStream == null) {
                continue;
            }
            try {
                fileOutputStream.close();
            } catch (IOException e) {
            }
        }
    }

    zipFile.close();

}

From source file:org.arquillian.warp.ftest.installation.ContainerInstaller.java

private void unzip(InputStream inputStream, File destination, boolean overwrite) {
    try {//from  w w  w.  j a va  2s  .  co m
        byte[] buf = new byte[1024];
        ZipInputStream zipinputstream = null;
        ZipEntry zipentry;
        zipinputstream = new ZipInputStream(inputStream);

        zipentry = zipinputstream.getNextEntry();
        while (zipentry != null) {
            int n;
            FileOutputStream fileoutputstream;
            File newFile = new File(destination, zipentry.getName());
            if (zipentry.isDirectory()) {
                newFile.mkdirs();
                zipentry = zipinputstream.getNextEntry();
                continue;
            }

            if (newFile.exists() && overwrite) {
                log.info("Overwriting " + newFile);
                newFile.delete();
            }

            fileoutputstream = new FileOutputStream(newFile);

            while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
                fileoutputstream.write(buf, 0, n);
            }

            fileoutputstream.close();
            zipinputstream.closeEntry();
            zipentry = zipinputstream.getNextEntry();

        }

        zipinputstream.close();
    } catch (Exception e) {
        throw new IllegalStateException("Can't unzip input stream", e);
    }
}

From source file:net.daboross.bukkitdev.skywars.world.WorldUnzipper.java

public void doWorldUnzip(Logger logger) throws StartupFailedException {
    Validate.notNull(logger, "Logger cannot be null");
    Path outputDir = Bukkit.getWorldContainer().toPath().resolve(Statics.BASE_WORLD_NAME);
    if (Files.exists(outputDir)) {
        return;//from w  w  w  .  j ava  2 s. c om
    }
    try {
        Files.createDirectories(outputDir);
    } catch (IOException e) {
        throw new StartupFailedException("Couldn't create directory " + outputDir.toAbsolutePath() + ".");
    }

    InputStream fis = WorldUnzipper.class.getResourceAsStream(Statics.ZIP_FILE_PATH);
    if (fis == null) {
        throw new StartupFailedException("Couldn't get resource.\nError creating world. Please delete "
                + Statics.BASE_WORLD_NAME + " and restart server.");
    }
    try {
        try (ZipInputStream zis = new ZipInputStream(fis)) {
            ZipEntry ze = zis.getNextEntry();
            while (ze != null) {
                String fileName = ze.getName();
                Path newFile = outputDir.resolve(fileName);
                Path parent = newFile.getParent();
                if (parent != null) {
                    Files.createDirectories(parent);
                }
                if (ze.isDirectory()) {
                    logger.log(Level.FINER, "Making dir {0}", newFile);
                    Files.createDirectories(newFile);
                } else if (Files.exists(newFile)) {
                    logger.log(Level.FINER, "Already exists {0}", newFile);
                } else {
                    logger.log(Level.FINER, "Copying {0}", newFile);
                    try (FileOutputStream fos = new FileOutputStream(newFile.toFile())) {
                        try {
                            int next;
                            while ((next = zis.read()) != -1) {
                                fos.write(next);
                            }
                            fos.flush();
                        } catch (IOException ex) {
                            logger.log(Level.WARNING, "Error copying file from zip", ex);
                            throw new StartupFailedException("Error creating world. Please delete "
                                    + Statics.BASE_WORLD_NAME + " and restart server.");
                        }
                        fos.close();
                    }
                }
                try {
                    ze = zis.getNextEntry();
                } catch (IOException ex) {
                    throw new StartupFailedException(
                            "Error getting next zip entry\nError creating world. Please delete "
                                    + Statics.BASE_WORLD_NAME + " and restart server.",
                            ex);
                }
            }
        }
    } catch (IOException | RuntimeException ex) {
        throw new StartupFailedException(
                "\nError unzipping world. Please delete " + Statics.BASE_WORLD_NAME + " and restart server.",
                ex);
    }
}

From source file:com.haha01haha01.harail.DatabaseDownloader.java

private boolean unpackZip(File output_dir, File zipname) {
    InputStream is;//from   w  w  w  .j  ava2s  . c o  m
    ZipInputStream zis;
    try {
        String filename;
        is = new FileInputStream(zipname);
        zis = new ZipInputStream(new BufferedInputStream(is));
        ZipEntry ze;
        byte[] buffer = new byte[1024];
        int count;

        while ((ze = zis.getNextEntry()) != null) {
            filename = ze.getName();

            // Need to create directories if not exists, or
            // it will generate an Exception...
            if (ze.isDirectory()) {
                File fmd = new File(output_dir, filename);
                fmd.mkdirs();
                continue;
            }

            FileOutputStream fout = new FileOutputStream(new File(output_dir, filename));

            while ((count = zis.read(buffer)) != -1) {
                fout.write(buffer, 0, count);
            }

            fout.close();
            zis.closeEntry();
        }

        zis.close();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:com.taobao.android.builder.tasks.app.databinding.AwbDataBindingMergeArtifactsTask.java

private void extractBinFilesFromJar(File outFolder, File jarFile) throws IOException {
    File jarOutFolder = getOutFolderForJarFile(outFolder, jarFile);
    FileUtils.deleteQuietly(jarOutFolder);
    FileUtils.forceMkdir(jarOutFolder);//  w  ww.j  a va 2  s . c  o  m

    try (Closer localCloser = Closer.create()) {
        FileInputStream fis = localCloser.register(new FileInputStream(jarFile));
        ZipInputStream zis = localCloser.register(new ZipInputStream(fis));
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            if (entry.isDirectory()) {
                continue;
            }

            String name = entry.getName();

            if (!isResource(name)) {
                continue;
            }
            // get rid of the path. We don't need it since the file name includes the domain
            name = new File(name).getName();
            File out = new File(jarOutFolder, name);
            //noinspection ResultOfMethodCallIgnored
            FileOutputStream fos = localCloser.register(new FileOutputStream(out));
            ByteStreams.copy(zis, fos);
            zis.closeEntry();
        }
    }
}

From source file:edu.stanford.epadd.launcher.Splash.java

private static void copyResourcesRecursively(String sourceDirectory, String writeDirectory) throws IOException {
    final URL dirURL = ePADD.class.getClassLoader().getResource(sourceDirectory);
    //final String path = sourceDirectory.substring( 1 );

    if ((dirURL != null) && dirURL.getProtocol().equals("jar")) {
        final JarURLConnection jarConnection = (JarURLConnection) dirURL.openConnection();
        //System.out.println( "jarConnection is " + jarConnection );

        final ZipFile jar = jarConnection.getJarFile();

        final Enumeration<? extends ZipEntry> entries = jar.entries(); // gives ALL entries in jar

        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            final String name = entry.getName();
            // System.out.println( name );
            if (!name.startsWith(sourceDirectory)) {
                // entry in wrong subdir -- don't copy
                continue;
            }//from   w ww .j  a va  2 s.c om
            final String entryTail = name.substring(sourceDirectory.length());

            final File f = new File(writeDirectory + File.separator + entryTail);
            if (entry.isDirectory()) {
                // if its a directory, create it
                final boolean bMade = f.mkdir();
                System.out.println((bMade ? "  creating " : "  unable to create ") + name);
            } else {
                System.out.println("  writing  " + name);
                final InputStream is = jar.getInputStream(entry);
                final OutputStream os = new BufferedOutputStream(new FileOutputStream(f));
                final byte buffer[] = new byte[4096];
                int readCount;
                // write contents of 'is' to 'os'
                while ((readCount = is.read(buffer)) > 0) {
                    os.write(buffer, 0, readCount);
                }
                os.close();
                is.close();
            }
        }

    } else if (dirURL == null) {
        throw new IllegalStateException("can't find " + sourceDirectory + " on the classpath");
    } else {
        // not a "jar" protocol URL
        throw new IllegalStateException("don't know how to handle extracting from " + dirURL);
    }
}

From source file:com.adobe.acs.commons.it.build.ScrMetadataIT.java

private DescriptorList parseJar(InputStream is, boolean checkNs) throws Exception {
    DescriptorList result = new DescriptorList();

    try (ZipInputStream zis = new ZipInputStream(is)) {
        ZipEntry entry = zis.getNextEntry();
        while (entry != null) {
            if (!entry.isDirectory() && entry.getName().endsWith(".xml")) {
                if (entry.getName().startsWith("OSGI-INF/metatype")) {
                    result.merge(parseMetatype(new InputStreamFacade(zis), entry.getName()));
                } else if (entry.getName().startsWith("OSGI-INF/")) {
                    result.merge(parseScr(new InputStreamFacade(zis), entry.getName(), checkNs));
                }//from   ww w  .  ja  v  a  2  s .co m
            }

            entry = zis.getNextEntry();
        }
    }

    return result;
}