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.fabric8.tooling.archetype.generator.ArchetypeHelper.java

/**
 * Main method which extracts given Maven Archetype in destination directory
 *
 * @return/*from   ww w .java2 s.  c o m*/
 */
public int execute() throws IOException {
    outputDir.mkdirs();

    if (packageName == null || packageName.length() == 0) {
        packageName = groupId + "." + artifactId;
    }

    String packageDir = packageName.replace('.', '/');

    info("Creating archetype using Maven groupId: " + groupId + ", artifactId: " + artifactId + ", version: "
            + version + " in directory: " + outputDir);

    Map<String, String> replaceProperties = new HashMap<String, String>();

    ZipInputStream zip = null;
    try {
        zip = new ZipInputStream(archetypeIn);
        boolean ok = true;
        while (ok) {
            ZipEntry entry = zip.getNextEntry();
            if (entry == null) {
                ok = false;
            } else {
                if (!entry.isDirectory()) {
                    String fullName = entry.getName();
                    if (fullName != null && fullName.startsWith(zipEntryPrefix)) {
                        String name = replaceFileProperties(fullName.substring(zipEntryPrefix.length()),
                                replaceProperties);
                        debug("Processing resource: " + name);

                        int idx = name.lastIndexOf('/');
                        Matcher matcher = sourcePathRegexPattern.matcher(name);
                        String dirName;
                        if (packageName.length() > 0 && idx > 0 && matcher.matches()) {
                            String prefix = matcher.group(1);
                            dirName = prefix + packageDir + "/" + name.substring(prefix.length());
                        } else if (packageName.length() > 0 && name.startsWith(webInfResources)) {
                            dirName = "src/main/webapp/WEB-INF/" + packageDir + "/resources"
                                    + name.substring(webInfResources.length());
                        } else {
                            dirName = name;
                        }

                        // lets replace properties...
                        File file = new File(outputDir, dirName);
                        file.getParentFile().mkdirs();
                        FileOutputStream out = null;
                        try {
                            out = new FileOutputStream(file);
                            boolean isBinary = false;
                            for (String suffix : binarySuffixes) {
                                if (name.endsWith(suffix)) {
                                    isBinary = true;
                                    break;
                                }
                            }
                            if (isBinary) {
                                // binary file?  don't transform.
                                copy(zip, out);
                            } else {
                                // text file...
                                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                                copy(zip, bos);
                                String text = new String(bos.toByteArray(), "UTF-8");
                                out.write(transformContents(text, replaceProperties).getBytes());
                            }
                        } finally {
                            if (out != null) {
                                out.close();
                            }
                        }
                    } else if (fullName != null && fullName.equals("META-INF/maven/archetype-metadata.xml")) {
                        // we assume that this resource will be first in Archetype's ZIP
                        // this way we can find out what are the required properties before we will actually use them
                        parseReplaceProperties(zip, replaceProperties);
                        replaceProperties.putAll(overrideProperties);
                    }
                }
                zip.closeEntry();
            }
        }
    } catch (Exception e) {
        throw new IOException(e.getMessage(), e);
    } finally {
        if (zip != null) {
            zip.close();
        }
    }

    info("Using replace properties: " + replaceProperties);

    // now lets replace all the properties in the pom.xml
    if (!replaceProperties.isEmpty()) {
        File pom = new File(outputDir, "pom.xml");
        FileReader reader = new FileReader(pom);
        String text = IOUtils.toString(reader);
        IOUtils.closeQuietly(reader);
        for (Map.Entry<String, String> e : replaceProperties.entrySet()) {
            text = replaceVariable(text, e.getKey(), e.getValue());
        }
        FileWriter writer = new FileWriter(pom);
        IOUtils.write(text, writer);
        IOUtils.closeQuietly(writer);
    }

    // now lets create the default directories
    if (createDefaultDirectories) {
        File srcDir = new File(outputDir, "src");
        File mainDir = new File(srcDir, "main");
        File testDir = new File(srcDir, "test");

        String srcDirName = "java";
        // Who needs Scala in 2014?
        //            if (new File(mainDir, "scala").exists() || new File(textDir, "scala").exists()) {
        //                srcDirName = "scala";
        //            }

        for (File dir : new File[] { mainDir, testDir }) {
            for (String name : new String[] { srcDirName + "/" + packageDir, "resources" }) {
                new File(dir, name).mkdirs();
            }
        }
    }

    return 0;
}

From source file:fr.gouv.finances.cp.xemelios.importers.batch.BatchRealImporter.java

