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:io.github.jeremgamer.preview.actions.Download.java

private void download() {

    GeneralSave gs = new GeneralSave();
    try {//from  ww  w  . j  a  va 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:JarResources.java

public JarResources(String jarFileName) throws Exception {
    this.jarFileName = jarFileName;
    ZipFile zf = new ZipFile(jarFileName);
    Enumeration e = zf.entries();
    while (e.hasMoreElements()) {
        ZipEntry ze = (ZipEntry) e.nextElement();

        htSizes.put(ze.getName(), new Integer((int) ze.getSize()));
    }/*from   w  w  w.  j a  v a2  s  .  c o  m*/
    zf.close();

    // extract resources and put them into the hashtable.
    FileInputStream fis = new FileInputStream(jarFileName);
    BufferedInputStream bis = new BufferedInputStream(fis);
    ZipInputStream zis = new ZipInputStream(bis);
    ZipEntry ze = null;
    while ((ze = zis.getNextEntry()) != null) {
        if (ze.isDirectory()) {
            continue;
        }

        int size = (int) ze.getSize();
        // -1 means unknown size.
        if (size == -1) {
            size = ((Integer) htSizes.get(ze.getName())).intValue();
        }

        byte[] b = new byte[(int) size];
        int rb = 0;
        int chunk = 0;
        while (((int) size - rb) > 0) {
            chunk = zis.read(b, rb, (int) size - rb);
            if (chunk == -1) {
                break;
            }
            rb += chunk;
        }

        htJarContents.put(ze.getName(), b);
    }
}

From source file:com.ibm.jaggr.core.util.ZipUtil.java

/**
 * Extracts the specified zip file to the specified location. If {@code selector} is specified,
 * then only the entry specified by {@code selector} (if {@code selector} is a filename) or the
 * contents of the directory specified by {@code selector} (if {@code selector} is a directory
 * name) will be extracted. If {@code selector} specifies a directory, then the contents of the
 * directory in the zip file will be rooted at {@code destDir} when extracted.
 *
 * @param zipFile/*from  www .ja  va 2s  .c o  m*/
 *            the {@link File} object for the file to unzip
 * @param destDir
 *            the {@link File} object for the target directory
 * @param selector
 *            The name of a file or directory to extract
 * @throws IOException
 */
public static void unzip(File zipFile, File destDir, String selector) throws IOException {
    final String sourceMethod = "unzip"; //$NON-NLS-1$
    final boolean isTraceLogging = log.isLoggable(Level.FINER);
    if (isTraceLogging) {
        log.entering(sourceClass, sourceMethod, new Object[] { zipFile, destDir });
    }

    boolean selectorIsFolder = selector != null && selector.charAt(selector.length() - 1) == '/';
    ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFile));
    try {
        ZipEntry entry = zipIn.getNextEntry();
        // iterates over entries in the zip file
        while (entry != null) {
            String entryName = entry.getName();
            if (selector == null || !selectorIsFolder && entryName.equals(selector) || selectorIsFolder
                    && entryName.startsWith(selector) && entryName.length() != selector.length()) {
                if (selector != null) {
                    if (selectorIsFolder) {
                        // selector is a directory.  Strip selected path
                        entryName = entryName.substring(selector.length());
                    } else {
                        // selector is a filename.  Extract the filename portion of the path
                        int idx = entryName.lastIndexOf("/"); //$NON-NLS-1$
                        if (idx != -1) {
                            entryName = entryName.substring(idx + 1);
                        }
                    }
                }
                File file = new File(destDir, entryName.replace("/", File.separator)); //$NON-NLS-1$
                if (!entry.isDirectory()) {
                    // if the entry is a file, extract it
                    extractFile(entry, zipIn, file);
                } else {
                    // if the entry is a directory, make the directory
                    extractDirectory(entry, file);
                }
                zipIn.closeEntry();
            }
            entry = zipIn.getNextEntry();
        }
    } finally {
        zipIn.close();
    }

    if (isTraceLogging) {
        log.exiting(sourceClass, sourceMethod);
    }
}

From source file:com.arcusys.liferay.vaadinplugin.VaadinUpdater.java

