Example usage for java.util.zip ZipFile ZipFile

List of usage examples for java.util.zip ZipFile ZipFile

Introduction

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

Prototype

public ZipFile(File file) throws ZipException, IOException 

Source Link

Document

Opens a ZIP file for reading given the specified File object.

Usage

From source file:com.mgmtp.jfunk.common.util.Configuration.java

private void readObject(final ObjectInputStream ois) throws IOException, ClassNotFoundException {
    ois.defaultReadObject();/*  ww  w  . jav a  2s  .  c  o m*/
    String zipFileName = ois.readUTF();
    zipArchive = new ZipFile(zipFileName);
}

From source file:com.asakusafw.runtime.stage.launcher.LauncherOptionsParser.java

private boolean isInclude(File file, String className) {
    try (ZipFile zip = new ZipFile(file)) {
        return zip.getEntry(className.replace('.', '/') + ".class") != null; //$NON-NLS-1$
    } catch (Exception e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug(MessageFormat.format("Exception occurred while detecting for class: file={0}, class={1}", //$NON-NLS-1$
                    file, className), e);
        }//from  ww  w  . java  2 s . com
    }
    return false;
}

From source file:com.sshtools.j2ssh.util.DynamicClassLoader.java

private InputStream loadResourceFromZipfile(File file, String name) {
    try {//from   ww  w  .j  ava  2 s  .  c o m
        ZipFile zipfile = new ZipFile(file);
        ZipEntry entry = zipfile.getEntry(name);

        if (entry != null) {
            return zipfile.getInputStream(entry);
        } else {
            return null;
        }
    } catch (IOException e) {
        return null;
    }
}

From source file:io.promagent.internal.HookMetadataParser.java

/**
 * List all Java classes found in the JAR files.
 *
 *///from   w  w  w  .  j a va  2  s  .com
private static Set<String> listAllJavaClasses(Set<Path> hookJars, Predicate<String> classNameFilter)
        throws IOException {
    Set<String> result = new TreeSet<>();
    for (Path hookJar : hookJars) {
        // For convenient testing, hookJar may be a classes/ directory instead of a JAR file.
        if (hookJar.toFile().isDirectory()) {
            try (Stream<Path> dirEntries = Files.walk(hookJar)) {
                addClassNames(dirEntries.map(hookJar::relativize).map(Path::toString), result, classNameFilter);
            }
        } else if (hookJar.toFile().isFile()) {
            try (ZipFile zipFile = new ZipFile(hookJar.toFile())) {
                addClassNames(zipFile.stream().map(ZipEntry::getName), result, classNameFilter);
            }
        } else {
            throw new IOException(hookJar + ": Failed to read file or directory.");
        }
    }
    return result;
}

From source file:org.talend.mdm.repository.ui.wizards.imports.ImportServerObjectWizard.java

private byte[] extractBar(File barFile) {
    ZipFile zipFile = null;/*from w ww . j  a  v  a 2  s .c o  m*/
    InputStream entryInputStream = null;
    byte[] processBytes = null;
    try {
        zipFile = new ZipFile(barFile);

        for (Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            if (!entry.isDirectory()) {
                if (entry.getName().endsWith(".proc")) { //$NON-NLS-1$
                    entryInputStream = zipFile.getInputStream(entry);
                    processBytes = IOUtils.toByteArray(entryInputStream);
                }
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        if (entryInputStream != null) {
            try {
                entryInputStream.close();
            } catch (IOException e) {
            }
        }
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
            }
        }

    }
    return processBytes;
}

From source file:mobac.mapsources.loader.MapPackManager.java

public int getMapPackRevision(File mapPackFile) throws ZipException, IOException {
    ZipFile zip = new ZipFile(mapPackFile);
    try {/*ww w .ja  v  a2 s  . c  om*/
        ZipEntry entry = zip.getEntry("META-INF/MANIFEST.MF");
        if (entry == null)
            throw new ZipException("Unable to find MANIFEST.MF");
        Manifest mf = new Manifest(zip.getInputStream(entry));
        Attributes a = mf.getMainAttributes();
        String mpv = a.getValue("MapPackRevision").trim();
        return Utilities.parseSVNRevision(mpv);
    } catch (NumberFormatException e) {
        return -1;
    } finally {
        zip.close();
    }
}

