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:org.dspace.webmvc.controller.ResourceController.java

protected LookupResult lookupNoCache(HttpServletRequest req) {
    final String path = getPath(req);
    if (isForbidden(path)) {
        return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
    }//from w ww.  j  ava2  s .c  o m

    final URL url;
    try {
        url = req.getSession().getServletContext().getResource(path);
    } catch (MalformedURLException e) {
        return new Error(HttpServletResponse.SC_BAD_REQUEST, "Malformed path");
    }

    final String mimeType = getMimeType(req, path);

    final String realpath = req.getSession().getServletContext().getRealPath(path);
    if (url != null && realpath != null) {
        // Try as an ordinary file
        File f = new File(realpath);
        if (!f.isFile()) {
            return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
        } else {
            return new StaticFile(f.lastModified(), mimeType, (int) f.length(), acceptsDeflate(req), url);
        }
    } else {
        ClassPathResource cpr = new ClassPathResource(path);
        if (cpr.exists()) {
            URL cprURL = null;
            try {
                cprURL = cpr.getURL();

                // Try as a JAR Entry
                final ZipEntry ze = ((JarURLConnection) cprURL.openConnection()).getJarEntry();
                if (ze != null) {
                    if (ze.isDirectory()) {
                        return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
                    } else {
                        return new StaticFile(ze.getTime(), mimeType, (int) ze.getSize(), acceptsDeflate(req),
                                cprURL);
                    }
                } else {
                    // Unexpected?
                    return new StaticFile(-1, mimeType, -1, acceptsDeflate(req), cprURL);
                }
            } catch (ClassCastException e) {
                // Unknown resource type
                if (url != null) {
                    return new StaticFile(-1, mimeType, -1, acceptsDeflate(req), cprURL);
                } else {
                    return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
                }
            } catch (IOException e) {
                return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
            }
        } else {
            return new Error(HttpServletResponse.SC_NOT_FOUND, "Not found");
        }
    }
}

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  ww  w .  ja v a2  s  . c om
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:org.cloudfoundry.client.lib.archive.AbstractApplicationArchiveTest.java

@Test
@Ignore//from w  ww.j a v a  2 s .co  m
public void shouldAdaptEntries() throws Exception {
    Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
    while (zipEntries.hasMoreElements()) {
        ZipEntry zipEntry = zipEntries.nextElement();
        ApplicationArchive.Entry archiveEntry = archiveEntries.remove(zipEntry.getName());
        assertThat(archiveEntry, is(notNullValue()));
        assertThat(archiveEntry.getSize(), is(zipEntry.getSize()));
        assertThat(archiveEntry.isDirectory(), is(zipEntry.isDirectory()));
    }
    assertThat(archiveEntries.size(), is(0));
}

From source file:com.github.nethad.clustermeister.provisioning.local.JPPFLocalNode.java

private void unzipNode(InputStream fileToUnzip, File targetDir) {
    ZipInputStream zipFile;/*  ww  w.j a v a 2 s  .c  o  m*/
    try {
        zipFile = new ZipInputStream(fileToUnzip);
        ZipEntry entry;
        while ((entry = zipFile.getNextEntry()) != null) {
            //                ZipEntry entry = (ZipEntry) entries.nextElement();
            if (entry.isDirectory()) {
                // Assume directories are stored parents first then children.
                System.err.println("Extracting directory: " + entry.getName());
                // This is not robust, just for demonstration purposes.
                (new File(targetDir, entry.getName())).mkdir();
                continue;
            }
            System.err.println("Extracting file: " + entry.getName());
            File targetFile = new File(targetDir, entry.getName());
            copyInputStream_notClosing(zipFile, new BufferedOutputStream(new FileOutputStream(targetFile)));
            //                zipFile.closeEntry();
        }
        zipFile.close();
    } catch (IOException ioe) {
        logger.warn("Unhandled exception.", ioe);
    }
}

From source file:org.zilverline.service.CollectionManagerImpl.java

/**
 * unZips a given zip file into cache directory with derived name. e.g. c:\temp\file.zip wil be unziiped into
 * [cacheDir]\file_zip\./*from w w  w.  j  a  v a 2s  .co  m*/
 * 
 * @param sourceZipFile the ZIP file to be unzipped
 * @param thisCollection the collection whose cache and contenDir is used
 * 
 * @return File (new) directory containing zip file
 */