private String exctractZipFile(File vaadinZipFile, String tmpPath) throws IOException {
    byte[] buf = new byte[1024];
    String zipDestinationPath = tmpPath + fileSeparator + "unzip" + fileSeparator;
    File unzipDirectory = new File(zipDestinationPath);
    if (!unzipDirectory.mkdir()) {
        log.warn("Zip extract failed.");
        upgradeListener.updateFailed("Zip extract failed: Can not create directory " + zipDestinationPath);
        return null;
    }//from www.j a v  a2 s. c  o m

    ZipInputStream zinstream = new ZipInputStream(new FileInputStream(vaadinZipFile.getAbsolutePath()));
    ZipEntry zentry = zinstream.getNextEntry();

    while (zentry != null) {
        String entryName = zentry.getName();
        if (zentry.isDirectory()) {
            File newFile = new File(zipDestinationPath + entryName);
            if (!newFile.mkdir()) {
                break;
            }
            zentry = zinstream.getNextEntry();
            continue;
        }
        outputLog.log("Extracting " + entryName);
        FileOutputStream outstream = new FileOutputStream(
                zipDestinationPath + getFileNameWithoutVersion(entryName));
        int n;

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

        outputLog.log("Successfully Extracted File Name : " + entryName);
        outstream.close();

        zinstream.closeEntry();
        zentry = zinstream.getNextEntry();
    }
    zinstream.close();

    return zipDestinationPath;
}

From source file:Main.java

public static boolean unzip(InputStream inputStream, String dest, boolean replaceIfExists) {

    final int BUFFER_SIZE = 4096;

    BufferedOutputStream bufferedOutputStream = null;

    boolean succeed = true;

    try {//  w w w .j ava2s  . c om
        ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream));
        ZipEntry zipEntry;

        while ((zipEntry = zipInputStream.getNextEntry()) != null) {

            String zipEntryName = zipEntry.getName();

            //             if(!zipEntry.isDirectory()) {
            //                 File fil = new File(dest + zipEntryName);
            //                 fil.getParent()
            //             }

            // file exists ? delete ?
            File file2 = new File(dest + zipEntryName);

            if (file2.exists()) {
                if (replaceIfExists) {

                    try {
                        boolean b = deleteDir(file2);
                        if (!b) {
                            Log.e("Haggle", "Unzip failed to delete " + dest + zipEntryName);
                        } else {
                            Log.d("Haggle", "Unzip deleted " + dest + zipEntryName);
                        }
                    } catch (Exception e) {
                        Log.e("Haggle", "Unzip failed to delete " + dest + zipEntryName, e);
                    }
                }
            }

            // extract
            File file = new File(dest + zipEntryName);

            if (file.exists()) {

            } else {
                if (zipEntry.isDirectory()) {
                    file.mkdirs();
                    chmod(file, 0755);

                } else {

                    // create parent file folder if not exists yet
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                        chmod(file.getParentFile(), 0755);
                    }

                    byte buffer[] = new byte[BUFFER_SIZE];
                    bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file), BUFFER_SIZE);
                    int count;

                    while ((count = zipInputStream.read(buffer, 0, BUFFER_SIZE)) != -1) {
                        bufferedOutputStream.write(buffer, 0, count);
                    }

                    bufferedOutputStream.flush();
                    bufferedOutputStream.close();
                }
            }

            // enable standalone python
            if (file.getName().endsWith(".so") || file.getName().endsWith(".xml")
                    || file.getName().endsWith(".py") || file.getName().endsWith(".pyc")
                    || file.getName().endsWith(".pyo")) {
                chmod(file, 0755);
            }

            Log.d("Haggle", "Unzip extracted " + dest + zipEntryName);
        }

        zipInputStream.close();

    } catch (FileNotFoundException e) {
        Log.e("Haggle", "Unzip error, file not found", e);
        succeed = false;
    } catch (Exception e) {
        Log.e("Haggle", "Unzip error: ", e);
        succeed = false;
    }

    return succeed;
}

From source file:com.datos.vfs.provider.zip.ZipFileSystem.java