From source file:com.web.server.SARDeployer.java

/**
 * This method extracts the SAR archive and configures for the SAR and starts the services
 * @param file/*from  w  ww . j a v a  2 s . com*/
 * @param warDirectoryPath
 * @throws IOException
 */
public void extractSar(File file, String warDirectoryPath) throws IOException {
    ZipFile zip = new ZipFile(file);
    ZipEntry ze = null;
    String fileName = file.getName();
    fileName = fileName.substring(0, fileName.indexOf('.'));
    fileName += "sar";
    String fileDirectory;
    CopyOnWriteArrayList classPath = new CopyOnWriteArrayList();
    Enumeration<? extends ZipEntry> entries = zip.entries();
    int numBytes;
    while (entries.hasMoreElements()) {
        ze = entries.nextElement();
        // //System.out.println("Unzipping " + ze.getName());
        String filePath = deployDirectory + "/" + fileName + "/" + ze.getName();
        if (!ze.isDirectory()) {
            fileDirectory = filePath.substring(0, filePath.lastIndexOf('/'));
        } else {
            fileDirectory = filePath;
        }
        // //System.out.println(fileDirectory);
        createDirectory(fileDirectory);
        if (!ze.isDirectory()) {
            FileOutputStream fout = new FileOutputStream(filePath);
            byte[] inputbyt = new byte[8192];
            InputStream istream = zip.getInputStream(ze);
            while ((numBytes = istream.read(inputbyt, 0, inputbyt.length)) >= 0) {
                fout.write(inputbyt, 0, numBytes);
            }
            fout.close();
            istream.close();
            if (ze.getName().endsWith(".jar")) {
                classPath.add(filePath);
            }
        }
    }
    zip.close();
    URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    URL[] urls = loader.getURLs();
    WebClassLoader sarClassLoader = new WebClassLoader(urls);
    for (int index = 0; index < classPath.size(); index++) {
        System.out.println("file:" + classPath.get(index));
        new WebServer().addURL(new URL("file:" + classPath.get(index)), sarClassLoader);
    }
    new WebServer().addURL(new URL("file:" + deployDirectory + "/" + fileName + "/"), sarClassLoader);
    sarsMap.put(fileName, sarClassLoader);
    System.out.println(sarClassLoader.geturlS());
    try {
        Sar sar = (Sar) sardigester.parse(new InputSource(
                new FileInputStream(deployDirectory + "/" + fileName + "/META-INF/" + "mbean-service.xml")));
        CopyOnWriteArrayList mbeans = sar.getMbean();
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        System.out.println(mbs);
        ObjectName objName;
        for (int index = 0; index < mbeans.size(); index++) {
            Mbean mbean = (Mbean) mbeans.get(index);
            System.out.println(mbean.getObjectname());
            System.out.println(mbean.getCls());
            objName = new ObjectName(mbean.getObjectname());
            Class helloWorldService = sarClassLoader.loadClass(mbean.getCls());
            Object obj = helloWorldService.newInstance();
            if (mbs.isRegistered(objName)) {
                mbs.invoke(objName, "stopService", null, null);
                //mbs.invoke(objName, "destroy", null, null);
                mbs.unregisterMBean(objName);
            }
            mbs.registerMBean(obj, objName);
            CopyOnWriteArrayList attrlist = mbean.getMbeanAttribute();
            if (attrlist != null) {
                for (int count = 0; count < attrlist.size(); count++) {
                    MBeanAttribute attr = (MBeanAttribute) attrlist.get(count);
                    Attribute mbeanattribute = new Attribute(attr.getName(), attr.getValue());
                    mbs.setAttribute(objName, mbeanattribute);
                }
            }
            mbs.invoke(objName, "startService", null, null);
        }
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MalformedObjectNameException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstanceAlreadyExistsException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MBeanRegistrationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NotCompliantMBeanException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstanceNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ReflectionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MBeanException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidAttributeValueException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (AttributeNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:it.greenvulcano.util.zip.ZipHelper.java

/**
 * Performs the uncompression of a <code>zip</code> file, whose name and
 * parent directory are passed as arguments, on the local filesystem. The
 * content of the <code>zip</code> file will be uncompressed within a
 * specified target directory.<br>
 *
 * @param srcDirectory/*ww w  . j a v  a 2  s .  c om*/
 *            the source parent directory of the file/s to be unzipped. Must
 *            be an absolute pathname.
 * @param zipFilename
 *            the name of the file to be unzipped. Cannot contain wildcards.
 * @param targetDirectory
 *            the target directory in which the content of the
 *            <code>zip</code> file will be unzipped. Must be an absolute
 *            pathname.
 * @throws IOException
 *             If any error occurs during file uncompression.
 * @throws IllegalArgumentException
 *             if the arguments are invalid.
 */
public void unzipFile(String srcDirectory, String zipFilename, String targetDirectory) throws IOException {

    File srcDir = new File(srcDirectory);

    if (!srcDir.isAbsolute()) {
        throw new IllegalArgumentException(
                "The pathname of the source parent directory is NOT absolute: " + srcDirectory);
    }

    if (!srcDir.exists()) {
        throw new IllegalArgumentException(
                "Source parent directory " + srcDirectory + " NOT found on local filesystem.");
    }

    if (!srcDir.isDirectory()) {
        throw new IllegalArgumentException("Source parent directory " + srcDirectory + " is NOT a directory.");
    }

    File srcZipFile = new File(srcDirectory, zipFilename);
    if (!srcZipFile.exists()) {
        throw new IllegalArgumentException(
                "File to be unzipped (" + srcZipFile.getAbsolutePath() + ") NOT found on local filesystem.");
    }

    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(srcZipFile);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry currEntry = entries.nextElement();
            if (currEntry.isDirectory()) {
                String targetSubdirPathname = currEntry.getName();
                File dir = new File(targetDirectory, targetSubdirPathname);
                FileUtils.forceMkdir(dir);
                dir.setLastModified(currEntry.getTime());
            } else {
                InputStream is = null;
                OutputStream os = null;
                File file = null;
                try {
                    is = zipFile.getInputStream(currEntry);
                    FileUtils.forceMkdir(new File(targetDirectory, currEntry.getName()).getParentFile());
                    file = new File(targetDirectory, currEntry.getName());
                    os = new FileOutputStream(file);
                    IOUtils.copy(is, os);
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                        }

                        if (os != null) {
                            os.close();
                        }
                    } catch (IOException exc) {
                        // Do nothing
                    }

                    if (file != null) {
                        file.setLastModified(currEntry.getTime());
                    }
                }
            }
        }
    } finally {
        try {
            if (zipFile != null) {
                zipFile.close();
            }
        } catch (Exception exc) {
            // do nothing
        }
    }
}

