Example usage for java.util.zip ZipInputStream close

List of usage examples for java.util.zip ZipInputStream close

Introduction

In this page you can find the example usage for java.util.zip ZipInputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:org.intermine.api.lucene.KeywordSearch.java

private static FSDirectory readFSDirectory(String path, InputStream is)
        throws IOException, FileNotFoundException {
    long time = System.currentTimeMillis();
    final int bufferSize = 2048;
    File directoryPath = new File(path + File.separator + LUCENE_INDEX_DIR);
    LOG.debug("Directory path: " + directoryPath);

    // make sure we start with a new index
    if (directoryPath.exists()) {
        String[] files = directoryPath.list();
        for (int i = 0; i < files.length; i++) {
            LOG.info("Deleting old file: " + files[i]);
            new File(directoryPath.getAbsolutePath() + File.separator + files[i]).delete();
        }//w  ww.ja v  a  2 s.  c  om
    } else {
        directoryPath.mkdir();
    }

    ZipInputStream zis = new ZipInputStream(is);
    ZipEntry entry;
    try {
        while ((entry = zis.getNextEntry()) != null) {
            LOG.info("Extracting: " + entry.getName() + " (" + entry.getSize() + " MB)");

            FileOutputStream fos = new FileOutputStream(
                    directoryPath.getAbsolutePath() + File.separator + entry.getName());
            BufferedOutputStream bos = new BufferedOutputStream(fos, bufferSize);

            int count;
            byte[] data = new byte[bufferSize];

            try {
                while ((count = zis.read(data, 0, bufferSize)) != -1) {
                    bos.write(data, 0, count);
                }
            } finally {
                bos.flush();
                bos.close();
            }
        }
    } finally {
        zis.close();
    }

    FSDirectory directory = FSDirectory.open(directoryPath);

    LOG.info("Successfully restored FS directory from database in " + (System.currentTimeMillis() - time)
            + " ms");
    return directory;
}

From source file:org.apache.tajo.yarn.command.LaunchCommand.java

private String getTajoRootInZip(String zip) throws IOException {
    ZipInputStream inputStream = null;
    try {/*from  ww  w.  ja v  a  2  s.  co m*/
        inputStream = new ZipInputStream(new FileInputStream(zip));
        for (ZipEntry entry = inputStream.getNextEntry(); entry != null;) {
            String entryName = entry.getName();
            if (entry.isDirectory() && entryName.startsWith("tajo-")) {
                return entryName.substring(0, entryName.length() - 1);
            }
            entry = inputStream.getNextEntry();
        }
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }

    throw new IOException("Unable to get tajo home dir from " + zip);
}

From source file:org.dataconservancy.ui.util.ZipPackageExtractor.java

@Override
protected List<File> unpackFilesFromStream(InputStream packageInputStream, String packageDir, String fileName)
        throws UnpackException {
    final ZipInputStream zipInStream;

    if (!ZipInputStream.class.isAssignableFrom(packageInputStream.getClass())) {
        zipInStream = new ZipInputStream(packageInputStream);
    } else {// w w w  .  j  av a 2 s .  c  o m
        zipInStream = (ZipInputStream) packageInputStream;
    }

    List<File> files = new ArrayList<File>();
    try {
        ZipEntry entry = zipInStream.getNextEntry();
        //Get next tar entry returns null when there are no more entries
        while (entry != null) {
            //Directories are automatically handled by the base class so we can ignore them in this class.
            if (!entry.isDirectory()) {
                File entryFile = new File(packageDir, entry.getName());
                if (entryFile != null) {
                    List<File> savedFiles = saveExtractedFile(entryFile, zipInStream);
                    files.addAll(savedFiles);
                }
            }
            entry = zipInStream.getNextEntry();
        }

        zipInStream.close();
    } catch (IOException e) {
        final String msg = "Error processing ZipInputStream: " + e.getMessage();
        log.error(msg, e);
        throw new UnpackException(msg, e);
    }

    return files;
}

