Example usage for java.util.zip ZipEntry getName

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

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the entry.

Usage

From source file:com.glaf.core.util.ZipUtils.java

public static void unzip(File zipFile, String dir) throws Exception {
    File file = new File(dir);
    FileUtils.mkdirsWithExistsCheck(file);
    FileInputStream fileInputStream = null;
    ZipInputStream zipInputStream = null;
    FileOutputStream fileoutputstream = null;
    BufferedOutputStream bufferedoutputstream = null;
    try {//from  ww  w .  j  av  a  2  s . c o  m
        fileInputStream = new FileInputStream(zipFile);
        zipInputStream = new ZipInputStream(fileInputStream);
        fileInputStream = new FileInputStream(zipFile);
        zipInputStream = new ZipInputStream(fileInputStream);
        java.util.zip.ZipEntry zipEntry;
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            boolean isDirectory = zipEntry.isDirectory();
            byte abyte0[] = new byte[BUFFER];
            String s1 = zipEntry.getName();
            s1 = convertEncoding(s1);

            String s2 = dir + "/" + s1;
            s2 = FileUtils.getJavaFileSystemPath(s2);

            if (s2.indexOf('/') != -1 || isDirectory) {
                String s4 = s2.substring(0, s2.lastIndexOf('/'));
                File file2 = new File(s4);
                FileUtils.mkdirsWithExistsCheck(file2);
            }

            if (isDirectory) {
                continue;
            }

            fileoutputstream = new FileOutputStream(s2);
            bufferedoutputstream = new BufferedOutputStream(fileoutputstream, BUFFER);
            int i = 0;
            while ((i = zipInputStream.read(abyte0, 0, BUFFER)) != -1) {
                bufferedoutputstream.write(abyte0, 0, i);
            }
            bufferedoutputstream.flush();
            IOUtils.closeStream(fileoutputstream);
            IOUtils.closeStream(bufferedoutputstream);
        }

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(fileInputStream);
        IOUtils.closeStream(zipInputStream);
        IOUtils.closeStream(fileoutputstream);
        IOUtils.closeStream(bufferedoutputstream);
    }
}

From source file:be.fedict.eid.applet.service.signer.ooxml.OOXMLSignatureVerifier.java

/**
 * Checks whether the file referred by the given URL is an OOXML document.
 * //from  ww  w .j av  a 2  s .c  o  m
 * @param url
 * @return
 * @throws IOException
 */
public static boolean isOOXML(URL url) throws IOException {
    ZipInputStream zipInputStream = new ZipInputStream(url.openStream());
    ZipEntry zipEntry;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (false == "[Content_Types].xml".equals(zipEntry.getName())) {
            continue;
        }
        return true;
    }
    return false;
}

From source file:com.glaf.core.util.ZipUtils.java