@Override
public void init() throws FileSystemException {
    super.init();

    try {//  ww w .j a  v a  2  s  . c om
        // Build the index
        final List<ZipFileObject> strongRef = new ArrayList<>(getZipFile().size());
        final Enumeration<? extends ZipEntry> entries = getZipFile().entries();
        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            final AbstractFileName name = (AbstractFileName) getFileSystemManager().resolveName(getRootName(),
                    UriParser.encode(entry.getName()));

            // Create the file
            ZipFileObject fileObj;
            if (entry.isDirectory() && getFileFromCache(name) != null) {
                fileObj = (ZipFileObject) getFileFromCache(name);
                fileObj.setZipEntry(entry);
                continue;
            }

            fileObj = createZipFileObject(name, entry);
            putFileToCache(fileObj);
            strongRef.add(fileObj);
            fileObj.holdObject(strongRef);

            // Make sure all ancestors exist
            // TODO - create these on demand
            ZipFileObject parent;
            for (AbstractFileName parentName = (AbstractFileName) name
                    .getParent(); parentName != null; fileObj = parent, parentName = (AbstractFileName) parentName
                            .getParent()) {
                // Locate the parent
                parent = (ZipFileObject) getFileFromCache(parentName);
                if (parent == null) {
                    parent = createZipFileObject(parentName, null);
                    putFileToCache(parent);
                    strongRef.add(parent);
                    parent.holdObject(strongRef);
                }

                // Attach child to parent
                parent.attachChild(fileObj.getName());
            }
        }
    } finally {
        closeCommunicationLink();
    }
}

From source file:org.chromium.APKPackager.java

