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:nl.edia.sakai.tool.skinmanager.impl.SkinFileSystemServiceImpl.java

protected void handleEntry(ZipEntry myZipEntry, ZipFile myZipFile, File skinDir)
        throws SkinException, IOException {
    String myEntryName = myZipEntry.getName();
    boolean isMatched = isValidName(myEntryName);
    if (!isMatched) {
        LOG.warn("Skipping file entry: " + myEntryName + "");
        return;/*w w  w . j  a  v  a  2 s . c  om*/
    }
    File myFile = new File(skinDir, myEntryName);
    if (!FileSystemUtils.isParentOf(myFile, skinDir)) {
        throw new SkinException(
                "Error unpacking zip file, attempting to escape from skin dir! '" + myEntryName + "'");
    }
    if (!myFile.exists()) {
        if (myZipEntry.isDirectory()) {
            boolean myMkdirs = myFile.mkdirs();
            if (!myMkdirs) {
                throw new SkinException("Error unpacking zip file, cannot create directory '"
                        + myFile.getCanonicalPath() + "'");
            }
        } else {
            createFile(myZipEntry, myFile, myZipFile);
        }
    } else {
        if (myZipEntry.isDirectory()) {
            if (!myFile.isDirectory()) {
                if (!myFile.delete()) {
                    throw new SkinException(
                            "Error unpacking zip file, cannot remove file '" + myFile.getCanonicalPath() + "'");
                }
                if (!myFile.mkdirs()) {
                    throw new SkinException("Error unpacking zip file, cannot create directory '"
                            + myFile.getCanonicalPath() + "'");
                }
            }
        } else {
            if (myFile.isDirectory()) {
                FileSystemUtils.purge(myFile);
            }
            createFile(myZipEntry, myFile, myZipFile);
        }

    }
}

From source file:org.apache.maven.doxia.siterenderer.DefaultSiteRenderer.java