public static Map<String, byte[]> getZipBytesMap(ZipInputStream zipInputStream, List<String> includes) {
    Map<String, byte[]> zipMap = new java.util.HashMap<String, byte[]>();
    java.util.zip.ZipEntry zipEntry = null;
    ByteArrayOutputStream baos = null;
    BufferedOutputStream bos = null;
    byte tmpByte[] = null;
    try {//from  w  w w. j  a  va 2 s . c om
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            String name = zipEntry.getName();
            String ext = FileUtils.getFileExt(name);
            if (includes.contains(ext) || includes.contains(ext.toLowerCase())) {
                tmpByte = new byte[BUFFER];
                baos = new ByteArrayOutputStream();
                bos = new BufferedOutputStream(baos, BUFFER);
                int i = 0;
                while ((i = zipInputStream.read(tmpByte, 0, BUFFER)) != -1) {
                    bos.write(tmpByte, 0, i);
                }
                bos.flush();
                byte[] bytes = baos.toByteArray();
                IOUtils.closeStream(baos);
                IOUtils.closeStream(baos);
                zipMap.put(zipEntry.getName(), bytes);
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(baos);
        IOUtils.closeStream(baos);
    }
    return zipMap;
}

From source file:hermes.impl.LoaderSupport.java

/**
 * Return ClassLoader given the list of ClasspathConfig instances. The
 * resulting loader can then be used to instantiate providers from those
 * libraries.// w ww .  ja v  a2 s . c om
 */
static List lookForFactories(final List loaderConfigs, final ClassLoader baseLoader) throws IOException {
    final List rval = new ArrayList();

    for (Iterator iter = loaderConfigs.iterator(); iter.hasNext();) {
        final ClasspathConfig lConfig = (ClasspathConfig) iter.next();

        if (lConfig.getFactories() != null) {
            log.debug("using cached " + lConfig.getFactories());

            for (StringTokenizer tokens = new StringTokenizer(lConfig.getFactories(), ","); tokens
                    .hasMoreTokens();) {
                rval.add(tokens.nextToken());
            }
        } else if (lConfig.isNoFactories()) {
            log.debug("previously scanned " + lConfig.getJar());
        } else {
            Runnable r = new Runnable() {
                public void run() {
                    final List localFactories = new ArrayList();
                    boolean foundFactory = false;
                    StringBuffer factoriesAsString = null;

                    try {
                        log.debug("searching " + lConfig.getJar());

                        ClassLoader l = createClassLoader(loaderConfigs, baseLoader);
                        JarFile jarFile = new JarFile(lConfig.getJar());
                        ProgressMonitor monitor = null;
                        int entryNumber = 0;

                        if (HermesBrowser.getBrowser() != null) {
                            monitor = new ProgressMonitor(HermesBrowser.getBrowser(),
                                    "Looking for factories in " + lConfig.getJar(), "Scanning...", 0,
                                    jarFile.size());
                            monitor.setMillisToDecideToPopup(0);
                            monitor.setMillisToPopup(0);
                            monitor.setProgress(0);
                        }

                        for (Enumeration iter = jarFile.entries(); iter.hasMoreElements();) {
                            ZipEntry entry = (ZipEntry) iter.nextElement();
                            entryNumber++;

                            if (monitor != null) {
                                monitor.setProgress(entryNumber);
                                monitor.setNote("Checking entry " + entryNumber + " of " + jarFile.size());
                            }

                            if (entry.getName().endsWith(".class")) {
                                String s = entry.getName().substring(0, entry.getName().indexOf(".class"));

                                s = s.replaceAll("/", ".");

                                try {
                                    if (s.startsWith("hermes.browser") || s.startsWith("hermes.impl")
                                            || s.startsWith("javax.jms")) {
                                        // NOP
                                    } else {
                                        Class clazz = l.loadClass(s);

                                        if (!clazz.isInterface()) {

                                            if (implementsOrExtends(clazz, ConnectionFactory.class)) {

                                                foundFactory = true;
                                                localFactories.add(s);

                                                if (factoriesAsString == null) {
                                                    factoriesAsString = new StringBuffer();
                                                    factoriesAsString.append(clazz.getName());
                                                } else {
                                                    factoriesAsString.append(",").append(clazz.getName());
                                                }
                                                log.debug("found " + clazz.getName());
                                            }
                                        }

                                        /**
                                         * TODO: remove Class clazz = l.loadClass(s);
                                         * Class[] interfaces = clazz.getInterfaces();
                                         * for (int i = 0; i < interfaces.length; i++) {
                                         * if
                                         * (interfaces[i].equals(TopicConnectionFactory.class) ||
                                         * interfaces[i].equals(QueueConnectionFactory.class) ||
                                         * interfaces[i].equals(ConnectionFactory.class)) {
                                         * foundFactory = true; localFactories.add(s);
                                         * if (factoriesAsString == null) {
                                         * factoriesAsString = new
                                         * StringBuffer(clazz.getName()); } else {
                                         * factoriesAsString.append(",").append(clazz.getName()); }
                                         * log.debug("found " + clazz.getName()); } }
                                         */
                                    }
                                } catch (Throwable t) {
                                    // NOP
                                }
                            }
                        }
                    } catch (IOException e) {
                        log.error("unable to access jar/zip " + lConfig.getJar() + ": " + e.getMessage(), e);
                    }

                    if (!foundFactory) {
                        lConfig.setNoFactories(true);
                    } else {
                        lConfig.setFactories(factoriesAsString.toString());
                        rval.addAll(localFactories);
                    }

                }
            };

            r.run();

        }
    }

    return rval;
}

From source file:marytts.util.io.FileUtils.java

private static void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException {

    if (entry.isDirectory()) {
        createDir(new File(outputDir, entry.getName()));
        return;//ww w  .ja v  a2 s.  c o  m
    }

    File outputFile = new File(outputDir, entry.getName());
    if (!outputFile.getParentFile().exists()) {
        createDir(outputFile.getParentFile());
    }

    BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
    BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

    try {
        IOUtils.copy(inputStream, outputStream);
    } finally {
        outputStream.close();
        inputStream.close();
    }
}

From source file:de.innovationgate.wgpublisher.plugins.WGAPlugin.java

public static Configuration loadConfiguration(File file, boolean full)
        throws FileNotFoundException, IOException, InvalidCSConfigVersionException {

    if (!file.exists()) {
        return null;
    }/*from w  w  w  .ja  v  a 2s  .  c  o  m*/

    file = WGUtils.resolveDirLink(file);

    DesignDefinition syncInfo = null;
    CSConfig csConfig = null;
    OverlayData overlayData = null;
    String licenseText = null;

    // Normal plugin file
    if (file.isFile()) {
        ZipInputStream zipIn = new ZipInputStream(new FileInputStream(file));
        try {
            ZipEntry entry;
            while ((entry = zipIn.getNextEntry()) != null) {

                String entryName = entry.getName();
                if (entryName.equals(DesignDirectory.DESIGN_DEFINITION_FILE)
                        || entryName.equals(DesignDirectory.SYNCINFO_FILE)) {
                    TemporaryFile tempFile = new TemporaryFile("design", zipIn, WGFactory.getTempDir());
                    syncInfo = DesignDefinition.load(tempFile.getFile());
                    tempFile.delete();
                } else if (entryName.equals(SystemContainerManager.CSCONFIG_PATH)) {
                    TemporaryFile tempFile = new TemporaryFile("csconfig", zipIn, WGFactory.getTempDir());
                    csConfig = CSConfig.load(tempFile.getFile());
                    tempFile.delete();
                } else if (entryName.equals(SystemContainerManager.LICENSE_PATH)) {
                    licenseText = WGUtils.readString(new InputStreamReader(zipIn, "UTF-8")).trim();
                } else if (entryName.equals(SystemContainerManager.OVERLAY_DATA_PATH)) {
                    try {
                        overlayData = OverlayData.read(zipIn);
                    } catch (Exception e) {
                        Logger.getLogger("wga.plugins").error(
                                "Exception reading overlay data from plugin file " + file.getAbsolutePath(), e);
                    }
                }

                if (syncInfo != null && csConfig != null) {
                    if (!full || overlayData != null) {
                        break;
                    }
                }
            }
        } finally {
            zipIn.close();
        }
    }

    // Developer plugin folder
    else {
        File syncInfoFile = DesignDirectory.getDesignDefinitionFile(file);
        if (syncInfoFile.exists()) {
            syncInfo = DesignDefinition.load(syncInfoFile);
        }
        File csConfigFile = new File(file, SystemContainerManager.CSCONFIG_PATH);
        if (csConfigFile.exists()) {
            csConfig = CSConfig.load(csConfigFile);
        }
        File licenseTextFile = new File(file, SystemContainerManager.LICENSE_PATH);
        if (licenseTextFile.exists()) {
            Reader reader = new InputStreamReader(new FileInputStream(licenseTextFile), "UTF-8");
            licenseText = WGUtils.readString(reader).trim();
            reader.close();
        }
        File overlayDataFile = new File(file, SystemContainerManager.OVERLAY_DATA_PATH);
        if (overlayDataFile.exists()) {
            try {
                InputStream stream = new FileInputStream(overlayDataFile);
                overlayData = OverlayData.read(stream);
                stream.close();
            } catch (Exception e) {
                Logger.getLogger("wga.plugins").error(
                        "Exception reading overlay data from plugin directory " + file.getAbsolutePath(), e);
            }
        }

    }

    if (syncInfo != null && csConfig != null && csConfig.getPluginConfig() != null) {
        return new Configuration(syncInfo, csConfig, licenseText, overlayData);
    } else {
        return null;
    }

}

From source file:it.cnr.icar.eric.common.Utility.java

/**
 *
 * Extracts Zip file contents relative to baseDir
 * @return An ArrayList containing the File instances for each unzipped file
 *///from w ww  .j a v a 2 s  .  co  m
public static ArrayList<File> unZip(String baseDir, InputStream is) throws IOException {
    ArrayList<File> files = new ArrayList<File>();
    ZipInputStream zis = new ZipInputStream(is);

    while (true) {
        // Get the next zip entry.  Break out of the loop if there are
        //   no more.
        ZipEntry zipEntry = zis.getNextEntry();
        if (zipEntry == null)
            break;

        String entryName = zipEntry.getName();
        if (FILE_SEPARATOR.equalsIgnoreCase("\\")) {
            // Convert '/' to Windows file separator
            entryName = entryName.replaceAll("/", "\\\\");
        }
        String fileName = baseDir + FILE_SEPARATOR + entryName;
        //Make sure that directory exists.
        String dirName = fileName.substring(0, fileName.lastIndexOf(FILE_SEPARATOR));
        File dir = new File(dirName);
        dir.mkdirs();

        //Entry could be a directory
        if (!(zipEntry.isDirectory())) {
            //Entry is a file not a directory.
            //Write out the content of of entry to file 
            File file = new File(fileName);
            files.add(file);
            FileOutputStream fos = new FileOutputStream(file);

            // Read data from the zip entry.  The read() method will return
            //   -1 when there is no more data to read.
            byte[] buffer = new byte[1000];

            int n;

            while ((n = zis.read(buffer)) > -1) {
                // In real life, you'd probably write the data to a file.
                fos.write(buffer, 0, n);
            }
            zis.closeEntry();
            fos.close();
        } else {
            zis.closeEntry();
        }
    }

    zis.close();

    return files;
}

From source file:com.taobao.android.builder.tools.zip.ZipUtils.java

/**
 * zip/*  w w  w .j  av a 2s  .com*/
 *
 * @param zipFile
 * @param file
 * @param destPath
 * @param overwrite ?
 * @throws java.io.IOException
 */
public static void addFileToZipFile(File zipFile, File outZipFile, File file, String destPath,
        boolean overwrite) throws IOException {
    byte[] buf = new byte[1024];
    ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outZipFile));
    ZipEntry entry = zin.getNextEntry();
    boolean addFile = true;
    while (entry != null) {
        boolean addEntry = true;
        String name = entry.getName();
        if (StringUtils.equalsIgnoreCase(name, destPath)) {
            if (overwrite) {
                addEntry = false;
            } else {
                addFile = false;
            }
        }
        if (addEntry) {
            ZipEntry zipEntry = null;
            if (STORED == entry.getMethod()) {
                zipEntry = new ZipEntry(entry);
            } else {
                zipEntry = new ZipEntry(name);
            }
            out.putNextEntry(zipEntry);
            int len;
            while ((len = zin.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
        entry = zin.getNextEntry();
    }

    if (addFile) {
        InputStream in = new FileInputStream(file);
        // Add ZIP entry to output stream.
        ZipEntry zipEntry = new ZipEntry(destPath);
        out.putNextEntry(zipEntry);
        // Transfer bytes from the file to the ZIP file
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        // Complete the entry
        out.closeEntry();
        in.close();
    }
    // Close the streams
    zin.close();
    out.close();
}

From source file:net.minecraftforge.fml.common.asm.transformers.MarkerTransformer.java

private static void processJar(File inFile, File outFile, MarkerTransformer[] transformers) throws IOException {
    ZipInputStream inJar = null;//from   w  ww.ja  v  a 2  s .  c om
    ZipOutputStream outJar = null;

    try {
        try {
            inJar = new ZipInputStream(new BufferedInputStream(new FileInputStream(inFile)));
        } catch (FileNotFoundException e) {
            throw new FileNotFoundException("Could not open input file: " + e.getMessage());
        }

        try {
            outJar = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));
        } catch (FileNotFoundException e) {
            throw new FileNotFoundException("Could not open output file: " + e.getMessage());
        }

        ZipEntry entry;
        while ((entry = inJar.getNextEntry()) != null) {
            if (entry.isDirectory()) {
                outJar.putNextEntry(entry);
                continue;
            }

            byte[] data = new byte[4096];
            ByteArrayOutputStream entryBuffer = new ByteArrayOutputStream();

            int len;
            do {
                len = inJar.read(data);
                if (len > 0) {
                    entryBuffer.write(data, 0, len);
                }
            } while (len != -1);

            byte[] entryData = entryBuffer.toByteArray();

            String entryName = entry.getName();

            if (entryName.endsWith(".class") && !entryName.startsWith(".")) {
                ClassNode cls = new ClassNode();
                ClassReader rdr = new ClassReader(entryData);
                rdr.accept(cls, 0);
                String name = cls.name.replace('/', '.').replace('\\', '.');

                for (MarkerTransformer trans : transformers) {
                    entryData = trans.transform(name, name, entryData);
                }
            }

            ZipEntry newEntry = new ZipEntry(entryName);
            outJar.putNextEntry(newEntry);
            outJar.write(entryData);
        }
    } finally {
        IOUtils.closeQuietly(outJar);
        IOUtils.closeQuietly(inJar);
    }
}

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 ww  w .ja v a  2s  . co 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) {
        }
    }

}