From source file:de.mpg.escidoc.pubman.multipleimport.processor.ZfNProcessor.java

private void initialize() {
    this.init = true;

    try {/* www  .  jav a 2 s  .  c  om*/
        InputStream in = new FileInputStream(getSourceFile());
        ArrayList<String> itemList = new ArrayList<String>();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        String item = null;
        final int bufLength = 1024;
        char[] buffer = new char[bufLength];
        int readReturn;
        int count = 0;

        ZipEntry zipentry;
        ZipInputStream zipinputstream = new ZipInputStream(in);

        while ((zipentry = zipinputstream.getNextEntry()) != null) {
            count++;
            StringWriter sw = new StringWriter();
            Reader reader = new BufferedReader(new InputStreamReader(zipinputstream, "UTF-8"));

            while ((readReturn = reader.read(buffer)) != -1) {
                sw.write(buffer, 0, readReturn);
            }

            item = new String(sw.toString());
            itemList.add(item);
            this.fileNames.add(zipentry.getName());

            reader.close();
            zipinputstream.closeEntry();

        }

        this.logger.debug("Zip file contains " + count + "elements");
        zipinputstream.close();
        this.counter = 0;

        this.originalData = byteArrayOutputStream.toByteArray();
        this.items = itemList.toArray(new String[] {});
        this.length = this.items.length;
    } catch (Exception e) {
        this.logger.error("Could not read zip File: " + e.getMessage());
        throw new RuntimeException("Error reading input stream", e);
    }
}

From source file:com.dangdang.config.service.web.mb.PropertyGroupManagedBean.java

/**
 * ?//from   w ww  .j  a v a  2s.c om
 * 
 * @param event
 */
public void propertyZipUpload(FileUploadEvent event) {
    String fileName = event.getFile().getFileName();
    LOGGER.info("Deal uploaded file: {}", fileName);
    ZipInputStream zipInputStream = null;
    try {
        zipInputStream = new ZipInputStream(event.getFile().getInputstream());
        ZipEntry nextEntry = null;
        while ((nextEntry = zipInputStream.getNextEntry()) != null) {
            String entryName = nextEntry.getName();
            savePropertyGroup(entryName, Files.getNameWithoutExtension(entryName), zipInputStream);
        }
    } catch (IOException e) {
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, "Upload File error.", fileName));
        LOGGER.error("Upload File Exception.", e);
    } finally {
        if (zipInputStream != null) {
            try {
                zipInputStream.close();
            } catch (IOException e) {
                // DO NOTHING
            }
        }
    }
}

From source file:com.coinblesk.client.backup.BackupRestoreDialogFragment.java

/**
 * Extracts all files from a zip to disk.
 * @param zip data (zip format)/*  w w w. jav  a  2  s .c o m*/
 * @throws IOException
 */
private void extractZip(byte[] zip) throws IOException {
    ZipInputStream zis = null;
    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(zip);
        zis = new ZipInputStream(new BufferedInputStream(bais));
        ZipEntry ze = null;

        // extract all entries
        Log.d(TAG, "Start extracting backup.");
        int i = 0;
        while ((ze = zis.getNextEntry()) != null) {
            if (!shouldIgnoreZipEntry(ze)) {
                extractFromZipAndSaveToFile(zis, ze);
                ++i;
            } else {
                Log.d(TAG, "Ignore entry: " + ze.getName());
            }
        }
        Log.i(TAG, "Extracted " + i + " elements from backup.");

    } finally {
        if (zis != null) {
            try {
                zis.close();
            } catch (IOException e) {
                Log.w(TAG, "Could not close zip input stream.", e);
            }
        }
    }
}

From source file:com.dangdang.config.service.web.mb.PropertyGroupManagedBean.java

/**
 * ?(Old)/*from  ww w. j  a v  a 2s. co m*/
 * 
 * @param event
 */
