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:it.cnr.icar.eric.common.Utility.java

/**
 *
 * Extracts Zip file contents relative to baseDir
 * @return An ArrayList containing the File instances for each unzipped file
 *///from  w  w  w.ja  va  2 s. c om
public static ArrayList<File> unZip(String baseDir, InputStream is) throws IOException {
    ArrayList<File> files = new ArrayList<File>();
    ZipInputStream zis = new ZipInputStream(is);

    while (true) {
        // Get the next zip entry.  Break out of the loop if there are
        //   no more.
        ZipEntry zipEntry = zis.getNextEntry();
        if (zipEntry == null)
            break;

        String entryName = zipEntry.getName();
        if (FILE_SEPARATOR.equalsIgnoreCase("\\")) {
            // Convert '/' to Windows file separator
            entryName = entryName.replaceAll("/", "\\\\");
        }
        String fileName = baseDir + FILE_SEPARATOR + entryName;
        //Make sure that directory exists.
        String dirName = fileName.substring(0, fileName.lastIndexOf(FILE_SEPARATOR));
        File dir = new File(dirName);
        dir.mkdirs();

        //Entry could be a directory
        if (!(zipEntry.isDirectory())) {
            //Entry is a file not a directory.
            //Write out the content of of entry to file 
            File file = new File(fileName);
            files.add(file);
            FileOutputStream fos = new FileOutputStream(file);

            // Read data from the zip entry.  The read() method will return
            //   -1 when there is no more data to read.
            byte[] buffer = new byte[1000];

            int n;

            while ((n = zis.read(buffer)) > -1) {
                // In real life, you'd probably write the data to a file.
                fos.write(buffer, 0, n);
            }
            zis.closeEntry();
            fos.close();
        } else {
            zis.closeEntry();
        }
    }

    zis.close();

    return files;
}

From source file:org.apache.axis2.deployment.resolver.AARFileBasedURIResolver.java

public InputSource resolveEntity(String targetNamespace, String schemaLocation, String baseUri) {
    //no issue with abloslute schemas 
    // this schema can be in a relative location for another base scheama. so first
    // try to see the proper location

    lastImportLocation = URI.create(baseUri).resolve(schemaLocation);
    if (isAbsolute(lastImportLocation.toString())) {
        return super.resolveEntity(targetNamespace, schemaLocation, baseUri);
    } else {//from  ww  w. j a  v  a2s  . c o  m
        //validate
        if ((baseUri == null || "".equals(baseUri)) && schemaLocation.startsWith("..")) {
            throw new RuntimeException("Unsupported schema location " + schemaLocation);
        }

        ZipInputStream zin = null;
        try {
            zin = new ZipInputStream(new FileInputStream(aarFile));

            ZipEntry entry;
            byte[] buf = new byte[1024];
            int read;
            ByteArrayOutputStream out;
            String searchingStr = lastImportLocation.toString();
            while ((entry = zin.getNextEntry()) != null) {
                String entryName = entry.getName().toLowerCase();
                if (entryName.equalsIgnoreCase(searchingStr)) {
                    out = new ByteArrayOutputStream();
                    while ((read = zin.read(buf)) > 0) {
                        out.write(buf, 0, read);
                    }
                    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
                    InputSource inputSoruce = new InputSource(in);
                    inputSoruce.setSystemId(lastImportLocation.getPath());
                    inputSoruce.setPublicId(targetNamespace);
                    return inputSoruce;
                }
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (zin != null) {
                    zin.close();
                }
            } catch (IOException e) {
                log.debug(e);
            }
        }

    }

    log.info("AARFileBasedURIResolver: Unable to resolve" + lastImportLocation);
    return null;
}

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

/**
 * installs JBossModule to given directory
 * @param modulesHome//from   ww  w .  j  a v  a 2 s .c  o  m
 *            target directory to install module
 * @return list of installed files
 * @throws Exception
 */
