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.digitalcampus.oppia.utils.FileUtils.java

public static boolean unzipFiles(String srcDirectory, String srcFile, String destDirectory) {
    try {/*from  w  ww  . jav  a 2s  . com*/
        // first make sure that all the arguments are valid and not null
        if (srcDirectory == null) {
            return false;
        }
        if (srcFile == null) {
            return false;
        }
        if (destDirectory == null) {
            return false;
        }
        if (srcDirectory.equals("")) {
            return false;
        }
        if (srcFile.equals("")) {
            return false;
        }
        if (destDirectory.equals("")) {
            return false;
        }
        // now make sure that these directories exist
        File sourceDirectory = new File(srcDirectory);
        File sourceFile = new File(srcDirectory + File.separator + srcFile);
        File destinationDirectory = new File(destDirectory);

        if (!sourceDirectory.exists()) {
            return false;
        }
        if (!sourceFile.exists()) {
            return false;
        }
        if (!destinationDirectory.exists()) {
            return false;
        }

        // now start with unzip process
        BufferedOutputStream dest = null;

        FileInputStream fis = new FileInputStream(sourceFile);
        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));

        ZipEntry entry = null;

        while ((entry = zis.getNextEntry()) != null) {
            String outputFilename = destDirectory + File.separator + entry.getName();

            createDirIfNeeded(destDirectory, entry);

            int count;

            byte data[] = new byte[BUFFER_SIZE];

            File f = new File(outputFilename);

            // write the file to the disk
            if (!f.isDirectory()) {
                FileOutputStream fos = new FileOutputStream(f);
                dest = new BufferedOutputStream(fos, BUFFER_SIZE);

                // this counter is a hack to prevent getting stuck when
                // installing corrupted or not fully downloaded course
                // packages
                // it will prevent any course being installed with files
                // larger than around 500kb
                int counter = 0;
                while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
                    dest.write(data, 0, count);
                    counter++;
                    if (counter > 5000) {
                        dest.flush();
                        dest.close();
                        return false;
                    }
                }

                // close the output streams
                dest.flush();
                dest.close();
            }
        }

        // we are done with all the files
        // close the zip file
        zis.close();

    } catch (Exception e) {
        if (!MobileLearning.DEVELOPER_MODE) {
            BugSenseHandler.sendException(e);
        } else {
            e.printStackTrace();
        }
        return false;
    }

    return true;
}

From source file:com.thoughtworks.go.server.service.BackupServiceIntegrationTest.java

private String fileContents(File location, String filename) throws IOException {
    ZipInputStream zipIn = null;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {/*w w  w.java  2s  .  c  o  m*/
        zipIn = new ZipInputStream(new FileInputStream(location));
        while (zipIn.available() > 0) {
            ZipEntry nextEntry = zipIn.getNextEntry();
            if (nextEntry.getName().equals(filename)) {
                IOUtils.copy(zipIn, out);
            }
        }
    } finally {
        if (zipIn != null) {
            zipIn.close();
        }
    }
    return out.toString();
}

From source file:org.docx4j.openpackaging.io.LoadFromZipNG.java

public OpcPackage get(InputStream is) throws Docx4JException {

    HashMap<String, ByteArray> partByteArrays = new HashMap<String, ByteArray>();
    try {//ww  w .  j  a v a 2 s  .com
        ZipInputStream zis = new ZipInputStream(is);
        ZipEntry entry = null;
        while ((entry = zis.getNextEntry()) != null) {
            byte[] bytes = getBytesFromInputStream(zis);
            //log.debug("Extracting " + entry.getName());
            partByteArrays.put(entry.getName(), new ByteArray(bytes));
        }
        zis.close();
    } catch (Exception e) {
        log.error(e.getMessage());
        throw new Docx4JException("Error processing zip file (is it a zip file?)", e);
    }

    // At this point, we're finished with the zip input stream
    // TODO, so many of the below methods could be renamed.
    // If performance is ok, LoadFromJCR could be refactored to
    // work the same way

    return process(partByteArrays);
}

From source file:org.hawkular.wildfly.module.installer.JBossModule.java

/**
 * uninstall (delete) JBossModule from given directory
 * @param modulesHome target directory/* w  ww  .j av  a 2 s.co m*/
 */