public static File unZip(final File sourceZipFile, final FileSystemCollection thisCollection) {
    // specify buffer size for extraction
    final int aBUFFER = 2048;
    File unzipDestinationDirectory = null;
    ZipFile zipFile = null;
    FileOutputStream fos = null;
    BufferedOutputStream dest = null;
    BufferedInputStream bis = null;

    try {
        // Specify destination where file will be unzipped
        unzipDestinationDirectory = file2CacheDir(sourceZipFile, thisCollection);
        log.info("unzipping " + sourceZipFile + " into " + unzipDestinationDirectory);
        // Open Zip file for reading
        zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);
        // Create an enumeration of the entries in the zip file
        Enumeration zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            // grab a zip file entry
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            String currentEntry = entry.getName();
            log.debug("Extracting: " + entry);
            File destFile = new File(unzipDestinationDirectory, currentEntry);
            // grab file's parent directory structure
            File destinationParent = destFile.getParentFile();
            // create the parent directory structure if needed
            destinationParent.mkdirs();
            // extract file if not a directory
            if (!entry.isDirectory()) {
                bis = new BufferedInputStream(zipFile.getInputStream(entry));
                int currentByte;
                // establish buffer for writing file
                byte[] data = new byte[aBUFFER];
                // write the current file to disk
                fos = new FileOutputStream(destFile);
                dest = new BufferedOutputStream(fos, aBUFFER);
                // read and write until last byte is encountered
                while ((currentByte = bis.read(data, 0, aBUFFER)) != -1) {
                    dest.write(data, 0, currentByte);
                }
                dest.flush();
                dest.close();
                bis.close();
            }
        }
        zipFile.close();
        // delete the zip file if it is in the cache, we don't need to store
        // it, since we've extracted the contents
        if (FileUtils.isIn(sourceZipFile, thisCollection.getCacheDirWithManagerDefaults())) {
            sourceZipFile.delete();
        }
    } catch (Exception e) {
        log.error("Can't unzip: " + sourceZipFile, e);
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }
            if (dest != null) {
                dest.close();
            }
            if (bis != null) {
                bis.close();
            }
        } catch (IOException e1) {
            log.error("Error closing files", e1);
        }
    }

    return unzipDestinationDirectory;
}

From source file:hoot.services.controllers.ogr.OgrAttributesResource.java

/**
 * This rest endpoint uploads multipart data from UI and then generates attribute output
 * Example: http://localhost:8080//hoot-services/ogr/info/upload?INPUT_TYPE=DIR
 * Output: {"jobId":"e43feae4-0644-47fd-a23c-6249e6e7f7fb"}
 * //from w  w w .  ja  v a 2s.  co  m
 * After getting the jobId, one can track the progress through job status rest end point
 * Example: http://localhost:8080/hoot-services/job/status/e43feae4-0644-47fd-a23c-6249e6e7f7fb
 * Output: {"jobId":"e43feae4-0644-47fd-a23c-6249e6e7f7fb","statusDetail":null,"status":"complete"}
 * 
 * Once status is "complete"
 * Result attribute can be obtained through
 * Example:http://localhost:8080/hoot-services/ogr/info/e43feae4-0644-47fd-a23c-6249e6e7f7fb
 * output: JSON of attributes
 * 
 * @param inputType : [FILE | DIR] where FILE type should represents zip,shp or OMS and DIR represents FGDB
 * @param request
 * @return
 */
