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:hu.sztaki.lpds.pgportal.services.asm.ASMService.java

private void convertOutputZip(String userId, String workflowId, String jobId, String fileName, InputStream is,
        OutputStream os) throws IOException {

    InputStream exactFile = null;
    ZipInputStream zis = new ZipInputStream(is);
    ZipEntry entry;/*from w w w .j  av  a 2  s.c  o  m*/
    String runtimeID = getRuntimeID(userId, workflowId);
    ZipOutputStream zos = new ZipOutputStream(os);
    while ((entry = zis.getNextEntry()) != null) {

        if (jobId == null || (entry.getName().contains(jobId + "/outputs/" + runtimeID + "/")
                && (fileName == null || (fileName != null && entry.getName().endsWith(fileName))))) {
            int size;
            byte[] buffer = new byte[2048];

            String parentDir = entry.getName().split("/")[entry.getName().split("/").length - 2];
            String fileNameInZip = parentDir + "/"
                    + entry.getName().split("/")[entry.getName().split("/").length - 1];
            ZipEntry newFile = new ZipEntry(fileNameInZip);
            zos.putNextEntry(newFile);

            while ((size = zis.read(buffer, 0, buffer.length)) != -1) {

                zos.write(buffer, 0, size);
            }
            zos.closeEntry();

        }
    }
    zis.close();
    zos.close();

}

From source file:de.climbingguide.erzgebirsgrenzgebiet.downloader.DownloaderThread.java

private boolean unpackZip(String path, String zipname) {
    InputStream is;/*from   w ww .ja v a  2  s .  c om*/
    ZipInputStream zis;
    BufferedInputStream bis;
    try {
        String filename;
        is = new FileInputStream(path + zipname);
        bis = new BufferedInputStream(is);
        zis = new ZipInputStream(bis);
        ZipEntry ze;
        //                 byte[] buffer = new byte[1024];
        //                 int count;
        long fileSize = 0;

        //Gesamtdownloadgre bestimmen
        //                 while ((ze = zis.getNextEntry()) != null) 
        //                 { 
        ze = zis.getNextEntry();
        fileSize = ze.getSize() + fileSize;
        //                 }

        int fileSizeInKB = (int) (fileSize / 1024);

        Message msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_UNZIP_STARTED, fileSizeInKB, 0, "");
        activityHandler.sendMessage(msg);

        int bytesRead = 0, totalRead = 0;

        FileInputStream gis = new FileInputStream(path + zipname);

        BufferedInputStream fis = new BufferedInputStream(gis);

        ZipInputStream dis = new ZipInputStream(fis);

        while ((ze = dis.getNextEntry()) != null) {
            // zapis do souboru
            filename = ze.getName();

            // Need to create directories if not exists, or
            // it will generate an Exception...
            if (ze.isDirectory()) {
                File fmd = new File(path + filename);
                fmd.mkdirs();
                continue;
            }

            //

            //                BufferedInputStream inStream = new BufferedInputStream(mFTPClient.retrieveFileStream(ftpPathName));
            //                File outFile = new File(fileName);
            FileOutputStream fileStream = new FileOutputStream(path + filename);
            byte[] data = new byte[KleFuEntry.DOWNLOAD_BUFFER_SIZE];

            while (!isInterrupted() && (bytesRead = zis.read(data)) >= 0) {
                fileStream.write(data, 0, bytesRead);

                // update progress bar
                totalRead += bytesRead;
                int totalReadInKB = totalRead / 1024;
                msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_UPDATE_PROGRESS_BAR, totalReadInKB, 0);
                activityHandler.sendMessage(msg);
            }
            //                
            fileStream.close();
            //                 inStream.close();

            //                     FileOutputStream fout = new FileOutputStream(path + filename);
            //
            //                     while ((count = zis.read(buffer)) != -1) 
            //                     {
            //                         fout.write(buffer, 0, count);             
            //                     }
            //
            //                     fout.close();               
            //                     zis.closeEntry();
        }

        zis.close();
        dis.close();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:com.bluexml.side.Framework.alfresco.jbpm.CustomJBPMEngine.java

/**
 * Construct a Process Definition from the provided Process Definition
 * stream//from w  w  w. j a v  a 2  s  .c  o m
 * 
 * @param workflowDefinition
 *            stream to create process definition from
 * @param mimetype
 *            mimetype of stream
 * @return  process definition
 */
