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:fr.certu.chouette.exchange.xml.neptune.importer.XMLNeptuneImportLinePlugin.java

/**
 * import ZipFile//from w  ww  .  ja  v a2 s  .  com
 * 
 * @param filePath
 *           path to zip File
 * @param validate
 *           process XML and XSD format validation
 * @param importReport
 *           report to fill
 * @param optimizeMemory
 * @param unsharedData
 * @param sharedData
 * @return list of loaded lines
 */
private List<Line> processZipImport(String filePath, boolean validate, Report importReport,
        Report validationReport, boolean optimizeMemory, SharedImportedData sharedData,
        UnsharedImportedData unsharedData) {
    ZipFile zip = null;
    try {
        Charset encoding = FileTool.getZipCharset(filePath);
        if (encoding == null) {
            ReportItem item = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_ERROR, Report.STATE.ERROR,
                    filePath, "unknown encoding");
            importReport.addItem(item);
            importReport.updateStatus(Report.STATE.ERROR);
            logger.error("zip import failed (unknown encoding)");
            return null;
        }
        zip = new ZipFile(filePath);
    } catch (IOException e) {
        // report for save
        ReportItem fileErrorItem = new ExchangeReportItem(ExchangeReportItem.KEY.ZIP_ERROR, Report.STATE.ERROR,
                e.getLocalizedMessage());
        importReport.addItem(fileErrorItem);
        // log
        logger.error("zip import failed (cannot open zip)" + e.getLocalizedMessage());
        return null;
    }
    List<Line> lines = new ArrayList<Line>();
    for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {
        ZipEntry entry = entries.nextElement();

        // ignore directory without warning
        if (entry.isDirectory())
            continue;

        String entryName = entry.getName();
        if (!FilenameUtils.getExtension(entryName).toLowerCase().equals("xml")) {
            // report for save
            ReportItem fileReportItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_IGNORED,
                    Report.STATE.OK, entryName);
            importReport.addItem(fileReportItem);
            // log
            logger.info("zip entry " + entryName + " bypassed ; not a XML file");
            continue;
        }
        logger.info("start import zip entry " + entryName);
        ReportItem fileReportItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE, Report.STATE.OK,
                entryName);
        importReport.addItem(fileReportItem);
        try {
            InputStream stream = zip.getInputStream(entry);
            stream.close();
        } catch (IOException e) {
            // report for save
            ReportItem errorItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_ERROR, Report.STATE.ERROR,
                    e.getLocalizedMessage());
            fileReportItem.addItem(errorItem);
            // log
            logger.error("zip entry " + entryName + " import failed (get entry)" + e.getLocalizedMessage());
            continue;
        }
        ChouettePTNetworkHolder holder = null;
        try {
            holder = reader.read(zip, entry, validate);
            validationReport.addItem(holder.getReport());
        } catch (ExchangeRuntimeException e) {
            // report for save
            ReportItem errorItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_ERROR, Report.STATE.ERROR,
                    e.getLocalizedMessage());
            fileReportItem.addItem(errorItem);
            // log
            logger.error("zip entry " + entryName + " import failed (read XML)" + e.getLocalizedMessage());
            continue;
        } catch (Exception e) {
            // report for save
            ReportItem errorItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_ERROR, Report.STATE.ERROR,
                    e.getLocalizedMessage());
            fileReportItem.addItem(errorItem);
            // log
            logger.error(e.getLocalizedMessage());
            continue;
        }
        try {
            Line line = processImport(holder, validate, fileReportItem, validationReport, entryName, sharedData,
                    unsharedData, optimizeMemory);

            if (line != null) {
                lines.add(line);
            } else {
                logger.error("zip entry " + entryName + " import failed (build model)");
            }

        } catch (ExchangeException e) {
            // report for save
            ReportItem errorItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_ERROR, Report.STATE.ERROR,
                    e.getLocalizedMessage());
            fileReportItem.addItem(errorItem);
            // log
            logger.error(
                    "zip entry " + entryName + " import failed (convert to model)" + e.getLocalizedMessage());
            continue;
        }
        logger.info("zip entry imported");
    }
    try {
        zip.close();
    } catch (IOException e) {
        logger.info("cannot close zip file");
    }
    if (lines.size() == 0) {
        logger.error("zip import failed (no valid entry)");
        return null;
    }
    return lines;
}