public void uninstallFrom(File modulesHome) throws Exception {
    log.info("Uninstalling module [" + this.root + "] from [" + modulesHome.getAbsolutePath() + "]");
    ZipInputStream zin = null;
    try {
        zin = new ZipInputStream(this.root.openStream());
        ZipEntry ze = null;
        while ((ze = zin.getNextEntry()) != null) {
            String fileName = ze.getName();
            File newFile = new File(modulesHome + File.separator + fileName);
            if (!ze.isDirectory()) {
                if (log.isDebugEnabled()) {
                    log.debug("Deleting " + newFile.getAbsolutePath());
                }
                FileUtils.deleteQuietly(newFile);
            }
        }
    } finally {
        try {
            // it should be enough to close the latest created stream in
            // case of chained (nested) streams, @see
            // http://www.javapractices.com/topic/TopicAction.do?Id=8
            if (zin != null) {
                zin.close();
            }
        } catch (IOException ex) {
        }
    }
}

From source file:dk.itst.oiosaml.sp.configuration.ConfigurationHandler.java

public boolean writeConfiguration(String homeDir, byte[] configurationContents) {
    File root = new File(homeDir);
    if (!root.isDirectory() || !root.canWrite()) {
        return false;
    }/*from  w w  w .j  a  va  2s.  co m*/
    boolean written = true;
    try {
        ZipInputStream input = new ZipInputStream(new ByteArrayInputStream(configurationContents));
        ZipEntry next = null;
        while ((next = input.getNextEntry()) != null) {
            File newFile = new File(root, next.getName());
            FileUtils.forceMkdir(newFile.getParentFile());

            FileOutputStream file = new FileOutputStream(newFile);
            IOUtils.copy(input, file);
            file.close();
            input.closeEntry();
        }
        input.close();
    } catch (IOException e) {
        log.error("Unable to write configuration files to " + root, e);
        written = false;
    }
    return written;
}

From source file:com.khubla.simpleioc.classlibrary.ClassLibrary.java

/**
 * find all the classes in a jar file/*from  w w w. j av a 2  s .c o m*/
 */
private List<Class<?>> crackJar(String jarfile) throws Exception {
    try {
        /*
         * the ret
         */
        final List<Class<?>> ret = new ArrayList<Class<?>>();
        /*
         * the jar
         */
        final FileInputStream fis = new FileInputStream(jarfile);
        final ZipInputStream zip_inputstream = new ZipInputStream(fis);
        ZipEntry current_zip_entry = null;
        while ((current_zip_entry = zip_inputstream.getNextEntry()) != null) {
            if (current_zip_entry.getName().endsWith(".class")) {
                if (current_zip_entry.getSize() > 0) {
                    final ClassNode classNode = new ClassNode();
                    final ClassReader cr = new ClassReader(zip_inputstream);
                    cr.accept(classNode, 0);
                    if (annotated(classNode)) {
                        ret.add(Class.forName(classNode.name.replaceAll("/", ".")));
                        log.debug("Found " + classNode.name + " in " + jarfile);
                    }
                }
            }
        }
        zip_inputstream.close();
        fis.close();
        return ret;
    } catch (final Throwable e) {
        throw new Exception("Exception in crackJar for jar '" + jarfile + "'", e);
    }
}

From source file:ch.puzzle.itc.mobiliar.business.shakedown.control.ShakedownTestRunner.java

private String analyzeResult(STS sts) throws ShakedownTestException {
    String testResultPath = ConfigurationService.getProperty(ConfigKey.TEST_RESULT_PATH);
    try {/* www .j av  a  2s.  c o m*/
        StringBuilder sb = new StringBuilder();
        ZipInputStream zis = null;
        try {
            zis = new ZipInputStream(
                    new FileInputStream(testResultPath + File.separator + sts.getTestId() + ".zip"));
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                if (entry.getName().equals("/result.xml")) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(zis));
                    String s;
                    while ((s = reader.readLine()) != null) {
                        sb.append(s);
                    }
                }
            }
        } finally {
            if (zis != null) {
                zis.close();
            }
        }
        return sb.toString();
    } catch (FileNotFoundException e) {
        throw new ShakedownTestException("Was not able to analyze the result - no result file found!", e);
    } catch (IOException e) {
        throw new ShakedownTestException("Was not able to analyze the result", e);
    }

}

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