@SuppressWarnings("unchecked")
protected CompiledProcessDefinition compileProcessDefinition(InputStream definitionStream, String mimetype) {
    String actualMimetype = (mimetype == null) ? MimetypeMap.MIMETYPE_ZIP : mimetype;
    CompiledProcessDefinition compiledDef = null;

    // parse process definition from jBPM process archive file

    if (actualMimetype.equals(MimetypeMap.MIMETYPE_ZIP)) {
        ZipInputStream zipInputStream = null;
        try {
            zipInputStream = new ZipInputStream(definitionStream);
            ProcessArchive reader = new ProcessArchive(zipInputStream);
            ProcessDefinition def = reader.parseProcessDefinition();
            compiledDef = new CompiledProcessDefinition(def, reader.getProblems());
        } catch (Exception e) {
            String msg = messageService.getMessage(ERR_COMPILE_PROCESS_DEF_zip);
            throw new JbpmException(msg, e);
        } finally {
            if (zipInputStream != null) {
                try {
                    zipInputStream.close();
                } catch (IOException e) {
                    // Intentionally empty!
                }
            }
        }
    }

    // parse process definition from jBPM xml file

    else if (actualMimetype.equals(MimetypeMap.MIMETYPE_XML)) {
        try {
            if (logger.isDebugEnabled())
                logger.debug("Start deployment using BX CustomJBPMJpdlXmlReader");
            CustomJBPMJpdlXmlReader jpdlReader = new CustomJBPMJpdlXmlReader(definitionStream);
            ProcessDefinition def = jpdlReader.readProcessDefinition();
            List<Problem> problems = jpdlReader.getProblems();
            compiledDef = new CompiledProcessDefinition(def, problems);
        } catch (Exception e) {
            String msg = messageService.getMessage(ERR_COMPILE_PROCESS_DEF_XML);
            throw new JbpmException(msg, e);
        }
    } else {
        String msg = messageService.getMessage(ERR_COMPILE_PROCESS_DEF_UNSUPPORTED, mimetype);
        throw new JbpmException(msg);
    }

    if (tenantService.isEnabled()) {
        compiledDef.def.setName(tenantService.getName(compiledDef.def.getName()));
    }

    return compiledDef;
}

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  ww.  j  a v a  2  s . c o m*/

        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.httrack.android.HTTrackActivity.java

/**
 * Get the resource directory. Create it if necessary. Resources are created
 * in the dedicated cache, so that the files can be uninstalled upon
 * application removal.//from  ww w . ja  v  a  2s.  c om
 **/
private File buildResourceFile() {
    final File cache = android.os.Build.VERSION.SDK_INT >= VERSION_CODES.FROYO ? getExternalCacheDir()
            : getCacheDir();
    final File rscPath = new File(cache, "resources");
    final File stampFile = new File(rscPath, "resources.stamp");
    final long stamp = installOrUpdateTime();

    // Check timestamp of resources. If the applicate has been updated,
    // recreated cached resources.
    if (rscPath.exists()) {
        long diskStamp = 0;
        try {
            if (stampFile.exists()) {
                final FileReader reader = new FileReader(stampFile);
                final BufferedReader lreader = new BufferedReader(reader);
                try {
                    diskStamp = Long.parseLong(lreader.readLine());
                } catch (final NumberFormatException nfe) {
                    diskStamp = 0;
                }
                lreader.close();
                reader.close();
            }
        } catch (final IOException io) {
            diskStamp = 0;
        }
        // Different one: wipe and recreate
        if (stamp != diskStamp) {
            Log.i(getClass().getSimpleName(), "deleting old resources " + rscPath.getAbsolutePath()
                    + " (app_stamp=" + stamp + " != disk_stamp=" + diskStamp + ")");
            CleanupActivity.deleteRecursively(rscPath);
        } else {
            Log.i(getClass().getSimpleName(),
                    "keeping resources " + rscPath.getAbsolutePath() + " (app_stamp=disk_stamp=" + stamp + ")");
        }
    }

    // Recreate resources ?
    if (!rscPath.exists()) {
        Log.i(getClass().getSimpleName(),
                "creating resources " + rscPath.getAbsolutePath() + " with stamp " + stamp);
        if (HTTrackActivity.mkdirs(rscPath)) {
            long totalSize = 0;
            int totalFiles = 0;
            try {
                final InputStream zipStream = getResources().openRawResource(R.raw.resources);
                final ZipInputStream file = new ZipInputStream(zipStream);
                ZipEntry entry;
                while ((entry = file.getNextEntry()) != null) {
                    final File dest = new File(rscPath.getAbsoluteFile() + "/" + entry.getName());
                    if (entry.getName().endsWith("/")) {
                        dest.mkdirs();
                    } else {
                        final FileOutputStream writer = new FileOutputStream(dest);
                        final byte[] bytes = new byte[1024];
                        int length;
                        while ((length = file.read(bytes)) >= 0) {
                            writer.write(bytes, 0, length);
                            totalSize += length;
                        }
                        writer.close();
                        totalFiles++;
                        dest.setLastModified(entry.getTime());
                    }
                }
                file.close();
                zipStream.close();
                Log.i(getClass().getSimpleName(), "created resources " + rscPath.getAbsolutePath() + " ("
                        + totalFiles + " files, " + totalSize + " bytes)");

                // Write stamp
                final FileWriter writer = new FileWriter(stampFile);
                final BufferedWriter lwriter = new BufferedWriter(writer);
                lwriter.write(Long.toString(stamp));
                lwriter.close();
                writer.close();

                // Little info
                showNotification(getString(R.string.info_recreated_resources));
            } catch (final IOException io) {
                Log.w(getClass().getSimpleName(), "could not create resources", io);
                CleanupActivity.deleteRecursively(rscPath);
                showNotification(getString(R.string.info_could_not_create_resources), true);
            }
        }
    }

    // Return resources path
    return rscPath;
}

