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.aurel.track.dbase.InitReportTemplateBL.java

/**
 * Unzip a ZIP file into a directory//ww w.  j  a  v  a  2 s  . co m
 * @param zipFile
 * @param dir
 */
private static void unzipFileIntoDirectory(ZipFile zipFile, File dir) {
    Enumeration files = zipFile.entries();
    File f = null;
    FileOutputStream fos = null;
    while (files.hasMoreElements()) {
        try {
            ZipEntry entry = (ZipEntry) files.nextElement();
            InputStream eis = zipFile.getInputStream(entry);
            byte[] buffer = new byte[1024];
            int bytesRead = 0;

            f = new File(dir.getAbsolutePath() + File.separator + entry.getName());

            if (entry.isDirectory()) {
                f.mkdirs();
                continue;
            } else {
                f.getParentFile().mkdirs();
                f.createNewFile();
            }

            fos = new FileOutputStream(f);

            while ((bytesRead = eis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
            continue;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    // ignore
                }
            }
        }
    }
}

From source file:brut.directory.ZipUtils.java

private static void processFolder(final File folder, final ZipOutputStream zipOutputStream,
        final int prefixLength) throws BrutException, IOException {
    for (final File file : folder.listFiles()) {
        if (file.isFile()) {
            final String cleanedPath = BrutIO.sanitizeUnknownFile(folder,
                    file.getPath().substring(prefixLength));
            final ZipEntry zipEntry = new ZipEntry(BrutIO.normalizePath(cleanedPath));

            // aapt binary by default takes in parameters via -0 arsc to list extensions that shouldn't be
            // compressed. We will replicate that behavior
            final String extension = FilenameUtils.getExtension(file.getAbsolutePath());
            if (mDoNotCompress != null
                    && (mDoNotCompress.contains(extension) || mDoNotCompress.contains(zipEntry.getName()))) {
                zipEntry.setMethod(ZipEntry.STORED);
                zipEntry.setSize(file.length());
                BufferedInputStream unknownFile = new BufferedInputStream(new FileInputStream(file));
                CRC32 crc = BrutIO.calculateCrc(unknownFile);
                zipEntry.setCrc(crc.getValue());
                unknownFile.close();/* w  w w.jav a 2  s.c om*/
            } else {
                zipEntry.setMethod(ZipEntry.DEFLATED);
            }

            zipOutputStream.putNextEntry(zipEntry);
            try (FileInputStream inputStream = new FileInputStream(file)) {
                IOUtils.copy(inputStream, zipOutputStream);
            }
            zipOutputStream.closeEntry();
        } else if (file.isDirectory()) {
            processFolder(file, zipOutputStream, prefixLength);
        }
    }
}

From source file:com.nextep.designer.repository.services.impl.RepositoryUpdaterService.java

/**
 * Creates the specified delivery (ZIP resource file) on the temporary directory of the local
 * file system.//w w w .j a  v  a 2s .c  om
 * 
 * @param deliveryResource java resource zip file
 * @return a <code>String</code> representing the absolute path to the delivery root directory.
 */
private static String createTempDelivery(String deliveryResource) {
    InputStream is = RepositoryUpdaterService.class.getResourceAsStream(deliveryResource);
    if (is == null) {
        throw new ErrorException("Unable to load delivery file: " + deliveryResource); //$NON-NLS-1$
    }

    final String exportLoc = System.getProperty("java.io.tmpdir"); //$NON-NLS-1$
    ZipInputStream zipInput = new ZipInputStream(is);
    ZipEntry entry = null;
    String rootDeliveryDir = null;
    try {
        while ((entry = zipInput.getNextEntry()) != null) {
            File targetFile = new File(exportLoc, entry.getName());

            if (rootDeliveryDir == null) {
                /*
                 * Initialize the delivery root directory value by searching recursively for the
                 * shallowest directory in the path.
                 */
                rootDeliveryDir = getDeliveryRootPath(targetFile, new File(exportLoc));
            }

            if (entry.isDirectory()) {
                targetFile.mkdirs();
            } else {
                File targetDir = targetFile.getParentFile();
                if (!targetDir.exists()) {
                    /*
                     * Creates the directory including any necessary but nonexistent parent
                     * directories.
                     */
                    targetDir.mkdirs();
                }

                FileOutputStream outFile = new FileOutputStream(targetFile);
                copyStreams(zipInput, outFile);
                outFile.close();
            }
            zipInput.closeEntry();
        }
    } catch (IOException e) {
        throw new ErrorException(e);
    } finally {
        try {
            zipInput.close();
        } catch (IOException e) {
            throw new ErrorException(e);
        }
    }
    return rootDeliveryDir;
}