public List<File> installTo(File modulesHome) throws Exception {
    List<File> installedFiles = new ArrayList<File>();

    ZipInputStream zin = null;
    FileOutputStream fos;
    log.info("Extracting module [" + this.root + "] to [" + modulesHome.getAbsolutePath() + "]");
    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()) {
                log.debug("Writing " + newFile.getAbsolutePath());
                File parent = newFile.getParentFile();
                if (!parent.exists()) {
                    parent.mkdirs();
                }
                fos = new FileOutputStream(newFile);

                IOUtils.copy(zin, fos);
                IOUtils.closeQuietly(fos);
                installedFiles.add(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) {
        }
    }

    return installedFiles;
}

From source file:org.geoserver.wps.ppio.ShapeZipPPIO.java

@Override
public Object decode(InputStream input) throws Exception {
    // create the temp directory and register it as a temporary resource
    File tempDir = IOUtils.createTempDirectory("shpziptemp");

    // unzip to the temporary directory
    ZipInputStream zis = null;
    File shapeFile = null;//from www . j a va2  s.  c o  m
    try {
        zis = new ZipInputStream(input);
        ZipEntry entry = null;

        while ((entry = zis.getNextEntry()) != null) {
            String name = entry.getName();
            File file = new File(tempDir, entry.getName());
            if (entry.isDirectory()) {
                file.mkdir();
            } else {
                if (file.getName().toLowerCase().endsWith(".shp")) {
                    shapeFile = file;
                }

                int count;
                byte data[] = new byte[4096];
                // write the files to the disk
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(file);
                    while ((count = zis.read(data)) != -1) {
                        fos.write(data, 0, count);
                    }
                    fos.flush();
                } finally {
                    if (fos != null) {
                        fos.close();
                    }
                }
            }
            zis.closeEntry();
        }
    } finally {
        if (zis != null) {
            zis.close();
        }
    }

    if (shapeFile == null) {
        FileUtils.deleteDirectory(tempDir);
        throw new IOException("Could not find any file with .shp extension in the zip file");
    } else {
        ShapefileDataStore store = new ShapefileDataStore(DataUtilities.fileToURL(shapeFile));
        resources.addResource(new ShapefileResource(store, tempDir));
        return store.getFeatureSource().getFeatures();
    }

}

From source file:org.geoserver.wps.gs.download.DownloadMapProcessTest.java

public void testExecutMultiLayerKmz(String mime) throws Exception {
    String request = IOUtils.toString(getClass().getResourceAsStream("mapMultiLayer.xml"));
    request = request.replaceAll("image/png", mime);
    MockHttpServletResponse response = postAsServletResponse("wps", request);
    assertEquals(KMZMapOutputFormat.MIME_TYPE, response.getContentType());
    assertEquals("inline; filename=result.kmz", response.getHeader("Content-disposition"));

    ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(response.getContentAsByteArray()));
    try {/*from  w w  w  .  j  a  v a2  s .c o m*/
        // first entry, the kml document itself
        ZipEntry entry = zis.getNextEntry();
        assertEquals("wms.kml", entry.getName());
        byte[] data = IOUtils.toByteArray(zis);
        Document dom = dom(new ByteArrayInputStream(data));
        // print(dom);
        assertXpathEvaluatesTo("1", "count(//kml:Folder/kml:GroundOverlay)", dom);
        String href = XMLUnit.newXpathEngine().evaluate("//kml:Folder/kml:GroundOverlay/kml:Icon/kml:href",
                dom);
        assertEquals("image.png", href);
        zis.closeEntry();

        // the ground overlay for the raster layer
        entry = zis.getNextEntry();
        assertEquals("image.png", entry.getName());
        BufferedImage image = ImageIO.read(zis);
        zis.closeEntry();
        assertNull(zis.getNextEntry());

        // check the output, same as mapMultiName
        ImageAssert.assertEquals(new File(SAMPLES + "mapMultiName.png"), image, 100);
    } finally {
        zis.close();
    }
}

From source file:net.ymate.platform.commons.util.ClassUtils.java