From source file:com.seajas.search.contender.service.modifier.FeedModifierService.java

/**
 * Retrieve the content of a result feed URL.
 * /*from w w w  .j  a  va  2 s.c o  m*/
 * @param uri
 * @param encodingOverride
 * @param userAgent
 * @param resultHeaders
 * @return Reader
 */
private Reader getContent(final URI uri, final String encodingOverride, final String userAgent,
        final Map<String, String> resultHeaders) {
    Reader result = null;
    String contentType = null;

    // Retrieve the feed

    try {
        InputStream inputStream = null;

        if (uri.getScheme().equalsIgnoreCase("ftp") || uri.getScheme().equalsIgnoreCase("ftps")) {
            FTPClient ftpClient = uri.getScheme().equalsIgnoreCase("ftps") ? new FTPSClient() : new FTPClient();

            try {
                ftpClient.connect(uri.getHost(), uri.getPort() != -1 ? uri.getPort() : 21);

                if (StringUtils.hasText(uri.getUserInfo())) {
                    if (uri.getUserInfo().contains(":"))
                        ftpClient.login(uri.getUserInfo().substring(0, uri.getUserInfo().indexOf(":")),
                                uri.getUserInfo().substring(uri.getUserInfo().indexOf(":") + 1));
                    else
                        ftpClient.login(uri.getUserInfo(), "");

                    inputStream = ftpClient.retrieveFileStream(uri.getPath());
                }
            } finally {
                ftpClient.disconnect();
            }
        } else if (uri.getScheme().equalsIgnoreCase("file")) {
            File file = new File(uri);

            if (!file.isDirectory())
                inputStream = new FileInputStream(uri.getPath());
            else
                inputStream = RSSDirectoryBuilder.build(file);
        } else if (uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equalsIgnoreCase("https")) {
            try {
                HttpGet method = new HttpGet(uri.toString());

                if (resultHeaders != null)
                    for (Entry<String, String> resultHeader : resultHeaders.entrySet())
                        method.setHeader(new BasicHeader(resultHeader.getKey(), resultHeader.getValue()));
                if (userAgent != null)
                    method.setHeader(CoreProtocolPNames.USER_AGENT, userAgent);

                SizeRestrictedHttpResponse response = httpClient.execute(method,
                        new SizeRestrictedResponseHandler(maximumContentLength, uri));

                try {
                    if (response != null) {
                        inputStream = new ByteArrayInputStream(response.getResponse());
                        contentType = response.getContentType() != null ? response.getContentType().getValue()
                                : null;
                    } else
                        return null;
                } catch (RuntimeException e) {
                    method.abort();

                    throw e;
                }
            } catch (IllegalArgumentException e) {
                logger.error("Invalid URL " + uri.toString() + " - not returning content", e);

                return null;
            }
        } else {
            logger.error("Unknown protocol " + uri.getScheme() + ". Skipping feed.");

            return null;
        }

        // Guess the character encoding using ROME's reader, then buffer it so we can discard the input stream (and close the connection)

        InputStream readerInputStream = new BufferedInputStream(inputStream);
        MediaType mediaType = autoDetectParser.getDetector().detect(readerInputStream, new Metadata());

        try {
            Reader reader = null;

            if (mediaType.getType().equals("application")) {
                if (mediaType.getSubtype().equals("x-gzip")) {
                    GZIPInputStream gzipInputStream = new GZIPInputStream(readerInputStream);

                    if (encodingOverride != null)
                        reader = readerToBuffer(new StringBuffer(),
                                new InputStreamReader(gzipInputStream, encodingOverride), false);
                    else
                        reader = readerToBuffer(new StringBuffer(),
                                contentType != null ? new XmlHtmlReader(gzipInputStream, contentType, true)
                                        : new XmlReader(gzipInputStream, true),
                                false);

                    gzipInputStream.close();
                } else if (mediaType.getSubtype().equals("zip")) {
                    ZipFile zipFile = null;

                    // ZipInputStream can't do read-aheads, so we have to use a temporary on-disk file instead

                    File temporaryFile = File.createTempFile("profiler-", ".zip");

                    try {
                        FileOutputStream zipOutputStream = new FileOutputStream(temporaryFile);
                        IOUtils.copy(readerInputStream, zipOutputStream);

                        readerInputStream.close();

                        zipOutputStream.flush();
                        zipOutputStream.close();

                        // Create a new entry and process it

                        zipFile = new ZipFile(temporaryFile);
                        Enumeration<? extends ZipEntry> zipEnumeration = zipFile.entries();

                        ZipEntry zipEntry = zipEnumeration.nextElement();

                        if (zipEntry == null || zipEntry.isDirectory() || zipEnumeration.hasMoreElements()) {
                            logger.error(
                                    "ZIP files are currently expected to contain one and only one entry, which is to be a file");

                            return null;
                        }

                        // We currently only perform prolog stripping for ZIP files

                        InputStream zipInputStream = new BufferedInputStream(zipFile.getInputStream(zipEntry));

                        if (encodingOverride != null)
                            reader = readerToBuffer(new StringBuffer(), new InputStreamReader(
                                    new BufferedInputStream(zipInputStream), encodingOverride), true);
                        else
                            result = readerToBuffer(new StringBuffer(),
                                    contentType != null
                                            ? new XmlHtmlReader(new BufferedInputStream(zipInputStream),
                                                    contentType, true)
                                            : new XmlReader(new BufferedInputStream(zipInputStream), true),
                                    true);
                    } catch (Exception e) {
                        logger.error("An error occurred during ZIP file processing", e);

                        return null;
                    } finally {
                        if (zipFile != null)
                            zipFile.close();

                        if (!temporaryFile.delete())
                            logger.error("Unable to delete temporary file");
                    }
                }
            }

            if (result == null) {
                if (encodingOverride != null)
                    result = readerToBuffer(new StringBuffer(), reader != null ? reader
                            : new InputStreamReader(readerInputStream, encodingOverride), false);
                else
                    result = readerToBuffer(new StringBuffer(),
                            reader != null ? reader
                                    : contentType != null
                                            ? new XmlHtmlReader(readerInputStream, contentType, true)
                                            : new XmlReader(readerInputStream, true),
                            false);
            }
        } catch (Exception e) {
            logger.error("An error occurred during stream processing", e);

            return null;
        } finally {
            inputStream.close();
        }
    } catch (IOException e) {
        logger.error("Could not retrieve the given feed: " + e.getMessage(), e);

        return null;
    }

    return result;
}