From source file:edu.uci.ics.asterix.event.service.AsterixEventServiceUtil.java

private static void createDir(String destDirectory, ZipEntry entry) {
    String name = entry.getName();
    int index = name.lastIndexOf(File.separator);
    String dirSequence = name.substring(0, index);
    File newDirs = new File(destDirectory + File.separator + dirSequence);
    newDirs.mkdirs();/*from w  w  w  .  j  a v a 2s.c om*/
}

From source file:com.twinsoft.convertigo.engine.util.ZipUtils.java

public static void expandZip(String zipFileName, String rootDir, String prefixDir)
        throws FileNotFoundException, IOException {
    Engine.logEngine.debug("Expanding the zip file " + zipFileName);

    // Creating the root directory
    File ftmp = new File(rootDir);
    if (!ftmp.exists()) {
        ftmp.mkdirs();/*from  w ww  .ja v a  2  s  . c  o m*/
        Engine.logEngine.debug("Root directory created");
    }

    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFileName)));

    try {
        ZipEntry entry;
        int prefixSize = prefixDir != null ? prefixDir.length() : 0;

        while ((entry = zis.getNextEntry()) != null) {
            // Ignoring directories
            if (entry.isDirectory()) {

            } else {

                String entryName = entry.getName();
                Engine.logEngine.debug("+ Analyzing the entry: " + entryName);

                try {
                    // Ignore entry if does not belong to the project directory
                    if ((prefixDir == null) || entryName.startsWith(prefixDir)) {

                        // Ignore entry from _data or _private directory
                        if ((entryName.indexOf("/_data/") != prefixSize)
                                && (entryName.indexOf("/_private/") != prefixSize)) {
                            Engine.logEngine.debug("  The entry is accepted");
                            String s1 = rootDir + "/" + entryName;
                            String dir = s1.substring(0, s1.lastIndexOf('/'));

                            // Creating the directory if needed
                            ftmp = new File(dir);
                            if (!ftmp.exists()) {
                                ftmp.mkdirs();
                                Engine.logEngine.debug("  Directory created");
                            }

                            // Writing the files to the disk
                            File file = new File(rootDir + "/" + entryName);
                            FileOutputStream fos = new FileOutputStream(file);
                            try {
                                IOUtils.copy(zis, fos);
                            } finally {
                                fos.close();
                            }
                            file.setLastModified(entry.getTime());
                            Engine.logEngine.debug("  File written to: " + rootDir + "/" + entryName);
                        }
                    }
                } catch (IOException e) {
                    Engine.logEngine.error(
                            "Unable to expand the ZIP entry \"" + entryName + "\": " + e.getMessage(), e);
                }
            }
        }
    } finally {
        zis.close();
    }
}

From source file:com.esofthead.mycollab.jetty.GenericServerRunner.java

private static void unpackFile(File upgradeFile) throws IOException {
    File libFolder = new File(System.getProperty("user.dir"), "lib");
    File webappFolder = new File(System.getProperty("user.dir"), "webapp");
    org.apache.commons.io.FileUtils.deleteDirectory(libFolder);
    org.apache.commons.io.FileUtils.deleteDirectory(webappFolder);

    byte[] buffer = new byte[2048];

    try (ZipInputStream inputStream = new ZipInputStream(new FileInputStream(upgradeFile))) {
        ZipEntry entry;
        while ((entry = inputStream.getNextEntry()) != null) {
            if (!entry.isDirectory()
                    && (entry.getName().startsWith("lib/") || entry.getName().startsWith("webapp"))) {
                File candidateFile = new File(System.getProperty("user.dir"), entry.getName());
                candidateFile.getParentFile().mkdirs();
                try (FileOutputStream output = new FileOutputStream(candidateFile)) {
                    int len;
                    while ((len = inputStream.read(buffer)) > 0) {
                        output.write(buffer, 0, len);
                    }/*from   w w  w .  j a va  2s  . c o  m*/
                }
            }
        }
    } catch (IOException e) {
        throw new MyCollabException(e);
    }
}