@POST
@Path("/upload")
@Produces(MediaType.TEXT_PLAIN)
public Response processUpload(@QueryParam("INPUT_TYPE") final String inputType,
        @Context HttpServletRequest request) {
    JSONObject res = new JSONObject();
    String jobId = UUID.randomUUID().toString();

    try {
        log.debug("Starting file upload for ogr attribute Process");
        Map<String, String> uploadedFiles = new HashMap<String, String>();
        ;
        Map<String, String> uploadedFilesPaths = new HashMap<String, String>();

        MultipartSerializer ser = new MultipartSerializer();
        ser.serializeUpload(jobId, inputType, uploadedFiles, uploadedFilesPaths, request);

        List<String> filesList = new ArrayList<String>();
        List<String> zipList = new ArrayList<String>();

        Iterator it = uploadedFiles.entrySet().iterator();
        while (it.hasNext()) {

            Map.Entry pairs = (Map.Entry) it.next();
            String fName = pairs.getKey().toString();
            String ext = pairs.getValue().toString();

            String inputFileName = "";

            inputFileName = uploadedFilesPaths.get(fName);

            JSONObject param = new JSONObject();
            // If it is zip file then we crack open to see if it contains FGDB.
            // If so then we add the folder location and desired output name which is fgdb name in the zip
            if (ext.equalsIgnoreCase("ZIP")) {
                zipList.add(fName);
                String zipFilePath = homeFolder + "/upload/" + jobId + "/" + inputFileName;
                ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath));
                ZipEntry ze = zis.getNextEntry();

                while (ze != null) {

                    String zipName = ze.getName();
                    if (ze.isDirectory()) {

                        if (zipName.toLowerCase().endsWith(".gdb/") || zipName.toLowerCase().endsWith(".gdb")) {
                            String fgdbZipName = zipName;
                            if (zipName.toLowerCase().endsWith(".gdb/")) {
                                fgdbZipName = zipName.substring(0, zipName.length() - 1);
                            }
                            filesList.add("\"" + fName + "/" + fgdbZipName + "\"");
                        }
                    } else {
                        if (zipName.toLowerCase().endsWith(".shp")) {
                            filesList.add("\"" + fName + "/" + zipName + "\"");
                        }

                    }
                    ze = zis.getNextEntry();
                }

                zis.closeEntry();
                zis.close();
            } else {
                filesList.add("\"" + inputFileName + "\"");
            }

        }

        String mergeFilesList = StringUtils.join(filesList.toArray(), ' ');
        String mergedZipList = StringUtils.join(zipList.toArray(), ';');
        JSONArray params = new JSONArray();
        JSONObject param = new JSONObject();
        param.put("INPUT_FILES", mergeFilesList);
        params.add(param);
        param = new JSONObject();
        param.put("INPUT_ZIPS", mergedZipList);
        params.add(param);

        String argStr = createPostBody(params);
        postJobRquest(jobId, argStr);

    } catch (Exception ex) {
        ResourceErrorHandler.handleError("Failed upload: " + ex.toString(), Status.INTERNAL_SERVER_ERROR, log);
    }
    res.put("jobId", jobId);
    return Response.ok(res.toJSONString(), MediaType.APPLICATION_JSON).build();
}

From source file:com.aurel.track.util.PluginUtils.java

/**
 * Unzip this file into the given directory. If the zipFile is called "zipFile.zip",
 * the files will be placed into "targetDir/zipFile".
 * @param zipFile//from ww  w  .j  a v  a2 s .c o m
 * @param targetDir
 */
public static void unzipFileIntoDirectory(File zipFile, File targetDir) {
    try {
        LOGGER.debug("Expanding Genji extension file " + zipFile.getName());
        int BUFFER = 2048;
        File file = zipFile;
        ZipFile zip = new ZipFile(file);
        String newPath = targetDir + File.separator
                + zipFile.getName().substring(0, zipFile.getName().length() - 4);
        new File(newPath).mkdir();
        Enumeration zipFileEntries = zip.entries();
        // Process each entry
        while (zipFileEntries.hasMoreElements()) {
            // grab a zip file entry
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            String currentEntry = entry.getName();
            File destFile = new File(newPath, currentEntry);
            //destFile = new File(newPath, destFile.getName());
            File destinationParent = destFile.getParentFile();
            // create the parent directory structure if needed
            destinationParent.mkdirs();
            if (!entry.isDirectory()) {
                BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
                int currentByte;
                // establish buffer for writing file
                byte data[] = new byte[BUFFER];
                // write the current file to disk
                LOGGER.debug("Unzipping " + destFile.getAbsolutePath());
                FileOutputStream fos = new FileOutputStream(destFile);
                BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
                // read and write until last byte is encountered
                while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, currentByte);
                }
                dest.flush();
                dest.close();
                is.close();
            }
        }
    } catch (Exception e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    }
}