From source file:com.dsh105.commodus.data.Updater.java

/**
 * Part of Zip-File-Extractor, modified by Gravity for use with Bukkit
 *//* ww w .  ja  v  a  2s.  c om*/
private void unzip(String file) {
    try {
        final File fSourceZip = new File(file);
        final String zipPath = file.substring(0, file.length() - 4);
        ZipFile zipFile = new ZipFile(fSourceZip);
        Enumeration<? extends ZipEntry> e = zipFile.entries();
        while (e.hasMoreElements()) {
            ZipEntry entry = e.nextElement();
            File destinationFilePath = new File(zipPath, entry.getName());
            destinationFilePath.getParentFile().mkdirs();
            if (entry.isDirectory()) {
                continue;
            } else {
                final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                int b;
                final byte buffer[] = new byte[Updater.BYTE_SIZE];
                final FileOutputStream fos = new FileOutputStream(destinationFilePath);
                final BufferedOutputStream bos = new BufferedOutputStream(fos, Updater.BYTE_SIZE);
                while ((b = bis.read(buffer, 0, Updater.BYTE_SIZE)) != -1) {
                    bos.write(buffer, 0, b);
                }
                bos.flush();
                bos.close();
                bis.close();
                final String name = destinationFilePath.getName();
                if (name.endsWith(".jar") && this.pluginFile(name)) {
                    destinationFilePath.renameTo(
                            new File(this.plugin.getDataFolder().getParent(), this.updateFolder + "/" + name));
                }
            }
            entry = null;
            destinationFilePath = null;
        }
        e = null;
        zipFile.close();
        zipFile = null;

        // Move any plugin data folders that were included to the right place, Bukkit won't do this for us.
        for (final File dFile : new File(zipPath).listFiles()) {
            if (dFile.isDirectory()) {
                if (this.pluginFile(dFile.getName())) {
                    final File oFile = new File(this.plugin.getDataFolder().getParent(), dFile.getName()); // Get current dir
                    final File[] contents = oFile.listFiles(); // List of existing files in the current dir
                    for (final File cFile : dFile.listFiles()) // Loop through all the files in the new dir
                    {
                        boolean found = false;
                        for (final File xFile : contents) // Loop through contents to see if it exists
                        {
                            if (xFile.getName().equals(cFile.getName())) {
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            // Move the new file into the current dir
                            cFile.renameTo(new File(oFile.getCanonicalFile() + "/" + cFile.getName()));
                        } else {
                            // This file already exists, so we don't need it anymore.
                            cFile.delete();
                        }
                    }
                }
            }
            dFile.delete();
        }
        new File(zipPath).delete();
        fSourceZip.delete();
    } catch (final IOException ex) {
        this.plugin.getLogger()
                .warning("The auto-updater tried to unzip a new update file, but was unsuccessful.");
        this.result = Updater.UpdateResult.FAIL_DOWNLOAD;
        ex.printStackTrace();
    }
    new File(file).delete();
}

From source file:com.cubeia.maven.plugin.firebase.FirebaseRunPlugin.java

private void explode(ZipFile file, File dir) throws IOException {
    for (Enumeration<? extends ZipEntry> en = file.entries(); en.hasMoreElements();) {
        ZipEntry entry = en.nextElement();
        File next = new File(dir, entry.getName());
        if (entry.isDirectory()) {
            next.mkdirs();/*www.j  a  v a2 s.  co  m*/
        } else {
            next.createNewFile();
            if (next.getParentFile() != null) {
                next.getParentFile().mkdirs();
            }
            InputStream in = file.getInputStream(entry);
            OutputStream out = new FileOutputStream(next);
            try {
                IOUtils.copy(in, out);
            } finally {
                IOUtils.closeQuietly(out);
                IOUtils.closeQuietly(in);
            }
        }
    }
}

From source file:org.apache.gobblin.aws.AWSJobConfigurationManager.java

/***
 * Unzip a zip archive/*from   w  ww .j a  v a  2  s  .c o m*/
 * @param file Zip file to unarchive
 * @param outputDir Output directory for the unarchived file
 * @throws IOException If any issue occurs in unzipping the file
 */
public void unzipArchive(String file, File outputDir) throws IOException {

    try (ZipFile zipFile = new ZipFile(file)) {

        final Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            final File entryDestination = new File(outputDir, entry.getName());
            if (!org.apache.gobblin.util.FileUtils.isSubPath(outputDir, entryDestination)) {
                throw new IOException(
                        String.format("Extracted file: %s is trying to write outside of output directory: %s",
                                entryDestination, outputDir));
            }

            if (entry.isDirectory()) {
                // If entry is directory, create directory
                if (!entryDestination.mkdirs() && !entryDestination.exists()) {
                    throw new IOException("Could not create directory: " + entryDestination
                            + " while un-archiving zip: " + file);
                }
            } else {
                // Create parent dirs if required
                if (!entryDestination.getParentFile().mkdirs() && !entryDestination.getParentFile().exists()) {
                    throw new IOException("Could not create parent directory for: " + entryDestination
                            + " while un-archiving zip: " + file);
                }

                // Extract and save the conf file
                InputStream in = null;
                OutputStream out = null;
                try {
                    in = zipFile.getInputStream(entry);
                    out = new FileOutputStream(entryDestination);
                    IOUtils.copy(in, out);
                } finally {
                    if (null != in)
                        IOUtils.closeQuietly(in);
                    if (null != out)
                        IOUtils.closeQuietly(out);
                }
            }
        }
    }
}