From source file:com.app.server.SARDeployer.java

/**
 * This method extracts the SAR archive and configures for the SAR and starts the services
 * @param file/* w  w w .jav a2s .  c  o  m*/
 * @param warDirectoryPath
 * @throws IOException
 */
public void extractSarDeploy(ClassLoader cL, Object... args) throws IOException {
    CopyOnWriteArrayList classPath = null;
    File file = null;
    String fileName = "";
    String fileWithPath = "";
    if (args[0] instanceof File) {
        classPath = new CopyOnWriteArrayList();
        file = (File) args[0];
        fileWithPath = file.getAbsolutePath();
        ZipFile zip = new ZipFile(file);
        ZipEntry ze = null;
        fileName = file.getName();
        fileName = fileName.substring(0, fileName.indexOf('.'));
        fileName += "sar";
        String fileDirectory;
        Enumeration<? extends ZipEntry> entries = zip.entries();
        int numBytes;
        while (entries.hasMoreElements()) {
            ze = entries.nextElement();
            // //log.info("Unzipping " + ze.getName());
            String filePath = serverConfig.getDeploydirectory() + "/" + fileName + "/" + ze.getName();
            if (!ze.isDirectory()) {
                fileDirectory = filePath.substring(0, filePath.lastIndexOf('/'));
            } else {
                fileDirectory = filePath;
            }
            // //log.info(fileDirectory);
            createDirectory(fileDirectory);
            if (!ze.isDirectory()) {
                FileOutputStream fout = new FileOutputStream(filePath);
                byte[] inputbyt = new byte[8192];
                InputStream istream = zip.getInputStream(ze);
                while ((numBytes = istream.read(inputbyt, 0, inputbyt.length)) >= 0) {
                    fout.write(inputbyt, 0, numBytes);
                }
                fout.close();
                istream.close();
                if (ze.getName().endsWith(".jar")) {
                    classPath.add(filePath);
                }
            }
        }
        zip.close();
    } else if (args[0] instanceof FileObject) {
        FileObject fileObj = (FileObject) args[0];
        fileName = fileObj.getName().getBaseName();
        try {
            fileWithPath = fileObj.getURL().toURI().toString();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        fileName = fileName.substring(0, fileName.indexOf('.'));
        fileName += "sar";
        classPath = unpack(fileObj, new File(serverConfig.getDeploydirectory() + "/" + fileName + "/"),
                (StandardFileSystemManager) args[1]);
    }
    URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    URL[] urls = loader.getURLs();
    WebClassLoader sarClassLoader;
    if (cL != null) {
        sarClassLoader = new WebClassLoader(urls, cL);
    } else {
        sarClassLoader = new WebClassLoader(urls);
    }
    for (int index = 0; index < classPath.size(); index++) {
        // log.info("file:"+classPath.get(index));
        sarClassLoader.addURL(new URL("file:" + classPath.get(index)));
    }
    sarClassLoader.addURL(new URL("file:" + serverConfig.getDeploydirectory() + "/" + fileName + "/"));
    //log.info(sarClassLoader.geturlS());
    sarsMap.put(fileWithPath, sarClassLoader);
    try {
        Sar sar = (Sar) sardigester.parse(new InputSource(new FileInputStream(
                serverConfig.getDeploydirectory() + "/" + fileName + "/META-INF/" + "mbean-service.xml")));
        CopyOnWriteArrayList mbeans = sar.getMbean();
        //log.info(mbeanServer);
        ObjectName objName, classLoaderObjectName = new ObjectName("com.app.server:classLoader=" + fileName);
        if (!mbeanServer.isRegistered(classLoaderObjectName)) {
            mbeanServer.registerMBean(sarClassLoader, classLoaderObjectName);
        } else {
            mbeanServer.unregisterMBean(classLoaderObjectName);
            mbeanServer.registerMBean(sarClassLoader, classLoaderObjectName);
            ;
        }
        for (int index = 0; index < mbeans.size(); index++) {
            Mbean mbean = (Mbean) mbeans.get(index);
            //log.info(mbean.getObjectname());
            //log.info(mbean.getCls());
            objName = new ObjectName(mbean.getObjectname());
            Class service = sarClassLoader.loadClass(mbean.getCls());
            if (mbeanServer.isRegistered(objName)) {
                //mbs.invoke(objName, "stopService", null, null);
                //mbs.invoke(objName, "destroy", null, null);
                mbeanServer.unregisterMBean(objName);
            }
            mbeanServer.createMBean(service.getName(), objName, classLoaderObjectName);
            //mbs.registerMBean(obj, objName);
            CopyOnWriteArrayList attrlist = mbean.getMbeanAttribute();
            if (attrlist != null) {
                for (int count = 0; count < attrlist.size(); count++) {
                    MBeanAttribute attr = (MBeanAttribute) attrlist.get(count);
                    Attribute mbeanattribute = new Attribute(attr.getName(), attr.getValue());
                    mbeanServer.setAttribute(objName, mbeanattribute);
                }
            }
            Attribute mbeanattribute = new Attribute("ObjectName", objName);
            mbeanServer.setAttribute(objName, mbeanattribute);
            if (((String) mbeanServer.getAttribute(objName, "Deployer")).equals("true")) {
                mbeanServer.invoke(objName, "init", new Object[] { deployerList },
                        new String[] { Vector.class.getName() });

            }
            mbeanServer.invoke(objName, "init", new Object[] { serviceList, serverConfig, mbeanServer },
                    new String[] { Vector.class.getName(), ServerConfig.class.getName(),
                            MBeanServer.class.getName() });
            mbeanServer.invoke(objName, "start", null, null);
            serviceListObjName.put(fileWithPath, objName);
        }
    } catch (Exception e) {
        log.error("Could not able to deploy sar archive " + fileWithPath, e);
        // TODO Auto-generated catch block
        //e.printStackTrace();
    }
}

From source file:com.dsh105.commodus.data.Updater.java

/**
 * Part of Zip-File-Extractor, modified by Gravity for use with Bukkit
 */// w  w w .  jav  a  2  s  . c  o  m
private void unzip(String file) {
    try {
        final File fSourceZip = new File(file);
        final String zipPath = file.substring(0, file.length() - 4);
        ZipFile zipFile = new ZipFile(fSourceZip);
        Enumeration<? extends ZipEntry> e = zipFile.entries();
        while (e.hasMoreElements()) {
            ZipEntry entry = e.nextElement();
            File destinationFilePath = new File(zipPath, entry.getName());
            destinationFilePath.getParentFile().mkdirs();
            if (entry.isDirectory()) {
                continue;
            } else {
                final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                int b;
                final byte buffer[] = new byte[Updater.BYTE_SIZE];
                final FileOutputStream fos = new FileOutputStream(destinationFilePath);
                final BufferedOutputStream bos = new BufferedOutputStream(fos, Updater.BYTE_SIZE);
                while ((b = bis.read(buffer, 0, Updater.BYTE_SIZE)) != -1) {
                    bos.write(buffer, 0, b);
                }
                bos.flush();
                bos.close();
                bis.close();
                final String name = destinationFilePath.getName();
                if (name.endsWith(".jar") && this.pluginFile(name)) {
                    destinationFilePath.renameTo(
                            new File(this.plugin.getDataFolder().getParent(), this.updateFolder + "/" + name));
                }
            }
            entry = null;
            destinationFilePath = null;
        }
        e = null;
        zipFile.close();
        zipFile = null;

        // Move any plugin data folders that were included to the right place, Bukkit won't do this for us.
        for (final File dFile : new File(zipPath).listFiles()) {
            if (dFile.isDirectory()) {
                if (this.pluginFile(dFile.getName())) {
                    final File oFile = new File(this.plugin.getDataFolder().getParent(), dFile.getName()); // Get current dir
                    final File[] contents = oFile.listFiles(); // List of existing files in the current dir
                    for (final File cFile : dFile.listFiles()) // Loop through all the files in the new dir
                    {
                        boolean found = false;
                        for (final File xFile : contents) // Loop through contents to see if it exists
                        {
                            if (xFile.getName().equals(cFile.getName())) {
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            // Move the new file into the current dir
                            cFile.renameTo(new File(oFile.getCanonicalFile() + "/" + cFile.getName()));
                        } else {
                            // This file already exists, so we don't need it anymore.
                            cFile.delete();
                        }
                    }
                }
            }
            dFile.delete();
        }
        new File(zipPath).delete();
        fSourceZip.delete();
    } catch (final IOException ex) {
        this.plugin.getLogger()
                .warning("The auto-updater tried to unzip a new update file, but was unsuccessful.");
        this.result = Updater.UpdateResult.FAIL_DOWNLOAD;
        ex.printStackTrace();
    }
    new File(file).delete();
}