private ImportContent files(final String extension, final String titreEtat) {
    ImportContent ic = new ImportContent();
    Vector<File> ret = new Vector<File>();
    ret.addAll(files);//from w ww.  ja  v a2  s .co  m
    // on regarde si l'un des fichiers a importer est un zip
    for (int i = 0; i < ret.size(); i++) {
        if (ret.get(i).getName().toLowerCase().endsWith(".zip")) {
            if (ret.get(i).exists()) {
                ZipFile zf = null;
                try {
                    zf = new ZipFile(ret.get(i));
                    for (Enumeration<? extends ZipEntry> enumer = zf.entries(); enumer.hasMoreElements();) {
                        ZipEntry ze = enumer.nextElement();
                        if (!ze.isDirectory()) {
                            String fileName = ze.getName();
                            String entryName = fileName.toLowerCase();
                            fileName = fileName.replace(File.pathSeparatorChar, '_')
                                    .replace(File.separatorChar, '_').replace(':', '|').replace('\'', '_')
                                    .replace('/', '_');
                            logger.debug(entryName);
                            if (PJRef.isPJ(ze)) {
                                PJRef pj = new PJRef(ze);
                                File tmpFile = pj.writeTmpFile(FileUtils.getTempDir(), zf);
                                ic.pjs.add(pj);
                                filesToDrop.add(tmpFile);
                            } else if ((entryName.endsWith(extension.toLowerCase())
                                    || entryName.endsWith(".xml")) && !fileName.startsWith("_")) {
                                // on decompresse le fichier dans le
                                // repertoire temporaire, comme ca il sera
                                // supprime en quittant
                                InputStream is = zf.getInputStream(ze);
                                BufferedInputStream bis = new BufferedInputStream(is);
                                File output = new File(FileUtils.getTempDir(), fileName);
                                BufferedOutputStream bos = new BufferedOutputStream(
                                        new FileOutputStream(output));
                                byte[] buffer = new byte[1024];
                                int read = bis.read(buffer);
                                while (read > 0) {
                                    bos.write(buffer, 0, read);
                                    read = bis.read(buffer);
                                }
                                bos.flush();
                                bos.close();
                                bis.close();
                                ic.filesToImport.add(output);
                                filesToDrop.add(output);
                            }
                        }
                    }
                    zf.close();
                } catch (ZipException zEx) {
                    System.out.println(
                            "Le fichier " + ret.get(i).getName() + " n'est pas une archive ZIP valide.");
                } catch (IOException ioEx) {
                    ioEx.printStackTrace();
                } finally {
                    if (zf != null) {
                        try {
                            zf.close();
                        } catch (Throwable t) {
                        }
                    }
                }
            }
        } else if (ret.get(i).getName().toLowerCase().endsWith(".gz")) {
            try {
                String fileName = ret.get(i).getName();
                fileName = fileName.substring(0, fileName.length() - 3);
                File output = new File(FileUtils.getTempDir(), fileName);
                GZIPInputStream gis = new GZIPInputStream(new FileInputStream(ret.get(i)));
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output));
                byte[] buffer = new byte[1024];
                int read = gis.read(buffer);
                while (read > 0) {
                    bos.write(buffer, 0, read);
                    read = gis.read(buffer);
                }
                bos.flush();
                bos.close();
                gis.close();
                ic.filesToImport.add(output);
                filesToDrop.add(output);
            } catch (IOException ioEx) {
                // nothing to do
            }
        } else {
            ic.filesToImport.add(ret.get(i));
            // dans ce cas l, on ne le supprime pas
        }
    }
    return ic;
}

From source file:com.openmeap.file.FileOperationManagerImpl.java

@Override
public void unzipFile(ZipFile zipFile, String destinationDir) throws FileOperationException {
    try {/*w  w w.  j a v  a  2s. co m*/
        int BUFFER = 1024;
        BufferedOutputStream dest = null;
        BufferedInputStream is = null;
        OutputStream fos = null;

        ZipEntry entry;

        Enumeration e = zipFile.entries();
        while (e.hasMoreElements()) {
            try {
                entry = (ZipEntry) e.nextElement();
                is = new BufferedInputStream(zipFile.getInputStream(entry));
                String newFile = destinationDir + File.separator + entry.getName();
                if (entry.isDirectory()) {
                    continue; // skip directories, resource manager will create for us
                } else {
                    fos = write(newFile);
                    dest = new BufferedOutputStream(fos, BUFFER);
                    Utils.pipeInputStreamIntoOutputStream(is, dest);
                }
            } finally {
                if (dest != null) {
                    dest.close();
                }
                if (fos != null) {
                    fos.close();
                }
                if (is != null) {
                    is.close();
                }
            }
        }
    } catch (IOException ioe) {
        throw new FileOperationException(ioe);
    }
}

From source file:eu.esdihumboldt.hale.io.appschema.writer.AppSchemaFileWriterTest.java

private void checkFileEntry(ZipEntry entry, String fileName) {
    assertNotNull(entry);//from   w  ww  .j av  a 2  s  .c  o  m
    assertEquals(fileName, entry.getName());
    assertFalse(entry.isDirectory());
}

From source file:maltcms.ui.nb.pipelineRunner.options.LocalMaltcmsExecutionPanel.java

public String getTopLevelArchiveDirectoryName(File archive) {
    try {//from   ww w  .j  a  v  a 2s.c o m
        ZipFile zipfile = new ZipFile(archive);
        for (Enumeration e = zipfile.entries(); e.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            if (entry.isDirectory()) {
                return entry.getName();
            }
        }
    } catch (Exception e) {
        Exceptions.printStackTrace(e);
    }
    return null;
}