From source file:com.ibm.amc.FileManager.java

public static File decompress(URI temporaryFileUri) {
    final File destination = new File(getUploadDirectory(), temporaryFileUri.getSchemeSpecificPart());
    if (!destination.mkdirs()) {
        throw new AmcRuntimeException(Status.INTERNAL_SERVER_ERROR, "CWZBA2001E_DIRECTORY_CREATION_FAILED",
                destination.getPath());//from   w  w  w  .  ja  v a 2  s  .c  om
    }

    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(getFileForUri(temporaryFileUri));

        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File newDirOrFile = new File(destination, entry.getName());
            if (newDirOrFile.getParentFile() != null && !newDirOrFile.getParentFile().exists()) {
                if (!newDirOrFile.getParentFile().mkdirs()) {
                    throw new AmcRuntimeException(Status.INTERNAL_SERVER_ERROR,
                            "CWZBA2001E_DIRECTORY_CREATION_FAILED", newDirOrFile.getParentFile().getPath());
                }
            }
            if (entry.isDirectory()) {
                if (!newDirOrFile.mkdir()) {
                    throw new AmcRuntimeException(Status.INTERNAL_SERVER_ERROR,
                            "CWZBA2001E_DIRECTORY_CREATION_FAILED", newDirOrFile.getPath());
                }
            } else {
                BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                int size;
                byte[] buffer = new byte[ZIP_BUFFER];
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newDirOrFile),
                        ZIP_BUFFER);
                while ((size = bis.read(buffer, 0, ZIP_BUFFER)) != -1) {
                    bos.write(buffer, 0, size);
                }
                bos.flush();
                bos.close();
                bis.close();
            }
        }
    } catch (Exception e) {
        throw new AmcRuntimeException(e);
    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
                logger.debug("decompress", "close failed with " + e);
            }
        }
    }

    return destination;
}

From source file:org.nuxeo.apidoc.introspection.ServerInfo.java

protected static BundleInfoImpl computeBundleInfo(Bundle bundle) {
    RuntimeService runtime = Framework.getRuntime();
    BundleInfoImpl binfo = new BundleInfoImpl(bundle.getSymbolicName());
    binfo.setFileName(runtime.getBundleFile(bundle).getName());
    binfo.setLocation(bundle.getLocation());
    if (!(bundle instanceof BundleImpl)) {
        return binfo;
    }/*from   w  w  w .j a v  a2  s  .  c  o  m*/
    BundleImpl nxBundle = (BundleImpl) bundle;
    File jarFile = nxBundle.getBundleFile().getFile();
    if (jarFile == null) {
        return binfo;
    }
    try {
        if (jarFile.isDirectory()) {
            // directory: run from Eclipse in unit tests
            // .../nuxeo-runtime/nuxeo-runtime/bin
            // or sometimes
            // .../nuxeo-runtime/nuxeo-runtime/bin/main
            File manifest = new File(jarFile, META_INF_MANIFEST_MF);
            if (manifest.exists()) {
                InputStream is = new FileInputStream(manifest);
                String mf = IOUtils.toString(is, Charsets.UTF_8);
                binfo.setManifest(mf);
            }
            // find and parse pom.xml
            File up = new File(jarFile, "..");
            File pom = new File(up, POM_XML);
            if (!pom.exists()) {
                pom = new File(new File(up, ".."), POM_XML);
                if (!pom.exists()) {
                    pom = null;
                }
            }
            if (pom != null) {
                DocumentBuilder b = documentBuilderFactory.newDocumentBuilder();
                Document doc = b.parse(new FileInputStream(pom));
                XPath xpath = xpathFactory.newXPath();
                String groupId = (String) xpath.evaluate("//project/groupId", doc, XPathConstants.STRING);
                if ("".equals(groupId)) {
                    groupId = (String) xpath.evaluate("//project/parent/groupId", doc, XPathConstants.STRING);
                }
                String artifactId = (String) xpath.evaluate("//project/artifactId", doc, XPathConstants.STRING);
                if ("".equals(artifactId)) {
                    artifactId = (String) xpath.evaluate("//project/parent/artifactId", doc,
                            XPathConstants.STRING);
                }
                String version = (String) xpath.evaluate("//project/version", doc, XPathConstants.STRING);
                if ("".equals(version)) {
                    version = (String) xpath.evaluate("//project/parent/version", doc, XPathConstants.STRING);
                }
                binfo.setArtifactId(artifactId);
                binfo.setGroupId(groupId);
                binfo.setArtifactVersion(version);
            }
        } else {
            try (ZipFile zFile = new ZipFile(jarFile)) {
                ZipEntry mfEntry = zFile.getEntry(META_INF_MANIFEST_MF);
                if (mfEntry != null) {
                    try (InputStream mfStream = zFile.getInputStream(mfEntry)) {
                        String mf = IOUtils.toString(mfStream, Charsets.UTF_8);
                        binfo.setManifest(mf);
                    }
                }
                Enumeration<? extends ZipEntry> entries = zFile.entries();
                while (entries.hasMoreElements()) {
                    ZipEntry entry = entries.nextElement();
                    if (entry.getName().endsWith(POM_PROPERTIES)) {
                        try (InputStream is = zFile.getInputStream(entry)) {
                            PropertyResourceBundle prb = new PropertyResourceBundle(is);
                            String groupId = prb.getString("groupId");
                            String artifactId = prb.getString("artifactId");
                            String version = prb.getString("version");
                            binfo.setArtifactId(artifactId);
                            binfo.setGroupId(groupId);
                            binfo.setArtifactVersion(version);
                        }
                        break;
                    }
                }
            }
            try (ZipFile zFile = new ZipFile(jarFile)) {
                EmbeddedDocExtractor.extractEmbeddedDoc(zFile, binfo);
            }
        }
    } catch (IOException | ParserConfigurationException | SAXException | XPathException | NuxeoException e) {
        log.error(e, e);
    }
    return binfo;
}