From source file:com.mindquarry.desktop.workspace.SVNTestBase.java

/**
 * Extracts the zip file <code>zipName</code> into the folder
 * <code>destinationPath</code>.
 *///from w  ww .ja v  a2  s  . c  o m
private void extractZip(String zipName, String destinationPath) throws IOException {
    File dest = new File(destinationPath);
    // delete if test has failed and extracted dir is still present
    FileUtils.deleteDirectory(dest);
    dest.mkdirs();

    byte[] buffer = new byte[1024];
    ZipEntry zipEntry;
    ZipInputStream zipInputStream = new ZipInputStream(
            new FileInputStream("src/test/resources/com/mindquarry/desktop/workspace/" + zipName));

    while (null != (zipEntry = zipInputStream.getNextEntry())) {

        File zippedFile = new File(destinationPath + zipEntry.getName());

        if (zipEntry.isDirectory()) {
            zippedFile.mkdirs();
        } else {
            // ensure the parent directory exists
            zippedFile.getParentFile().mkdirs();

            OutputStream fileOutStream = new FileOutputStream(zippedFile);
            transferBytes(zipInputStream, fileOutStream, buffer);
            fileOutStream.close();
        }
    }

    zipInputStream.close();
}

From source file:es.eucm.mokap.backend.controller.insert.MokapInsertController.java