From source file:de.intranda.goobi.plugins.CSICMixedImport.java

private HashMap<String, String> unzipStream(InputStream iStream) {
    ArrayList<String> stringList = new ArrayList<String>();
    ArrayList<String> filenames = new ArrayList<String>();
    HashMap<String, String> contentMap = new HashMap<String, String>();

    BufferedInputStream bis = null;
    ZipInputStream in = null;
    try {//from   w w w.  j  a  v a 2  s  .  co  m
        bis = new BufferedInputStream(iStream);
        in = new ZipInputStream(bis);
        ZipEntry entry;
        while ((entry = in.getNextEntry()) != null) {
            filenames.add(entry.getName());
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            stringList.add(sb.toString());
            contentMap.put(entry.getName(), sb.toString());
        }
    } catch (IOException e) {
        logger.error(e.toString(), e);
    } finally {
        try {
            if (bis != null) {
                bis.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            logger.error("Error closing zip input stream");
        }
    }

    return contentMap;
}

From source file:com.cloudera.whirr.cm.server.impl.CmServerImpl.java

@Override
@CmServerCommandMethod(name = "client")
public boolean getServiceConfigs(final CmServerCluster cluster, final File directory) throws CmServerException {

    final AtomicBoolean executed = new AtomicBoolean(false);
    try {//  w w  w.ja  va  2s .co m

        if (isProvisioned(cluster)) {
            logger.logOperation("GetConfig", new CmServerLogSyncCommand() {
                @Override
                public void execute() throws IOException {
                    for (ApiService apiService : apiResourceRootV3.getClustersResource()
                            .getServicesResource(getName(cluster)).readServices(DataView.SUMMARY)) {
                        CmServerServiceType type = CmServerServiceType.valueOfId(apiService.getType());
                        if (type.equals(CmServerServiceType.HDFS) || type.equals(CmServerServiceType.MAPREDUCE)
                                || type.equals(CmServerServiceType.YARN)
                                || type.equals(CmServerServiceType.HBASE)
                                || versionApi >= 4 && type.equals(CmServerServiceType.HIVE)
                                || versionApi >= 5 && type.equals(CmServerServiceType.SOLR)) {
                            ZipInputStream configInputZip = null;
                            try {
                                InputStreamDataSource configInput = apiResourceRootV3.getClustersResource()
                                        .getServicesResource(getName(cluster))
                                        .getClientConfig(apiService.getName());
                                if (configInput != null) {
                                    configInputZip = new ZipInputStream(configInput.getInputStream());
                                    ZipEntry configInputZipEntry = null;
                                    while ((configInputZipEntry = configInputZip.getNextEntry()) != null) {
                                        String configFile = configInputZipEntry.getName();
                                        if (configFile.contains(File.separator)) {
                                            configFile = configFile.substring(
                                                    configFile.lastIndexOf(File.separator),
                                                    configFile.length());
                                        }
                                        directory.mkdirs();
                                        BufferedWriter configOutput = null;
                                        try {
                                            int read;
                                            configOutput = new BufferedWriter(
                                                    new FileWriter(new File(directory, configFile)));
                                            while (configInputZip.available() > 0) {
                                                if ((read = configInputZip.read()) != -1) {
                                                    configOutput.write(read);
                                                }
                                            }
                                        } finally {
                                            configOutput.close();
                                        }
                                    }
                                }
                            } finally {
                                if (configInputZip != null) {
                                    configInputZip.close();
                                }
                            }
                            executed.set(true);
                        }
                    }
                }
            });
        }

    } catch (Exception e) {
        throw new CmServerException("Failed to get cluster config", e);
    }

    return executed.get();

}

From source file:me.piebridge.bible.Bible.java

private boolean unpackZip(File path) throws IOException {
    if (path == null || !path.isFile()) {
        return false;
    }/*  w  w  w  . j  a va  2 s . c o  m*/

    File dirpath = getExternalFilesDirWrapper();

    // bibledata-zh-cn-version.zip
    String filename = path.getAbsolutePath();
    int sep = filename.lastIndexOf("-");
    if (sep != -1) {
        filename = filename.substring(sep + 1, filename.length() - 4);
    }
    filename += ".sqlite3";

    InputStream is = new FileInputStream(path);
    long fileSize = path.length();
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
    try {
        ZipEntry ze;
        while ((ze = zis.getNextEntry()) != null) {
            long zeSize = ze.getCompressedSize();
            // zip is incomplete
            if (fileSize < zeSize) {
                break;
            }
            String zename = ze.getName();
            if (zename == null || !zename.endsWith((".sqlite3"))) {
                continue;
            }
            sep = zename.lastIndexOf(File.separator);
            if (sep != -1) {
                zename = zename.substring(sep + 1);
            }
            File file;
            String version = zename.toLowerCase(Locale.US).replace(".sqlite3", "");
            if (versionpaths.containsKey(version)) {
                file = new File(versionpaths.get(version));
            } else {
                file = new File(dirpath, zename);
            }
            if (file.exists() && file.lastModified() > ze.getTime()
                    && file.lastModified() > path.lastModified()) {
                continue;
            }
            Log.d(TAG, "unpacking " + file.getAbsoluteFile());
            int length;
            File tmpfile = new File(dirpath, zename + ".tmp");
            OutputStream os = new BufferedOutputStream(new FileOutputStream(tmpfile));
            byte[] buffer = new byte[8192];
            int zero = 0;
            while ((length = zis.read(buffer)) != -1) {
                if (length == 0) {
                    ++zero;
                    if (zero > 3) {
                        break;
                    }
                } else {
                    zero = 0;
                }
                os.write(buffer, 0, length);
            }
            os.close();
            if (zero > 3) {
                return false;
            } else {
                tmpfile.renameTo(file);
                path.delete();
                return true;
            }
        }
    } finally {
        is.close();
        zis.close();
    }
    return false;
}

From source file:org.alfresco.repo.workflow.jbpm.JBPMEngine.java

/**
 * Construct a Process Definition from the provided Process Definition
 * stream// w  ww  .  j av a 2 s. c o  m
 * 
 * @param definitionStream
 *            stream to create process definition from
 * @param mimetype
 *            mimetype of stream
 * @return  process definition
 */
@SuppressWarnings("unchecked")
protected CompiledProcessDefinition compileProcessDefinition(InputStream definitionStream, String mimetype) {
    String actualMimetype = (mimetype == null) ? MimetypeMap.MIMETYPE_ZIP : mimetype;
    CompiledProcessDefinition compiledDef = null;

    // parse process definition from jBPM process archive file

    if (actualMimetype.equals(MimetypeMap.MIMETYPE_ZIP)) {
        ZipInputStream zipInputStream = null;
        try {
            zipInputStream = new ZipInputStream(definitionStream);
            ProcessArchive reader = new ProcessArchive(zipInputStream);
            ProcessDefinition def = reader.parseProcessDefinition();
            compiledDef = new CompiledProcessDefinition(def, reader.getProblems());
        } catch (Exception e) {
            String msg = messageService.getMessage(ERR_COMPILE_PROCESS_DEF_zip);
            throw new JbpmException(msg, e);
        } finally {
            if (zipInputStream != null) {
                try {
                    zipInputStream.close();
                } catch (IOException e) {
                    // Intentionally empty!
                }
            }
        }
    }

    // parse process definition from jBPM xml file

    else if (actualMimetype.equals(MimetypeMap.MIMETYPE_XML)) {
        try {
            JBPMJpdlXmlReader jpdlReader = new JBPMJpdlXmlReader(definitionStream);
            ProcessDefinition def = jpdlReader.readProcessDefinition();
            List<Problem> problems = jpdlReader.getProblems();
            compiledDef = new CompiledProcessDefinition(def, problems);
        } catch (Exception e) {
            String msg = messageService.getMessage(ERR_COMPILE_PROCESS_DEF_XML);
            throw new JbpmException(msg, e);
        }
    } else {
        String msg = messageService.getMessage(ERR_COMPILE_PROCESS_DEF_UNSUPPORTED, mimetype);
        throw new JbpmException(msg);
    }

    if (tenantService.isEnabled()) {
        compiledDef.def.setName(tenantService.getName(compiledDef.def.getName()));
    }

    return compiledDef;
}

From source file:jp.co.opentone.bsol.linkbinder.service.correspon.impl.CorresponSearchServiceImplTest.java

/**
 * ZIP?./*from w ww  .  j a v a  2 s .c om*/
 * HTML??? + ???????.
 */
@Test
public void testGenerateZipHtmlName() throws Exception {
    List<String> nullKeys = new ArrayList<String>();
    nullKeys.add("file.name.regex");
    nullKeys.add("file.name.replacement");
    MockSystemConfig.NULL_KEYS = nullKeys;

    MockAbstractService.RET_CURRENT_PROJECT_ID = "PJ1";

    List<Correspon> corresponlist = new ArrayList<Correspon>();
    Correspon c = new Correspon();
    c.setId(1L);
    c.setCorresponNo("YOC:OT:BUILDING-00001");
    c.setWorkflows(new ArrayList<Workflow>());
    corresponlist.add(c);
    c = new Correspon();
    c.setId(2L);
    c.setCorresponNo(null); // ????
    c.setWorkflows(new ArrayList<Workflow>());
    corresponlist.add(c);
    c = new Correspon();
    c.setId(3L);
    c.setCorresponNo(" "); // ?
    c.setWorkflows(new ArrayList<Workflow>());
    corresponlist.add(c);
    c = new Correspon();
    c.setId(4L);
    c.setCorresponNo("\\/:*?\"<>|"); // ?
    c.setWorkflows(new ArrayList<Workflow>());
    corresponlist.add(c);
    c = new Correspon();
    c.setId(9999999999L); // ???
    c.setCorresponNo("YOC:OT:BUILDING-00001");
    c.setWorkflows(new ArrayList<Workflow>());
    corresponlist.add(c);
    c = new Correspon();
    c.setId(10000000000L); // 10?
    c.setCorresponNo("YOC:OT:BUILDING-00001");
    c.setWorkflows(new ArrayList<Workflow>());
    corresponlist.add(c);

    MockCorresponService.RET_FIND = corresponlist;
    MockAbstractService.CORRESPONS = corresponlist;

    byte[] actual = service.generateZip(corresponlist);

    ByteArrayInputStream bi = new ByteArrayInputStream(actual);
    ZipInputStream zis = new ZipInputStream(bi);
    String[] expFileNames = { "PJ1_YOC-OT-BUILDING-00001(0000000001).html", "PJ1_(0000000002).html",
            "PJ1_ (0000000003).html", "PJ1_---------(0000000004).html",
            "PJ1_YOC-OT-BUILDING-00001(9999999999).html", "PJ1_YOC-OT-BUILDING-00001(10000000000).html" };
    int index = 0;
    try {
        for (ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) {
            String expFileName = expFileNames[index];
            assertEquals(expFileName, ze.getName());
            if (ze.isDirectory()) {
                continue;
            }
            index++;
        }
    } finally {
        zis.close();
        bi.close();
    }
}