/**
 * Process the element descriptor inside the zip file, and set properties for given graphic element.
 *
 * @throws java.io.IOException/*from  ww  w  . ja v  a2  s .  c  o  m*/
 */
protected void deploy() throws Exception {
    Properties prop = new Properties();
    resources = new HashMap<String, Map<String, String>>();
    InputStream in = new BufferedInputStream(new FileInputStream(tmpZipFile));
    ZipInputStream zin = null;
    try {
        zin = new ZipInputStream(in);
        ZipEntry e;
        while ((e = zin.getNextEntry()) != null) {
            if (getDescriptorFileName().equals(e.getName())) {
                prop.load(zin);
            }
        }
    } finally {
        if (zin != null)
            zin.close();
    }
    if (prop.isEmpty()) {
        log.error("No properties inside descriptor " + getDescriptorFileName() + " for item with id " + id);
    }
    Enumeration properties = prop.propertyNames();
    String[] languages = getLocaleManager().getAllLanguages();
    while (properties.hasMoreElements()) {
        String propName = (String) properties.nextElement();
        if (propName.startsWith("name.")) {
            String lang = propName.substring(propName.lastIndexOf(".") + 1);
            setDescription(prop.getProperty(propName), lang);
            log.debug("Look-and-feel name (" + lang + "): " + prop.getProperty(propName));
        } else if (propName.startsWith("resource.")) {
            String resourceName = propName.substring("resource.".length());
            String langId = null;
            for (int i = 0; i < languages.length; i++) {
                String lngId = languages[i];
                if (resourceName.startsWith(lngId + ".")) {
                    langId = lngId;
                    resourceName = resourceName.substring(langId.length() + 1);
                    break;
                }
            }
            String resourcePath = prop.getProperty(propName);
            Map<String, String> existingResource = resources.get(resourceName);
            if (existingResource == null)
                resources.put(resourceName, existingResource = new HashMap<String, String>());
            existingResource.put(langId, resourcePath);
        } else {
            log.error("Unknown property in descriptor " + propName);
        }
    }
    log.debug("Loaded Graphic element description" + getDescription());
    log.debug("Loaded Graphic element resources: " + resources);
}

From source file:com.wheelermarine.publicAccessSites.Updater.java

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

    try {// ww w .j  a  v 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").endsWith(".zip")) {
                    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);
                }
            });
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(dataURL.toString());
            HttpResponse response = client.execute(get);
            HttpEntity entity = response.getEntity();
            if (entity == null)
                throw new IOException("Error downloading update.");

            Map<Integer, Location> locations = null;

            // Download the ZIP archive.
            Log.v(TAG, "Downloading: " + dataURL.getFile());
            InputStream in = entity.getContent();
            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);
                }
            }
            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.Layout.java

protected void deploy() throws Exception {
    super.deploy();
    InputStream in = new BufferedInputStream(new FileInputStream(getTmpZipFile()));
    ZipInputStream zin = new ZipInputStream(in);
    ZipEntry e;/* w  w  w .  j  av  a 2s .  c om*/
    SAXBuilder builder = new SAXBuilder();
    Document doc = null;
    Map descriptorPathMap = (Map) resources.get("XML");
    if (descriptorPathMap == null)
        throw new IllegalArgumentException("No valid xml descriptor in layout " + getId());
    String descriptorPath = (String) descriptorPathMap.get(null);
    if (descriptorPath == null)
        throw new IllegalArgumentException("No valid xml descriptor in layout " + getId());

    while ((e = zin.getNextEntry()) != null) {
        if (e.getName().equals(descriptorPath)) {
            doc = builder.build(zin);
            break;
        }
    }
    zin.close();
    if (doc == null)
        throw new IllegalArgumentException("No valid xml descriptor in layout " + getId());
    Element root = doc.getRootElement();

    if (root.getName().equalsIgnoreCase("layout")) {
        List xmlRegions = loadRegions(root);
        regions = new ArrayList();
        for (int i = 0; i < xmlRegions.size(); i++)
            addRegion((LayoutRegion) xmlRegions.get(i));
    } else {
        throw new IOException("Invalid layout format in xml descriptor");
    }
}