/**
 * Processes a temp file stored in Cloud Storage: -It analyzes its contents
 * -Processes the descriptor.json file and stores the entity in Datastore
 * -Finally it stores the thumbnails and contents.zip in Cloud Storage
 * //w  ww .ja v  a 2 s . c  om
 * @param tempFileName
 *            name of the temp file we are going to process
 * @return The Datastore Key id for the entity we just created (entityRef in
 *         RepoElement)
 * @throws IOException
 *             If the file is not accessible or Cloud Storage is not
 *             available ServerError If a problem is found with the internal
 *             structure of the file
 */
private long processUploadedTempFile(String tempFileName) throws IOException, ServerError {
    long assignedKeyId;
    // Read the cloud storage file
    byte[] content = null;
    String descriptor = "";
    Map<String, byte[]> tns = new HashMap<String, byte[]>();
    InputStream is = st.readFile(tempFileName);
    ZipInputStream zis = new ZipInputStream(is);
    ZipEntry entry;
    while ((entry = zis.getNextEntry()) != null) {
        String filename = entry.getName();
        if (UploadZipStructure.isContentsFile(filename)) {
            content = IOUtils.toByteArray(zis);
        } else if (UploadZipStructure.isDescriptorFile(filename)) {
            BufferedReader br = new BufferedReader(new InputStreamReader(zis, "UTF-8"));
            String str;
            while ((str = br.readLine()) != null) {
                descriptor += str;
            }
        } else if (entry.isDirectory()) {
            continue;
        }
        // Should be a thumbnail
        else if (UploadZipStructure.checkThumbnailImage(filename)) {
            byte[] img = IOUtils.toByteArray(zis);
            tns.put(filename, img);
        }
        zis.closeEntry();
    }

    try {
        if (descriptor != null && !descriptor.equals("") && content != null) {
            // Analizar json
            Map<String, Object> entMap = Utils.jsonToMap(descriptor);
            // Parse the map into an entity
            Entity ent = new Entity("Resource");
            for (String key : entMap.keySet()) {
                ent.setProperty(key, entMap.get(key));
            }
            // Store the entity (GDS) and get the Id
            Key k = db.storeEntity(ent);
            assignedKeyId = k.getId();

            // Store the contents file with the Id in the name
            ByteArrayInputStream bis = new ByteArrayInputStream(content);
            st.storeFile(bis, assignedKeyId + UploadZipStructure.ZIP_EXTENSION);

            // Store the thumbnails in a folder with the id as the name
            for (String key : tns.keySet()) {
                ByteArrayInputStream imgs = new ByteArrayInputStream(tns.get(key));
                st.storeFile(imgs, assignedKeyId + "/" + key);
            }
            // Create the Search Index Document
            db.addToSearchIndex(ent, k);

            // Everything went ok, so we delete the temp file
            st.deleteFile(tempFileName);
        } else {
            assignedKeyId = 0;
            if (descriptor == null || descriptor.equals("")) {
                throw new ServerError(ServerReturnMessages.INVALID_UPLOAD_DESCRIPTOR);
            } else {
                throw new ServerError(ServerReturnMessages.INVALID_UPLOAD_CONTENT);
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
        assignedKeyId = 0;
        // Force rollback if anything failed
        try {
            st.deleteFile(tempFileName);
            for (String key : tns.keySet()) {
                ByteArrayInputStream imgs = new ByteArrayInputStream(tns.get(key));
                st.deleteFile(assignedKeyId + "/" + key);
            }
            db.deleteEntity(assignedKeyId);
        } catch (Exception ex) {
        }
    }
    return assignedKeyId;
}

From source file:com.visural.stereotyped.ui.service.StereotypeServiceImpl.java

public ComponentLibrary readComponentLibrary(String name) {
    File jar = new File(getComponentJarsPath() + "/" + name);
    if (jar.exists()) {
        ZipInputStream zis = null;
        try {/*from w ww . j  a v  a2 s  .c om*/
            ComponentLibrary cl = new ComponentLibrary(jar.getName(), new HashSet(), new HashMap());
            File ovrDir = getOverrideLibPath(cl);
            zis = new ZipInputStream(new FileInputStream(jar));
            ZipEntry ze;
            while ((ze = zis.getNextEntry()) != null) {
                if (!ze.isDirectory()) {
                    if (!ze.getName().endsWith(".class")) {
                        // check for override first
                        File ovr = new File(ovrDir.getCanonicalPath() + "/" + ze.getName());
                        if (ovr.exists()) {
                            byte[] data = IOUtil.fileToByteArray(ovr.getCanonicalPath());
                            cl.getTemplate().put(ze.getName(), new Binary(data, true));
                        } else {
                            // no override, read from JAR
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            int r;
                            while ((r = zis.read()) != -1) {
                                baos.write(r);
                            }
                            cl.getTemplate().put(ze.getName(), new Binary(baos.toByteArray()));
                        }
                    } else {
                        Class c = getComponentClassWithName(ze.getName()
                                .substring(0, ze.getName().lastIndexOf(".class")).replace("/", "."));
                        if (c != null) {
                            cl.getComponents().add(c);
                        }
                    }
                }
            }
            addOverrideFiles(ovrDir.getAbsolutePath(), cl, ovrDir);
            return cl;
        } catch (IOException e) {
            throw new IllegalStateException(e);
        } finally {
            if (zis != null) {
                try {
                    zis.close();
                } catch (IOException ex) {
                    Logger.getLogger(StereotypeServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    } else {
        throw new IllegalArgumentException("Library " + name + " does not exist.");
    }
}

From source file:com.receipts.backingbeans.StoreView.java

public void importStores(FileUploadEvent event) {
    int userId = (int) event.getComponent().getAttributes().get("userId");
    UploadedFile zipFile = event.getFile();

    String insertStoresSql = "insert into stores (store_id, store_date, user_id) values (?, ?, ?)";
    String selectStoresSql = "select id from stores where store_id = ? and store_date = ?";
    String insertReceiptsSql = "insert into receipts (store_fk, user_id, img_name) values (?, ?, ?)";
    try (Connection conn = DbUtils.getDbConnection()) {
        try (ZipInputStream zin = new ZipInputStream(new BufferedInputStream(zipFile.getInputstream()));
                PreparedStatement insertStoresPs = conn.prepareStatement(insertStoresSql);
                PreparedStatement selectStoresPs = conn.prepareStatement(selectStoresSql);
                PreparedStatement insertReceiptsPs = conn.prepareStatement(insertReceiptsSql)) {
            ZipEntry entry;

            conn.setAutoCommit(false);// w w w  .  j ava 2 s.c  o  m

            while ((entry = zin.getNextEntry()) != null) {
                String entryName = entry.getName();
                boolean isDirectory = entry.isDirectory();

                if (isDirectory) {
                    String storeId = entryName.split("_")[0];
                    String storeDay = entryName.split("_")[1];
                    String storeMonth = entryName.split("_")[2];
                    String storeYear = entryName.split("_")[3].substring(0,
                            entryName.split("_")[3].length() - 1);

                    LocalDate storeDate = new LocalDate(Integer.parseInt(storeYear),
                            Integer.parseInt(storeMonth), Integer.parseInt(storeDay));

                    insertStoresPs.setString(1, storeId);
                    insertStoresPs.setDate(2,
                            new java.sql.Date(storeDate.toDateTimeAtStartOfDay().getMillis()));
                    insertStoresPs.setInt(3, userId);

                    insertStoresPs.executeUpdate();
                } else {
                    String storeData = entryName.split("/")[0];
                    String fileName = entryName.split("/")[1];

                    if (fileName.toLowerCase().endsWith(".jpg") || fileName.toLowerCase().endsWith(".jpeg")
                            || fileName.toLowerCase().endsWith(".png")
                            || fileName.toLowerCase().endsWith(".gif") || fileName.endsWith(".tiff")) {
                        String storeId = storeData.split("_")[0];
                        String storeDay = storeData.split("_")[1];
                        String storeMonth = storeData.split("_")[2];
                        String storeYear = storeData.split("_")[3];

                        LocalDate storeDate = new LocalDate(Integer.parseInt(storeYear),
                                Integer.parseInt(storeMonth), Integer.parseInt(storeDay));

                        selectStoresPs.setInt(1, Integer.parseInt(storeId));
                        selectStoresPs.setDate(2,
                                new java.sql.Date(storeDate.toDateTimeAtStartOfDay().getMillis()));

                        int storePK = -1;
                        try (ResultSet rs = selectStoresPs.executeQuery()) {
                            while (rs.next()) {
                                storePK = rs.getInt("id");
                            }
                        }

                        //                            insertReceiptsPs.setBlob(1, zin, entry.getSize());
                        insertReceiptsPs.setInt(1, storePK);
                        insertReceiptsPs.setInt(2, userId);
                        insertReceiptsPs.setString(3, fileName);

                        insertReceiptsPs.executeUpdate();
                    }
                }
            }

            conn.commit();

            allStores = storesService.loadAllStores();
            conn.setAutoCommit(true);
        } catch (Exception ex) {
            conn.rollback();
            conn.setAutoCommit(true);

            ex.printStackTrace();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

From source file:com.amazonaws.eclipse.sdk.ui.AbstractSdkManager.java

private void unzipSDK(File zipFile, File unzipDestination, IProgressMonitor monitor, int totalUnitsOfWork)
        throws IOException {

    ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFile));

    monitor.subTask("Extracting SDK to workspace metadata directory");

    int worked = 0;
    long totalSize = zipFile.length();
    long totalUnzipped = 0;
    int unitWorkInBytes = (int) (totalSize / (double) totalUnitsOfWork);

    ZipEntry zipEntry = null;

    try {/*from w  w w . j  a  va 2s .  co m*/
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            IPath path = new Path(zipEntry.getName());

            File destinationFile = new File(unzipDestination, path.toOSString());
            if (zipEntry.isDirectory()) {
                destinationFile.mkdirs();
            } else {
                long compressedSize = zipEntry.getCompressedSize();

                FileOutputStream outputStream = new FileOutputStream(destinationFile);
                try {
                    IOUtils.copy(zipInputStream, outputStream);
                } catch (EOFException eof) {
                    /*
                     * There is a bug in ZipInputStream, where it might
                     * incorrectly throw EOFException if the read exceeds
                     * the current zip-entry size.
                     *
                     * http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6519463
                     */
                    JavaSdkPlugin.getDefault().getLog().log(new Status(Status.WARNING, JavaSdkPlugin.PLUGIN_ID,
                            "Ignore EOFException when unpacking zip-entry " + zipEntry.getName(), eof));
                }
                outputStream.close();

                totalUnzipped += compressedSize;
                if (totalUnzipped / unitWorkInBytes > worked) {
                    int newWork = (int) (totalUnzipped / (double) unitWorkInBytes) - worked;
                    monitor.worked(newWork);
                    worked += newWork;
                }
            }
        }

    } finally {
        zipInputStream.close();
    }
}