From source file:org.adl.samplerte.server.LMSPackageHandler.java

/****************************************************************************
 **//from  w w  w.  ja  va 2 s  . co  m
 ** Method:   findMetadata()
 ** Input:  String zipFileName  --  The name of the zip file to be used
 ** Output: Boolean  --  Whether or not any xml files were found  
 **
 ** Description: This method takes in the name of a zip file and locates 
 **              all files with an .xml extension 
 **              
 *****************************************************************************/
public static boolean findMetadata(String zipFileName) {
    if (_Debug) {
        System.out.println("***********************");
        System.out.println("in findMetadata()      ");
        System.out.println("***********************\n");
    }

    boolean rtn = false;
    String suffix = ".xml";

    try {
        //  The zip file being searched.
        ZipInputStream in = new ZipInputStream(new FileInputStream(zipFileName));
        //  An entry in the zip file
        ZipEntry entry;

        while ((in.available() != 0)) {
            entry = in.getNextEntry();

            if (in.available() != 0) {
                if ((entry.getName()).endsWith(suffix)) {
                    rtn = true;
                    if (_Debug) {
                        System.out.println("Other Meta-data located... returning true");
                    }
                }
            }
        }

        in.close();
    } catch (IOException e) {
        if (_Debug) {
            System.out.println("IO Exception Caught: " + e);
        }
    }

    return rtn;
}

From source file:org.nebulaframework.core.job.archive.GridArchive.java

/**
 * Detects all classes inside the given {@code .nar} file and returns an
 * array of fully qualified class name of each class, as {@code String}.
 * /*  w w w.  jav  a 2s .c o m*/
 * @param file
 *            {@code .nar File}
 * 
 * @return Fully qualified class names classes in {@code File}
 * 
 * @throws IOException
 *             if occurred during File I/O operations
 */
protected static String[] getAllClassNames(File file) throws IOException {

    // Holds Class Names
    List<String> names = new ArrayList<String>();

    // Create ZipArchive for File
    ZipFile archive = new ZipFile(file);
    Enumeration<? extends ZipEntry> entries = archive.entries();

    // Read each entry in archive
    while (entries.hasMoreElements()) {

        ZipEntry entry = entries.nextElement();

        // Ignore Directories
        if (entry.isDirectory())
            continue;

        // Ignore content in NEBULA-INF
        if (entry.getName().startsWith(GridArchive.NEBULA_INF)) {
            continue;
        }

        // Add each file which is a valid class file to list
        if (isClass(entry.getName())) {
            names.add(toClassName(entry.getName()));
        }
    }
    return names.toArray(new String[] {});
}