From source file:com.amazonaws.eclipse.elasticbeanstalk.git.AWSGitPushCommand.java

private void extractZipFile(File zipFile, File destination) throws IOException {
    int BUFFER = 2048;

    FileInputStream fis = new FileInputStream(zipFile);
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
    BufferedOutputStream dest = null;
    try {/*from   www  .  ja  v a  2 s  .c  o  m*/
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            int count;
            byte data[] = new byte[BUFFER];
            // write the files to the disk

            if (entry.isDirectory())
                continue;

            File entryFile = new File(destination, entry.getName());
            if (!entryFile.getParentFile().exists()) {
                entryFile.getParentFile().mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(entryFile);
            dest = new BufferedOutputStream(fos, BUFFER);
            while ((count = zis.read(data, 0, BUFFER)) != -1) {
                dest.write(data, 0, count);
            }
            dest.flush();
        }
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(zis);
        IOUtils.closeQuietly(dest);
    }
}

From source file:com.bemis.portal.fileuploader.service.impl.FileUploaderLocalServiceImpl.java

public void uploadFiles(long companyId, long groupId, long userId, File file, long fileTypeId,
        String[] assetTagNames) throws IOException, PortalException {

    String fileName = file.getName();

    if (!fileName.endsWith(".zip")) {
        if (_log.isWarnEnabled()) {
            _log.warn(">>> Unsupported compressed file type. Supports ZIP" + "compressed files only. ");
        }//from   w  ww . j av  a  2  s  .c om

        throw new FileUploaderException("error.unsupported-file-type");
    }

    DataOutputStream outputStream = null;

    try (ZipInputStream inputStream = new ZipInputStream(new BufferedInputStream(new FileInputStream(file)))) {

        ZipEntry fileEntry;
        while ((fileEntry = inputStream.getNextEntry()) != null) {
            boolean isDir = fileEntry.isDirectory();
            boolean isSubDirFile = fileEntry.getName().contains(SLASH);

            if (isDir || isSubDirFile) {
                if (_log.isWarnEnabled()) {
                    _log.warn(">>> Directory found inside the zip file " + "uploaded.");
                }

                continue;
            }

            String fileEntryName = fileEntry.getName();

            String extension = PERIOD + FileUtil.getExtension(fileEntryName);

            File tempFile = null;

            try {
                tempFile = File.createTempFile("tempfile", extension);

                byte[] buffer = new byte[INPUT_BUFFER];

                outputStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(tempFile)));

                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                outputStream.flush();

                String fileDescription = BLANK;
                String changeLog = BLANK;

                uploadFile(companyId, groupId, userId, tempFile, fileDescription, fileEntryName, fileTypeId,
                        changeLog, assetTagNames);
            } finally {
                StreamUtil.cleanUp(outputStream);

                if ((tempFile != null) && tempFile.exists()) {
                    tempFile.delete();
                }
            }
        }
    } catch (FileNotFoundException fnfe) {
        if (_log.isWarnEnabled()) {
            _log.warn(">>> Unable to upload files" + fnfe);
        }
    }
}

From source file:org.atombeat.xquery.functions.util.GetZipEntries.java

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    try {/* www . java 2s.  c  o m*/
        String path = args[0].getStringValue();
        ZipFile zf = new ZipFile(path);
        log.debug(zf.getName());
        log.debug(zf.size());
        log.debug(zf.hashCode());
        ZipEntry e;
        Enumeration<? extends ZipEntry> entries = zf.entries();
        ValueSequence s = new ValueSequence();
        for (int i = 0; entries.hasMoreElements(); i++) {
            log.debug(i);
            e = entries.nextElement();
            log.debug(e.getName());
            log.debug(e.getComment());
            log.debug(e.isDirectory());
            log.debug(e.getCompressedSize());
            log.debug(e.getCrc());
            log.debug(e.getMethod());
            log.debug(e.getSize());
            log.debug(e.getTime());
            if (!e.isDirectory())
                s.add(new StringValue(e.getName()));
        }
        return s;
    } catch (Exception e) {
        throw new XPathException("error processing zip file: " + e.getLocalizedMessage(), e);
    }

}