private void extractToFolder(File zipfile, File tempdir) {
    InputStream inputStream = null;
    try {//from  w  w w. ja va2 s  . co  m
        FileInputStream zipStream = new FileInputStream(zipfile);
        inputStream = new BufferedInputStream(zipStream);
        ZipInputStream zis = new ZipInputStream(inputStream);
        inputStream = zis;

        ZipEntry ze;
        byte[] buffer = new byte[32 * 1024];

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

            if (ze.isDirectory()) {
                File dir = new File(tempdir, compressedName);
                dir.mkdirs();
            } else {
                File file = new File(tempdir, compressedName);
                file.getParentFile().mkdirs();
                if (file.exists() || file.createNewFile()) {
                    FileOutputStream fout = new FileOutputStream(file);
                    int count;
                    while ((count = zis.read(buffer)) != -1) {
                        fout.write(buffer, 0, count);
                    }
                    fout.close();
                }
            }
            zis.closeEntry();
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "Unzip error ", e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:io.fabric8.forge.camel.commands.CamelNewComponentsCommand.java

private String findComponentFQCN(String component, String selectedVersion) {
    String result = null;//from   w w  w  .  j a  va2 s.c  om
    InputStream stream = null;
    try {
        File tmp = File.createTempFile("camel-dep", "jar");
        URL url = new URL(String.format("https://repo1.maven.org/maven2/org/apache/camel/%s/%s/%s-%s.jar",
                component, selectedVersion, component, selectedVersion));

        FileUtils.copyURLToFile(url, tmp);

        ZipFile zipFile = new ZipFile(tmp);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.getName().startsWith("META-INF/services/org/apache/camel/component/")
                    && !entry.isDirectory()) {
                stream = zipFile.getInputStream(entry);
                Properties prop = new Properties();
                prop.load(stream);
                result = prop.getProperty("class");
                break;
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Unable to inspect added component", e);
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (Exception e) {
            }
        }
    }
    return result;
}

From source file:org.artifactory.webapp.wicket.page.importexport.repos.ImportZipPanel.java

@Override
public void onFileSaved(File file) {
    ZipInputStream zipinputstream = null;
    FileOutputStream fos = null;//from w  w w  .  j av  a  2  s .  co  m
    File uploadedFile = null;
    File destFolder;
    try {
        uploadedFile = uploadForm.getUploadedFile();
        zipinputstream = new ZipInputStream(new FileInputStream(uploadedFile));
        ArtifactoryHome artifactoryHome = ContextHelper.get().getArtifactoryHome();
        destFolder = new File(artifactoryHome.getTempUploadDir(), uploadedFile.getName() + "_extract");
        FileUtils.deleteDirectory(destFolder);

        byte[] buf = new byte[DEFAULT_BUFF_SIZE];
        ZipEntry zipentry;

        zipentry = zipinputstream.getNextEntry();
        while (zipentry != null) {
            //for each entry to be extracted
            String entryName = zipentry.getName();
            File destFile = new File(destFolder, entryName);

            if (zipentry.isDirectory()) {
                if (!destFile.exists()) {
                    if (!destFile.mkdirs()) {
                        error("Cannot create directory " + destFolder);
                        return;
                    }
                }
            } else {
                fos = new FileOutputStream(destFile);
                int n;
                while ((n = zipinputstream.read(buf, 0, DEFAULT_BUFF_SIZE)) > -1) {
                    fos.write(buf, 0, n);
                }
                fos.close();
            }
            zipinputstream.closeEntry();
            zipentry = zipinputstream.getNextEntry();
        } //while

        setImportFromPath(destFolder);
        getImportForm().setVisible(true);
    } catch (Exception e) {
        String errorMessage = "Error during import of " + uploadedFile;
        String systemLogsPage = WicketUtils.absoluteMountPathForPage(SystemLogsPage.class);
        String logs = ". Please review the <a href=\"" + systemLogsPage + "\">log</a> for further information.";
        error(new UnescapedFeedbackMessage(errorMessage + logs));
        log.error(errorMessage, e);
        onException();
    } finally {
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(zipinputstream);
        FileUtils.deleteQuietly(uploadedFile);
    }
}

From source file:com.meltmedia.cadmium.core.util.WarUtils.java

/**
 * <p>This method updates a template war with the following settings.</p>
 * @param templateWar The name of the template war to pull from the classpath.
 * @param war The path of an external war to update (optional).
 * @param newWarNames The name to give the new war. (note: only the first element of this list is used.)
 * @param repoUri The uri to a github repo to pull content from.
 * @param branch The branch of the github repo to pull content from.
 * @param configRepoUri The uri to a github repo to pull config from.
 * @param configBranch The branch of the github repo to pull config from.
 * @param domain The domain to bind a vHost to.
 * @param context The context root that this war will deploy to.
 * @param secure A flag to set if this war needs to have its contents password protected.
 * @throws Exception//from  w  w  w.j  a  v  a  2 s.  c o m
 */
public static void updateWar(String templateWar, String war, List<String> newWarNames, String repoUri,
        String branch, String configRepoUri, String configBranch, String domain, String context, boolean secure,
        Logger log) throws Exception {
    ZipFile inZip = null;
    ZipOutputStream outZip = null;
    InputStream in = null;
    OutputStream out = null;
    try {
        if (war != null) {
            if (war.equals(newWarNames.get(0))) {
                File tmpZip = File.createTempFile(war, null);
                tmpZip.delete();
                tmpZip.deleteOnExit();
                new File(war).renameTo(tmpZip);
                war = tmpZip.getAbsolutePath();
            }
            inZip = new ZipFile(war);
        } else {
            File tmpZip = File.createTempFile("cadmium-war", "war");
            tmpZip.delete();
            tmpZip.deleteOnExit();
            in = WarUtils.class.getClassLoader().getResourceAsStream(templateWar);
            out = new FileOutputStream(tmpZip);
            FileSystemManager.streamCopy(in, out);
            inZip = new ZipFile(tmpZip);
        }
        outZip = new ZipOutputStream(new FileOutputStream(newWarNames.get(0)));

        ZipEntry cadmiumPropertiesEntry = null;
        cadmiumPropertiesEntry = inZip.getEntry("WEB-INF/cadmium.properties");

        Properties cadmiumProps = updateProperties(inZip, cadmiumPropertiesEntry, repoUri, branch,
                configRepoUri, configBranch);

        ZipEntry jbossWeb = null;
        jbossWeb = inZip.getEntry("WEB-INF/jboss-web.xml");

        Enumeration<? extends ZipEntry> entries = inZip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry e = entries.nextElement();
            if (e.getName().equals(cadmiumPropertiesEntry.getName())) {
                storeProperties(outZip, cadmiumPropertiesEntry, cadmiumProps, newWarNames);
            } else if (((domain != null && domain.length() > 0) || (context != null && context.length() > 0))
                    && e.getName().equals(jbossWeb.getName())) {
                updateDomain(inZip, outZip, jbossWeb, domain, context);
            } else if (secure && e.getName().equals("WEB-INF/web.xml")) {
                addSecurity(inZip, outZip, e);
            } else {
                outZip.putNextEntry(e);
                if (!e.isDirectory()) {
                    FileSystemManager.streamCopy(inZip.getInputStream(e), outZip, true);
                }
                outZip.closeEntry();
            }
        }
    } finally {
        if (FileSystemManager.exists("tmp_cadmium-war.war")) {
            new File("tmp_cadmium-war.war").delete();
        }
        try {
            if (inZip != null) {
                inZip.close();
            }
        } catch (Exception e) {
            if (log != null) {
                log.error("Failed to close " + war);
            }
        }
        try {
            if (outZip != null) {
                outZip.close();
            }
        } catch (Exception e) {
            if (log != null) {
                log.error("Failed to close " + newWarNames.get(0));
            }
        }
        try {
            if (out != null) {
                out.close();
            }
        } catch (Exception e) {
        }
        try {
            if (in != null) {
                in.close();
            }
        } catch (Exception e) {
        }
    }

}