@Deprecated
public void propertyZipUploadOld(FileUploadEvent event) {
    String fileName = event.getFile().getFileName();
    LOGGER.info("Deal uploaded file: {}", fileName);
    ZipInputStream zipInputStream = null;
    try {
        zipInputStream = new ZipInputStream(event.getFile().getInputstream());
        ZipEntry nextEntry = null;
        while ((nextEntry = zipInputStream.getNextEntry()) != null) {
            String entryName = nextEntry.getName();
            savePropertyGroupOld(entryName, Files.getNameWithoutExtension(entryName), zipInputStream);
        }
    } catch (IOException e) {
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, "Upload File error.", fileName));
        LOGGER.error("Upload File Exception.", e);
    } finally {
        if (zipInputStream != null) {
            try {
                zipInputStream.close();
            } catch (IOException e) {
                // DO NOTHING
            }
        }
    }
}

From source file:com.wheelermarine.android.publicAccesses.Updater.java

@Override
protected Integer doInBackground(URL... urls) {

    try {// w w w. j  av a2s  .c  o m
        final DatabaseHelper db = new DatabaseHelper(context);

        SQLiteDatabase database = db.getWritableDatabase();
        if (database == null)
            throw new IllegalStateException("Unable to open database!");

        database.beginTransaction();
        try {
            // Clear out the old data.
            database.delete(DatabaseHelper.PublicAccessEntry.TABLE_NAME, null, null);

            // Connect to the web server and locate the FTP download link.
            Log.v(TAG, "Finding update: " + urls[0]);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progress.setMessage("Locating update...");
                    progress.setIndeterminate(true);
                }
            });
            Document doc = Jsoup.connect(urls[0].toString()).timeout(timeout * 1000).userAgent(userAgent).get();
            URL dataURL = null;
            for (Element element : doc.select("a")) {
                if (element.hasAttr("href") && element.attr("href").startsWith("ftp://ftp.dnr.state.mn.us")) {
                    dataURL = new URL(element.attr("href"));
                }
            }

            // Make sure the download URL was fund.
            if (dataURL == null)
                throw new FileNotFoundException("Unable to locate data URL.");

            // Connect to the FTP server and download the update.
            Log.v(TAG, "Downloading update: " + dataURL);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progress.setMessage("Downloading update...");
                    progress.setIndeterminate(true);
                }
            });
            FTPClient ftp = new FTPClient();
            try {
                ftp.setConnectTimeout(timeout * 1000);
                ftp.setDefaultTimeout(timeout * 1000);
                ftp.connect(dataURL.getHost());
                ftp.enterLocalPassiveMode();

                // After connection attempt, you should check the reply code
                // to verify success.
                if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                    ftp.disconnect();
                    throw new IOException("FTP server refused connection: " + ftp.getReplyString());
                }

                // Login using the standard anonymous credentials.
                if (!ftp.login("anonymous", "anonymous")) {
                    ftp.disconnect();
                    throw new IOException("FTP Error: " + ftp.getReplyString());
                }

                Map<Integer, Location> locations = null;

                // Download the ZIP archive.
                Log.v(TAG, "Downloading: " + dataURL.getFile());
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
                InputStream in = ftp.retrieveFileStream(dataURL.getFile());
                if (in == null)
                    throw new FileNotFoundException(dataURL.getFile() + " was not found!");
                try {
                    ZipInputStream zin = new ZipInputStream(in);
                    try {
                        // Locate the .dbf entry in the ZIP archive.
                        ZipEntry entry;
                        while ((entry = zin.getNextEntry()) != null) {
                            if (entry.getName().endsWith(entryName)) {
                                readDBaseFile(zin, database);
                            } else if (entry.getName().endsWith(shapeEntryName)) {
                                locations = readShapeFile(zin);
                            }
                        }
                    } finally {
                        try {
                            zin.close();
                        } catch (Exception e) {
                            // Ignore this error.
                        }
                    }
                } finally {
                    in.close();
                }

                if (locations != null) {
                    final int recordCount = locations.size();
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progress.setIndeterminate(false);
                            progress.setMessage("Updating locations...");
                            progress.setMax(recordCount);
                        }
                    });

                    int progress = 0;
                    for (int recordNumber : locations.keySet()) {
                        PublicAccess access = db.getPublicAccessByRecordNumber(recordNumber);
                        Location loc = locations.get(recordNumber);
                        access.setLatitude(loc.getLatitude());
                        access.setLongitude(loc.getLongitude());
                        db.updatePublicAccess(access);
                        publishProgress(++progress);
                    }
                }
            } finally {
                if (ftp.isConnected())
                    ftp.disconnect();
            }
            database.setTransactionSuccessful();
            return db.getPublicAccessesCount();
        } finally {
            database.endTransaction();
        }
    } catch (Exception e) {
        error = e;
        Log.e(TAG, "Error loading data: " + e.getLocalizedMessage(), e);
        return -1;
    }
}