@SuppressWarnings("unchecked")
protected static <T> void __doFindClassByZip(Collection<Class<T>> collections, Class<T> clazz,
        String packageName, URL zipUrl, Class<?> callingClass) {
    ZipInputStream _zipStream = null;
    try {// w ww.  j  a  v a2  s.  co m
        String _zipFilePath = zipUrl.toString();
        if (_zipFilePath.indexOf('!') > 0) {
            _zipFilePath = StringUtils.substringBetween(zipUrl.toString(), "zip:", "!");
        } else {
            _zipFilePath = StringUtils.substringAfter(zipUrl.toString(), "zip:");
        }
        _zipStream = new ZipInputStream(new FileInputStream(new File(_zipFilePath)));
        ZipEntry _zipEntry = null;
        while (null != (_zipEntry = _zipStream.getNextEntry())) {
            if (!_zipEntry.isDirectory()) {
                if (_zipEntry.getName().endsWith(".class") && _zipEntry.getName().indexOf('$') < 0) {
                    Class<?> _class = __doProcessEntry(zipUrl, _zipEntry);
                    if (_class != null) {
                        if (clazz.isAnnotation()) {
                            if (isAnnotationOf(_class, (Class<Annotation>) clazz)) {
                                collections.add((Class<T>) _class);
                            }
                        } else if (clazz.isInterface()) {
                            if (isInterfaceOf(_class, clazz)) {
                                collections.add((Class<T>) _class);
                            }
                        } else if (isSubclassOf(_class, clazz)) {
                            collections.add((Class<T>) _class);
                        }
                    }
                }
            }
            _zipStream.closeEntry();
        }
    } catch (Exception e) {
        _LOG.warn("", RuntimeUtils.unwrapThrow(e));
    } finally {
        if (_zipStream != null) {
            try {
                _zipStream.close();
            } catch (IOException e) {
                _LOG.warn("", RuntimeUtils.unwrapThrow(e));
            }
        }
    }
}

From source file:org.apache.axis2.deployment.util.Utils.java

/**
 * Get names of all *.jar files inside the lib/ directory of a given jar URL
 *
 * @param url base URL of a JAR to search
 * @return a List containing file names (Strings) of all files matching "[lL]ib/*.jar"
 *///from  ww w.j a  v  a2  s  . c o  m