From source file:eu.esdihumboldt.hale.io.appschema.writer.AppSchemaFileWriterTest.java

private void checkDirEntry(ZipEntry entry, final String dirName) {
    assertNotNull(entry);//from   w ww  .  j av a 2 s . co m
    assertEquals(dirName, entry.getName());
    assertTrue(entry.isDirectory());
}

From source file:maltcms.ui.nb.pipelineRunner.options.LocalMaltcmsExecutionPanel.java

private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException {
    if (entry.isDirectory()) {
        createDir(new File(outputDir, entry.getName()));
        return;/*from   w  ww  .  java2s  . co m*/
    }

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

    BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
    try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile))) {
        IOUtils.copy(inputStream, outputStream);
    } finally {
        inputStream.close();
    }
}

From source file:com.speed.ob.api.ClassStore.java

public void init(JarInputStream jarIn, File output, File in) throws IOException {
    ZipEntry entry;
    JarOutputStream out = new JarOutputStream(new FileOutputStream(new File(output, in.getName())));
    while ((entry = jarIn.getNextEntry()) != null) {
        byte[] data = IOUtils.toByteArray(jarIn);
        if (entry.getName().endsWith(".class")) {
            ClassReader reader = new ClassReader(data);
            ClassNode cn = new ClassNode();
            reader.accept(cn, ClassReader.EXPAND_FRAMES);
            store.put(cn.name, cn);//from  w  w  w. j a  v a2 s  .c om
        } else if (!entry.isDirectory()) {
            Logger.getLogger(getClass().getName()).finer("Storing " + entry.getName() + " in output file");
            JarEntry je = new JarEntry(entry.getName());
            out.putNextEntry(je);
            out.write(data);
            out.closeEntry();
        }
    }
    out.close();
}

From source file:org.apache.taverna.commandline.TavernaCommandLineTest.java

private void assertZipFilesEqual(File file1, File file2) {
    ZipFile zipFile1 = null;/*from   w w  w. j av  a2s. c  o  m*/
    ZipFile zipFile2 = null;
    try {
        zipFile1 = new ZipFile(file1);
        zipFile2 = new ZipFile(file2);
    } catch (Exception e) {
        assertTrue(String.format("%s and %s are not both zip files"), zipFile1 == null);
    }
    if (zipFile1 != null && zipFile2 != null) {
        Enumeration<? extends ZipEntry> entries1 = zipFile1.entries();
        Enumeration<? extends ZipEntry> entries2 = zipFile2.entries();
        while (entries1.hasMoreElements()) {
            assertTrue(entries2.hasMoreElements());
            ZipEntry zipEntry1 = entries1.nextElement();
            ZipEntry zipEntry2 = entries2.nextElement();
            assertEquals(String.format("%s and %s are not both directories", zipEntry1, zipEntry2),
                    zipEntry1.isDirectory(), zipEntry2.isDirectory());
            assertEquals(String.format("%s and %s have different names", zipEntry1, zipEntry2),
                    zipEntry1.getName(), zipEntry2.getName());
            assertEquals(String.format("%s and %s have different sizes", zipEntry1, zipEntry2),
                    zipEntry1.getSize(), zipEntry2.getSize());
            try {
                byte[] byteArray1 = IOUtils.toByteArray(zipFile1.getInputStream(zipEntry1));
                byte[] byteArray2 = IOUtils.toByteArray(zipFile2.getInputStream(zipEntry2));
                assertArrayEquals(String.format("%s != %s", zipEntry1, zipEntry2), byteArray1, byteArray2);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        assertFalse(entries2.hasMoreElements());
    }
}

From source file:org.apache.axis2.deployment.DeploymentEngine.java

private static void addAsWebResources(File in, String serviceFileName, AxisServiceGroup serviceGroup) {
    try {//from   w  w  w .  ja v a  2 s  .com
        if (webLocationString == null) {
            return;
        }
        if (in.isDirectory()) {
            return;
        }
        File webLocation = new File(webLocationString);
        File out = new File(webLocation, serviceFileName);
        int BUFFER = 1024;
        byte data[] = new byte[BUFFER];
        FileInputStream fin = new FileInputStream(in);
        ZipInputStream zin = new ZipInputStream(fin);
        ZipEntry entry;
        while ((entry = zin.getNextEntry()) != null) {
            ZipEntry zip = new ZipEntry(entry);
            if (zip.getName().toUpperCase().startsWith("WWW")) {
                String fileName = zip.getName();
                fileName = fileName.substring("WWW/".length(), fileName.length());
                if (zip.isDirectory()) {
                    new File(out, fileName).mkdirs();
                } else {
                    FileOutputStream tempOut = new FileOutputStream(new File(out, fileName));
                    int count;
                    while ((count = zin.read(data, 0, BUFFER)) != -1) {
                        tempOut.write(data, 0, count);
                    }
                    tempOut.close();
                    tempOut.flush();
                }
                serviceGroup.setFoundWebResources(true);
            }
        }
        zin.close();
        fin.close();
    } catch (IOException e) {
        log.info(e.getMessage());
    }
}