/** {@inheritDoc} */
public void copyResources(SiteRenderingContext siteRenderingContext, File outputDirectory) throws IOException {
    if (siteRenderingContext.getSkin() != null) {
        ZipFile file = getZipFile(siteRenderingContext.getSkin().getFile());

        try {//from www . j  a va  2  s  .co  m
            for (Enumeration<? extends ZipEntry> e = file.entries(); e.hasMoreElements();) {
                ZipEntry entry = e.nextElement();

                if (!entry.getName().startsWith("META-INF/")) {
                    File destFile = new File(outputDirectory, entry.getName());
                    if (!entry.isDirectory()) {
                        if (destFile.exists()) {
                            // don't override existing content: avoids extra rewrite with same content or extra site
                            // resource
                            continue;
                        }

                        destFile.getParentFile().mkdirs();

                        copyFileFromZip(file, entry, destFile);
                    } else {
                        destFile.mkdirs();
                    }
                }
            }
        } finally {
            closeZipFile(file);
        }
    }

    if (siteRenderingContext.isUsingDefaultTemplate()) {
        InputStream resourceList = getClass().getClassLoader()
                .getResourceAsStream(RESOURCE_DIR + "/resources.txt");

        if (resourceList != null) {
            Reader r = null;
            LineNumberReader reader = null;
            try {
                r = ReaderFactory.newReader(resourceList, ReaderFactory.UTF_8);
                reader = new LineNumberReader(r);

                String line;

                while ((line = reader.readLine()) != null) {
                    if (line.startsWith("#") || line.trim().length() == 0) {
                        continue;
                    }

                    InputStream is = getClass().getClassLoader().getResourceAsStream(RESOURCE_DIR + "/" + line);

                    if (is == null) {
                        throw new IOException("The resource " + line + " doesn't exist.");
                    }

                    File outputFile = new File(outputDirectory, line);

                    if (outputFile.exists()) {
                        // don't override existing content: avoids extra rewrite with same content or extra site
                        // resource
                        continue;
                    }

                    if (!outputFile.getParentFile().exists()) {
                        outputFile.getParentFile().mkdirs();
                    }

                    OutputStream os = null;
                    try {
                        // for the images
                        os = new FileOutputStream(outputFile);
                        IOUtil.copy(is, os);
                    } finally {
                        IOUtil.close(os);
                    }

                    IOUtil.close(is);
                }
            } finally {
                IOUtil.close(reader);
                IOUtil.close(r);
            }
        }
    }

    // Copy extra site resources
    for (File siteDirectory : siteRenderingContext.getSiteDirectories()) {
        File resourcesDirectory = new File(siteDirectory, "resources");

        if (resourcesDirectory != null && resourcesDirectory.exists()) {
            copyDirectory(resourcesDirectory, outputDirectory);
        }
    }

    // Check for the existence of /css/site.css
    File siteCssFile = new File(outputDirectory, "/css/site.css");
    if (!siteCssFile.exists()) {
        // Create the subdirectory css if it doesn't exist, DOXIA-151
        File cssDirectory = new File(outputDirectory, "/css/");
        boolean created = cssDirectory.mkdirs();
        if (created && getLogger().isDebugEnabled()) {
            getLogger().debug(
                    "The directory '" + cssDirectory.getAbsolutePath() + "' did not exist. It was created.");
        }

        // If the file is not there - create an empty file, DOXIA-86
        if (getLogger().isDebugEnabled()) {
            getLogger().debug(
                    "The file '" + siteCssFile.getAbsolutePath() + "' does not exist. Creating an empty file.");
        }
        Writer writer = null;
        try {
            writer = WriterFactory.newWriter(siteCssFile, siteRenderingContext.getOutputEncoding());
            //DOXIA-290...the file should not be 0 bytes.
            writer.write("/* You can override this file with your own styles */");
        } finally {
            IOUtil.close(writer);
        }
    }
}

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/*  ww w  . j ava 2 s  .co  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:org.openmrs.module.dhisconnector.api.impl.DHISConnectorServiceImpl.java

@SuppressWarnings("rawtypes")
@Override/*from ww w .  ja v  a2s  . com*/
public String uploadMappings(MultipartFile mapping) {
    String msg = "";
    String tempFolderName = OpenmrsUtil.getApplicationDataDirectory() + DHISCONNECTOR_TEMP_FOLDER
            + File.separator;
    String mappingFolderName = OpenmrsUtil.getApplicationDataDirectory() + DHISCONNECTOR_MAPPINGS_FOLDER
            + File.separator;
    String mappingName = mapping.getOriginalFilename();

    if (mappingName.endsWith(".zip")) {
        boolean allFailed = true;
        File tempMappings = new File(tempFolderName + mappingName);

        (new File(tempFolderName)).mkdirs();
        try {
            mapping.transferTo(tempMappings);

            try {
                ZipFile zipfile = new ZipFile(tempMappings);

                for (Enumeration e = zipfile.entries(); e.hasMoreElements();) {
                    ZipEntry entry = (ZipEntry) e.nextElement();

                    if (entry.isDirectory()) {
                        System.out.println("Incorrect file (Can't be a folder instead): " + entry.getName()
                                + " has been ignored");
                    } else if (entry.getName().endsWith(DHISCONNECTOR_MAPPING_FILE_SUFFIX)) {
                        File outputFile = new File(mappingFolderName, entry.getName());

                        if (outputFile.exists()) {
                            System.out.println(
                                    "File: " + outputFile.getName() + " already exists and has been ignored");
                        } else {
                            BufferedInputStream inputStream = new BufferedInputStream(
                                    zipfile.getInputStream(entry));
                            BufferedOutputStream outputStream = new BufferedOutputStream(
                                    new FileOutputStream(outputFile));

                            try {
                                System.out.println("Extracting: " + entry);
                                IOUtils.copy(inputStream, outputStream);
                                allFailed = false;
                            } finally {
                                outputStream.close();
                                inputStream.close();
                            }
                        }
                    } else {
                        System.out.println("Incorrect file: " + entry.getName() + " has been ignored");
                    }
                }
                if (!allFailed) {
                    msg = Context.getMessageSourceService()
                            .getMessage("dhisconnector.uploadMapping.groupSuccess");
                } else {
                    msg = Context.getMessageSourceService().getMessage("dhisconnector.uploadMapping.allFailed");
                }
                FileUtils.deleteDirectory(new File(tempFolderName));
            } catch (Exception e) {
                System.out.println("Error while extracting file:" + mapping.getName() + " ; " + e);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else if (mappingName.endsWith(DHISCONNECTOR_MAPPING_FILE_SUFFIX)) {
        try {
            File uploadedMapping = new File(mappingFolderName + mappingName);
            if (uploadedMapping.exists()) {
                msg = Context.getMessageSourceService().getMessage("dhisconnector.uploadMapping.exists");
            } else {
                mapping.transferTo(uploadedMapping);
                msg = Context.getMessageSourceService().getMessage("dhisconnector.uploadMapping.singleSuccess");
            }

        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        msg = Context.getMessageSourceService().getMessage("dhisconnector.uploadMapping.wrongType");
    }

    return msg;
}

From source file:fr.paris.lutece.plugins.upload.web.UploadJspBean.java

/**
 * Process file upload/*from  ww  w . j  a v  a2 s .c  om*/
 *
 * @param request Http request
 * @return Html form
 */
public String doCreateFile(HttpServletRequest request) {
    String strDirectoryIndex = null;

    try {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        FileItem item = multiRequest.getFile(PARAMETER_FILE_NAME);

        // The index and value of the directory combo in the form
        strDirectoryIndex = multiRequest.getParameter(PARAMETER_DIRECTORY);

        String strRelativeDirectory = getDirectory(strDirectoryIndex);

        // The absolute path of the target directory
        String strDestDirectory = AppPathService.getWebAppPath() + strRelativeDirectory;

        // List the files in the target directory
        File[] existingFiles = (new File(strDestDirectory)).listFiles();

        // Is the 'unzip' checkbox checked?
        boolean bUnzip = (multiRequest.getParameter(PARAMETER_UNZIP) != null);

        if (item != null && !item.getName().equals(StringUtils.EMPTY)) {
            if (!bUnzip) // copy the file
            {
                AppLogService.debug("copying the file");

                // Getting downloadFile's name
                String strNameFile = FileUploadService.getFileNameOnly(item);

                // Clean name
                String strClearName = UploadUtil.cleanFileName(strNameFile);

                // Checking duplicate
                if (duplicate(strClearName, existingFiles)) {
                    return AdminMessageService.getMessageUrl(request, MESSAGE_FILE_EXISTS,
                            AdminMessage.TYPE_STOP);
                }

                // Move the file to the target directory
                File destFile = new File(strDestDirectory, strClearName);

                FileOutputStream fos = new FileOutputStream(destFile);
                fos.flush();
                fos.write(item.get());
                fos.close();
            } else // unzip the file
            {
                AppLogService.debug("unzipping the file");

                ZipFile zipFile;

                try {
                    // Create a temporary file with result of getTime() as unique file name
                    File tempFile = File.createTempFile(Long.toString((new Date()).getTime()), ".zip");
                    // Delete temp file when program exits.
                    tempFile.deleteOnExit();

                    FileOutputStream fos = new FileOutputStream(tempFile);
                    fos.flush();
                    fos.write(item.get());
                    fos.close();
                    zipFile = new ZipFile(tempFile);
                } catch (ZipException ze) {
                    AppLogService.error("Error opening zip file", ze);

                    return AdminMessageService.getMessageUrl(request, MESSAGE_ZIP_ERROR,
                            AdminMessage.TYPE_STOP);
                }

                // Each zipped file is indentified by a zip entry :
                Enumeration zipEntries = zipFile.entries();

                while (zipEntries.hasMoreElements()) {
                    ZipEntry zipEntry = (ZipEntry) zipEntries.nextElement();

                    // Clean the name :
                    String strZippedName = zipEntry.getName();
                    String strClearName = UploadUtil.cleanFilePath(strZippedName);

                    if (strZippedName.equals(strClearName)) {
                        // The unzipped file :
                        File destFile = new File(strDestDirectory, strClearName);

                        // Create the parent directory structure if needed :
                        destFile.getParentFile().mkdirs();

                        if (!zipEntry.isDirectory()) // don't unzip directories
                        {
                            AppLogService.debug("unzipping " + strZippedName + " to " + destFile.getName());

                            // InputStream from zipped data
                            InputStream inZipStream = zipFile.getInputStream(zipEntry);

                            // OutputStream to the destination file
                            OutputStream outDestStream = new FileOutputStream(destFile);

                            // Helper method to copy data
                            copyStream(inZipStream, outDestStream);

                            inZipStream.close();
                            outDestStream.close();
                        } else {
                            AppLogService.debug("skipping directory " + strZippedName);
                        }
                    } else {
                        AppLogService.debug("skipping accented file " + strZippedName);
                    }
                }
            }
        } else {
            return AdminMessageService.getMessageUrl(request, Messages.MANDATORY_FIELDS,
                    AdminMessage.TYPE_STOP);
        }
    } catch (IOException e) {
        AppLogService.error(e.getMessage(), e);
    }

    // Returns upload management page
    UrlItem url = new UrlItem(getHomeUrl(request));

    if (strDirectoryIndex != null) {
        url.addParameter(PARAMETER_DIRECTORY, strDirectoryIndex);
    }

    return url.getUrl();
}

From source file:com.esd.ps.EmployerController.java

/**
 * ? zip//  w w  w.  jav a 2 s  . c  o m
 * 
 * @param packName
 * @param taskLvl
 */
public void storeDataZIP(String packName, int taskLvl, String url, int userId, Date date) {
    InputStream in = null;
    String zipEntryName = null;
    int packId = 0;
    try {
        ZipFile zip = new ZipFile(url + Constants.SLASH + packName);
        for (Enumeration<?> entries = zip.entries(); entries.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            String taskDir = Constants.EMPTY;
            if (entry.isDirectory()) {// ?
                continue;
            }
            zipEntryName = entry.getName();
            if (zipEntryName.indexOf(Constants.SLASH) < zipEntryName.lastIndexOf(Constants.SLASH)) {
                String str[] = zipEntryName.split(Constants.SLASH);
                // (zipEntryName.indexOf("/") + 1)
                taskDir = zipEntryName.substring((zipEntryName.indexOf(Constants.SLASH) + 1),
                        zipEntryName.lastIndexOf(Constants.SLASH));
                zipEntryName = str[(str.length - 1)];
            }
            zipEntryName = zipEntryName.substring(zipEntryName.indexOf(Constants.SLASH) + 1,
                    zipEntryName.length());
            // ?
            if (zipEntryName.substring((zipEntryName.length() - 3), zipEntryName.length())
                    .equals(Constants.WAV) == false) {
                // String noMatch = zipEntryName;
                continue;
            }
            in = zip.getInputStream(entry);
            // inputstrem?byte[]
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] data = new byte[4096];
            int count = -1;
            while ((count = in.read(data, 0, 4096)) != -1)
                outStream.write(data, 0, count);
            data = null;
            byte[] wav = outStream.toByteArray();

            taskWithBLOBs taskWithBLOBs = new taskWithBLOBs();
            packId = packService.getPackIdByPackName(packName);
            // wav?0kb
            if (outStream.size() == 0) {
                taskWithBLOBs.setWorkerId(0);
            }
            taskWithBLOBs.setTaskWav(wav);
            taskWithBLOBs.setTaskLvl(taskLvl);
            // ?
            taskWithBLOBs.setPackId(packId);
            taskWithBLOBs.setTaskName(zipEntryName);
            // 
            if (taskDir.trim().length() > 0) {
                taskDir = packName.substring(0, (packName.length() - 4)) + Constants.SLASH + taskDir;
            } else {
                taskDir = packName.substring(0, (packName.length() - 4));
            }
            taskWithBLOBs.setTaskDir(taskDir);
            taskWithBLOBs.setCreateId(userId);
            taskWithBLOBs.setCreateTime(date);
            // ?
            taskWithBLOBs.setTaskUpload(false);
            StackTraceElement[] items = Thread.currentThread().getStackTrace();
            taskWithBLOBs.setCreateMethod(items[1].toString());
            taskWithBLOBs.setVersion(1);
            taskService.insert(taskWithBLOBs);
        }
        zip.close();
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    File fd = new File(packName);
    fd.delete();
    packWithBLOBs pack = new packWithBLOBs();
    pack.setPackId(packId);
    pack.setUnzip(2);// ??
    StackTraceElement[] items = Thread.currentThread().getStackTrace();
    pack.setUpdateMethod(items[1].toString());
    packService.updateByPrimaryKeySelective(pack);
}

From source file:org.openmrs.module.dhisconnector.api.impl.DHISConnectorServiceImpl.java

private void unZipDHIS2APIBackupToTemp(String zipFile) {
    byte[] buffer = new byte[1024];
    String outputFolder = OpenmrsUtil.getApplicationDataDirectory() + DHISCONNECTOR_TEMP_FOLDER;

    try {/*from   w w w . j a v  a  2 s  . c o m*/
        File destDir = new File(outputFolder);
        if (!destDir.exists()) {
            destDir.mkdir();
        }
        ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry entry = zipIn.getNextEntry();

        while (entry != null) {
            String filePath = outputFolder + File.separator + entry.getName();
            if (!entry.isDirectory()) {
                if (!(new File(filePath)).getParentFile().exists()) {
                    (new File(filePath)).getParentFile().mkdirs();
                }
                (new File(filePath)).createNewFile();
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
                byte[] bytesIn = buffer;
                int read = 0;
                while ((read = zipIn.read(bytesIn)) != -1) {
                    bos.write(bytesIn, 0, read);
                }
                bos.close();
            } else {
                // if the entry is a directory, make the directory
                File dir = new File(filePath);
                dir.mkdir();
            }
            zipIn.closeEntry();
            entry = zipIn.getNextEntry();
        }
        zipIn.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:hoot.services.controllers.ingest.FileUploadResource.java

protected JSONObject _getZipContentType(final String zipFilePath, JSONArray contentTypes, String fName)
        throws Exception {
    JSONObject resultStat = new JSONObject();
    String[] extList = { "gdb", "osm", "shp" };

    int shpCnt = 0;
    int osmCnt = 0;
    int fgdbCnt = 0;
    ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath));
    ZipEntry ze = zis.getNextEntry();

    while (ze != null) {
        String zipName = ze.getName();
        // check to see if zipName ends with slash and remove
        if (zipName.endsWith("/")) {
            zipName = zipName.substring(0, zipName.length() - 1);
        }/*w w w .j a v a2s .c om*/

        String[] fileNameParts = zipName.split("\\.");
        String ext = null;

        int partsLen = fileNameParts.length;
        if (partsLen > 1) {
            ext = fileNameParts[partsLen - 1];
        }

        //See if there is extension and if none then throw error
        if (ext == null) {
            throw new Exception("Unknown file type.");
        } else {
            // for each type of extensions
            for (int i = 0; i < extList.length; i++) {
                if (ext.equalsIgnoreCase(extList[i])) {
                    if (ze.isDirectory()) {
                        if (ext.equals("gdb")) {
                            JSONObject contentType = new JSONObject();
                            contentType.put("type", "FGDB_ZIP");
                            contentType.put("name", fName + "/" + zipName);
                            contentTypes.add(contentType);
                            fgdbCnt++;
                        } else {
                            throw new Exception("Unknown folder type. Only gdb folder type is supported.");
                        }
                    } else //file
                    {
                        if (ext.equals("shp")) {
                            JSONObject contentType = new JSONObject();
                            contentType.put("type", "OGR_ZIP");
                            contentType.put("name", fName + "/" + zipName);
                            contentTypes.add(contentType);
                            shpCnt++;
                        } else if (ext.equals("osm")) {
                            JSONObject contentType = new JSONObject();
                            contentType.put("type", "OSM_ZIP");
                            contentType.put("name", fName + "/" + zipName);
                            contentTypes.add(contentType);
                            osmCnt++;
                        } else {
                            // We will not throw error here since shape file can contain mutiple types of support files.
                            // We will let hoot-core decide if it can handle the zip.
                        }
                    }
                }
                // We do not allow mix of ogr and osm in zip
                if ((shpCnt + fgdbCnt) > 0 && osmCnt > 0) {
                    throw new Exception("Zip should not contain both osm and ogr types.");
                }
            }

        }

        ze = zis.getNextEntry();
    }

    zis.closeEntry();
    zis.close();

    resultStat.put("shpcnt", shpCnt);
    resultStat.put("fgdbcnt", fgdbCnt);
    resultStat.put("osmcnt", osmCnt);

    return resultStat;
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.customer.FileSystemViewHandler.java

private void unzipFile(File file) {
    String zipFileFullPath = file.getPath();// path contains file name
    String zipFilePath = zipFileFullPath.substring(0, zipFileFullPath.indexOf(file.getName()));// path without file
                                                                                               // name
    ZipInputStream zin = null;//from w ww  . j  ava  2s.co m
    try {
        zin = new ZipInputStream(new FileInputStream(zipFileFullPath));
        ZipEntry zipEntry = null;
        byte[] buf = new byte[1024];

        while ((zipEntry = zin.getNextEntry()) != null) {
            String zipEntryName = zipEntry.getName();
            String newPath = zipFilePath + File.separator
                    + file.getName().substring(0, file.getName().lastIndexOf(".")) + File.separator
                    + zipEntryName;// original path +
                                                                                                                                                                 // zipfile Name + entry
                                                                                                                                                                 // name
            File outfile = new File(newPath);
            if (zipEntry.isDirectory()) {
                outfile.mkdirs();
                continue;
            } else {
                if (!outfile.getParentFile().exists()) {
                    outfile.getParentFile().mkdirs();
                }
            }

            OutputStream os = new BufferedOutputStream(new FileOutputStream(outfile));
            int readLen = 0;
            try {
                readLen = zin.read(buf, 0, 1024);
            } catch (IOException ioe) {
                readLen = -1;
            }
            while (readLen != -1) {
                os.write(buf, 0, readLen);
                try {
                    readLen = zin.read(buf, 0, 1024);
                } catch (IOException ioe) {
                    readLen = -1;
                }
            }
            os.close();
        }
    } catch (IOException e) {
        s_logger.error("unzip file error.", e);
    } finally {
        if (zin != null) {
            try {
                zin.close();
            } catch (IOException e) {
                s_logger.error("Error occurs.", e);
            }
        }
    }
}

From source file:dev.dworks.apps.anexplorer.provider.ExternalStorageProvider.java

private void includeZIPFile(MatrixCursor result, String docId, ZipEntry zipEntry) throws FileNotFoundException {

    int flags = 0;

    final String displayName = zipEntry.getName();
    final String mimeType = ""; //getTypeForFile(zipEntry);

    final RowBuilder row = result.newRow();
    row.add(Document.COLUMN_DOCUMENT_ID, docId);
    row.add(Document.COLUMN_DISPLAY_NAME, displayName);
    row.add(Document.COLUMN_SIZE, zipEntry.getSize());
    row.add(Document.COLUMN_MIME_TYPE, mimeType);
    row.add(Document.COLUMN_PATH, "");//zipEntry.getAbsolutePath());
    row.add(Document.COLUMN_FLAGS, flags);
    if (zipEntry.isDirectory()) {
        row.add(Document.COLUMN_SUMMARY, "? files");
    }//from  ww  w .  ja v a 2s  .co  m

    // Only publish dates reasonably after epoch
    long lastModified = zipEntry.getTime();
    if (lastModified > 31536000000L) {
        row.add(Document.COLUMN_LAST_MODIFIED, lastModified);
    }
}