From source file:org.jboss.dashboard.ui.resources.GraphicElement.java

/**
 * Deploy to a given directory. Extract all files in associated zip to given directory plus getBaseDir()
 *
 * @throws java.io.IOException//from  ww w. j  av  a 2s .com
 */
protected void deployFiles() throws Exception {
    //setLastModified(new Date());
    log.info("Deploying files for " + this.getClass().getName() + " " + getId());
    String destinationDir = getDeploymentDirName();
    File destDirFile = new File(destinationDir);
    destDirFile.mkdirs();
    if (!destDirFile.setLastModified(System.currentTimeMillis())) {
        log.error("Failed to set directory last modified, it might not be supported by the filesystem. "
                + "This will cause a noticeable performance degradation. Consider using a better operating system.");
    }
    if (getLastModified() == null || destDirFile.lastModified() <= getLastModified().getTime()) {
        setLastModified(new Date(destDirFile.lastModified() - 1));
    }
    InputStream in = new BufferedInputStream(new FileInputStream(tmpZipFile));
    ZipInputStream zin = new ZipInputStream(in);
    ZipEntry e;
    while ((e = zin.getNextEntry()) != null) {
        String destName = destinationDir + "/" + e.getName();
        if (e.isDirectory()) {
            log.debug("Creating dir " + destName);
            new File(destName).mkdirs();
        } else {
            log.debug("Creating file " + destName);
            unzip(zin, destName, e.getName());
        }
    }
    zin.close();
}

From source file:com.taobao.android.tpatch.utils.JarSplitUtils.java

/**
 * 2jar?,??jar//from w  w w.j  a v a 2 s.  co m
 * @param baseJar
 * @param diffJar
 * @param outJar
 */
public static void unionJar(File baseJar, File diffJar, File outJar) throws IOException {
    File outParentFolder = outJar.getParentFile();
    if (!outParentFolder.exists()) {
        outParentFolder.mkdirs();
    }
    List<String> diffEntries = getZipEntries(diffJar);
    FileOutputStream fos = new FileOutputStream(outJar);
    ZipOutputStream jos = new ZipOutputStream(fos);
    final byte[] buffer = new byte[8192];
    FileInputStream fis = new FileInputStream(baseJar);
    ZipInputStream zis = new ZipInputStream(fis);

    try {
        // loop on the entries of the jar file package and put them in the final jar
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            // do not take directories or anything inside a potential META-INF folder.
            if (entry.isDirectory()) {
                continue;
            }
            String name = entry.getName();
            if (diffEntries.contains(name)) {
                continue;
            }
            JarEntry newEntry;
            // Preserve the STORED method of the input entry.
            if (entry.getMethod() == JarEntry.STORED) {
                newEntry = new JarEntry(entry);
            } else {
                // Create a new entry so that the compressed len is recomputed.
                newEntry = new JarEntry(name);
            }
            // add the entry to the jar archive
            jos.putNextEntry(newEntry);

            // read the content of the entry from the input stream, and write it into the archive.
            int count;
            while ((count = zis.read(buffer)) != -1) {
                jos.write(buffer, 0, count);
            }
            // close the entries for this file
            jos.closeEntry();
            zis.closeEntry();
        }
    } finally {
        zis.close();
    }
    fis.close();
    jos.close();

}