public static List findLibJars(URL url) {
    ArrayList embedded_jars = new ArrayList();
    try {
        ZipInputStream zin = new ZipInputStream(url.openStream());
        ZipEntry entry;
        String entryName;
        while ((entry = zin.getNextEntry()) != null) {
            entryName = entry.getName();
            /**
             * if the entry name start with /lib and ends with .jar add it
             * to the the arraylist
             */
            if (entryName != null && (entryName.startsWith("lib/") || entryName.startsWith("Lib/"))
                    && entryName.endsWith(".jar")) {
                embedded_jars.add(entryName);
            }
        }
        zin.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return embedded_jars;
}

From source file:org.apache.axis2.deployment.DeploymentEngine.java

private static void addAsWebResources(File in, String serviceFileName, AxisServiceGroup serviceGroup) {
    try {//from w  w  w  . j a va 2  s  .c om
        if (webLocationString == null) {
            return;
        }
        if (in.isDirectory()) {
            return;
        }
        File webLocation = new File(webLocationString);
        File out = new File(webLocation, serviceFileName);
        int BUFFER = 1024;
        byte data[] = new byte[BUFFER];
        FileInputStream fin = new FileInputStream(in);
        ZipInputStream zin = new ZipInputStream(fin);
        ZipEntry entry;
        while ((entry = zin.getNextEntry()) != null) {
            ZipEntry zip = new ZipEntry(entry);
            if (zip.getName().toUpperCase().startsWith("WWW")) {
                String fileName = zip.getName();
                fileName = fileName.substring("WWW/".length(), fileName.length());
                if (zip.isDirectory()) {
                    new File(out, fileName).mkdirs();
                } else {
                    FileOutputStream tempOut = new FileOutputStream(new File(out, fileName));
                    int count;
                    while ((count = zin.read(data, 0, BUFFER)) != -1) {
                        tempOut.write(data, 0, count);
                    }
                    tempOut.close();
                    tempOut.flush();
                }
                serviceGroup.setFoundWebResources(true);
            }
        }
        zin.close();
        fin.close();
    } catch (IOException e) {
        log.info(e.getMessage());
    }
}

From source file:com.arcusys.liferay.vaadinplugin.VaadinUpdater.java

private String exctractZipFile(File vaadinZipFile, String tmpPath) throws IOException {
    byte[] buf = new byte[1024];
    String zipDestinationPath = tmpPath + fileSeparator + "unzip" + fileSeparator;
    File unzipDirectory = new File(zipDestinationPath);
    if (!unzipDirectory.mkdir()) {
        log.warn("Zip extract failed.");
        upgradeListener.updateFailed("Zip extract failed: Can not create directory " + zipDestinationPath);
        return null;
    }/*from  ww w. j  a va  2s . co m*/

    ZipInputStream zinstream = new ZipInputStream(new FileInputStream(vaadinZipFile.getAbsolutePath()));
    ZipEntry zentry = zinstream.getNextEntry();

    while (zentry != null) {
        String entryName = zentry.getName();
        if (zentry.isDirectory()) {
            File newFile = new File(zipDestinationPath + entryName);
            if (!newFile.mkdir()) {
                break;
            }
            zentry = zinstream.getNextEntry();
            continue;
        }
        outputLog.log("Extracting " + entryName);
        FileOutputStream outstream = new FileOutputStream(
                zipDestinationPath + getFileNameWithoutVersion(entryName));
        int n;

        while ((n = zinstream.read(buf, 0, 1024)) > -1) {
            outstream.write(buf, 0, n);
        }

        outputLog.log("Successfully Extracted File Name : " + entryName);
        outstream.close();

        zinstream.closeEntry();
        zentry = zinstream.getNextEntry();
    }
    zinstream.close();

    return zipDestinationPath;
}

From source file:gov.pnnl.goss.gridappsd.app.AppManagerImpl.java

@Override
public void registerApp(AppInfo appInfo, byte[] appPackage) throws Exception {
    System.out.println("REGISTER REQUEST RECEIVED ");
    // appPackage should be received as a zip file. extract this to the apps
    // directory, and write appinfo to a json file under config/
    File appHomeDir = getAppConfigDirectory();
    if (!appHomeDir.exists()) {
        appHomeDir.mkdirs();//from  www.j  a v  a  2  s  .c  o  m
        if (!appHomeDir.exists()) {
            // if it still doesn't exist throw an error
            throw new Exception(
                    "App home directory does not exist and cannot be created " + appHomeDir.getAbsolutePath());
        }
    }
    System.out.println("HOME DIR " + appHomeDir.getAbsolutePath());
    // create a directory for the app
    File newAppDir = new File(appHomeDir.getAbsolutePath() + File.separator + appInfo.getId());
    if (newAppDir.exists()) {
        throw new Exception("App " + appInfo.getId() + " already exists");
    }

    try {
        newAppDir.mkdirs();
        // Extract zip file into new app dir
        ZipInputStream zipIn = new ZipInputStream(new ByteArrayInputStream(appPackage));
        ZipEntry entry = zipIn.getNextEntry();
        // iterates over entries in the zip file and write to dir
        while (entry != null) {
            String filePath = newAppDir + File.separator + entry.getName();
            if (!entry.isDirectory()) {
                // if the entry is a file, extracts it
                extractFile(zipIn, filePath);
            } else {
                // if the entry is a directory, make the directory
                File dir = new File(filePath);
                dir.mkdir();
            }
            zipIn.closeEntry();
            entry = zipIn.getNextEntry();
        }
        zipIn.close();

        writeAppInfo(appInfo);

        // add to apps hashmap
        apps.put(appInfo.getId(), appInfo);
    } catch (Exception e) {
        // Clean up app dir if fails
        newAppDir.delete();
        throw e;
    }
}