Example usage for java.util.zip ZipInputStream read

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

Introduction

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

Prototype

public int read(byte b[]) throws IOException 

Source Link

Document

Reads up to b.length bytes of data from this input stream into an array of bytes.

Usage

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.//  w w  w  .j  a va  2s  . c  o  m
 **/
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:org.yccheok.jstock.gui.Utils.java

public static boolean extractZipFile(File zipFilePath, String destDirectory, boolean overwrite) {
    InputStream inputStream = null;
    ZipInputStream zipInputStream = null;
    boolean status = true;

    try {/*from  w ww.ja  v  a2 s  .c om*/
        inputStream = new FileInputStream(zipFilePath);

        zipInputStream = new ZipInputStream(inputStream);
        final byte[] data = new byte[1024];

        while (true) {
            ZipEntry zipEntry = null;
            FileOutputStream outputStream = null;

            try {
                zipEntry = zipInputStream.getNextEntry();

                if (zipEntry == null) {
                    break;
                }

                final String destination;
                if (destDirectory.endsWith(File.separator)) {
                    destination = destDirectory + zipEntry.getName();
                } else {
                    destination = destDirectory + File.separator + zipEntry.getName();
                }

                if (overwrite == false) {
                    if (Utils.isFileOrDirectoryExist(destination)) {
                        continue;
                    }
                }

                if (zipEntry.isDirectory()) {
                    Utils.createCompleteDirectoryHierarchyIfDoesNotExist(destination);
                } else {
                    final File file = new File(destination);
                    // Ensure directory is there before we write the file.
                    Utils.createCompleteDirectoryHierarchyIfDoesNotExist(file.getParentFile());

                    int size = zipInputStream.read(data);

                    if (size > 0) {
                        outputStream = new FileOutputStream(destination);

                        do {
                            outputStream.write(data, 0, size);
                            size = zipInputStream.read(data);
                        } while (size >= 0);
                    }
                }
            } catch (IOException exp) {
                log.error(null, exp);
                status = false;
                break;
            } finally {
                org.yccheok.jstock.file.Utils.close(outputStream);
                org.yccheok.jstock.file.Utils.closeEntry(zipInputStream);
            }

        } // while(true)
    } catch (IOException exp) {
        log.error(null, exp);
        status = false;
    } finally {
        org.yccheok.jstock.file.Utils.close(zipInputStream);
        org.yccheok.jstock.file.Utils.close(inputStream);
    }
    return status;
}

From source file:org.opendatakit.survey.android.tasks.InitializationTask.java

private final void extractFromRawZip(int resourceId, boolean overwrite, ArrayList<String> result) {
    String message = null;/*  w  w w . j a  va 2 s  .  c o  m*/
    AssetFileDescriptor fd = null;
    try {
        fd = appContext.getResources().openRawResourceFd(resourceId);
        final long size = fd.getLength(); // apparently over-counts by 2x?
        InputStream rawInputStream = null;
        try {
            rawInputStream = fd.createInputStream();
            ZipInputStream zipInputStream = null;
            ZipEntry entry = null;
            try {

                // count the number of files in the zip
                zipInputStream = new ZipInputStream(rawInputStream);
                int totalFiles = 0;
                while ((entry = zipInputStream.getNextEntry()) != null) {
                    message = null;
                    if (isCancelled()) {
                        message = "cancelled";
                        result.add(entry.getName() + " " + message);
                        break;
                    }
                    ++totalFiles;
                }
                zipInputStream.close();

                // and re-open the stream, reading it this time...
                fd = appContext.getResources().openRawResourceFd(resourceId);
                rawInputStream = fd.createInputStream();
                zipInputStream = new ZipInputStream(rawInputStream);

                long bytesProcessed = 0L;
                long lastBytesProcessedThousands = 0L;
                int nFiles = 0;
                while ((entry = zipInputStream.getNextEntry()) != null) {
                    message = null;
                    if (isCancelled()) {
                        message = "cancelled";
                        result.add(entry.getName() + " " + message);
                        break;
                    }
                    ++nFiles;
                    File tempFile = new File(ODKFileUtils.getAppFolder(appName), entry.getName());
                    String formattedString = appContext.getString(R.string.expansion_unzipping_without_detail,
                            entry.getName(), nFiles, totalFiles);
                    String detail;
                    if (entry.isDirectory()) {
                        detail = appContext.getString(R.string.expansion_create_dir_detail);
                        publishProgress(formattedString, detail);
                        tempFile.mkdirs();
                    } else if (overwrite || !tempFile.exists()) {
                        int bufferSize = 8192;
                        OutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile, false),
                                bufferSize);
                        byte buffer[] = new byte[bufferSize];
                        int bread;
                        while ((bread = zipInputStream.read(buffer)) != -1) {
                            bytesProcessed += bread;
                            long curThousands = (bytesProcessed / 1000L);
                            if (curThousands != lastBytesProcessedThousands) {
                                detail = appContext.getString(R.string.expansion_unzipping_detail,
                                        bytesProcessed, size);
                                publishProgress(formattedString, detail);
                                lastBytesProcessedThousands = curThousands;
                            }
                            out.write(buffer, 0, bread);
                        }
                        out.flush();
                        out.close();

                        detail = appContext.getString(R.string.expansion_unzipping_detail, bytesProcessed,
                                size);
                        publishProgress(formattedString, detail);
                    }
                    WebLogger.getLogger(appName).i(t, "Extracted ZipEntry: " + entry.getName());
                }

                String completionString = appContext.getString(R.string.expansion_unzipping_complete,
                        totalFiles);
                publishProgress(completionString, null);
            } catch (IOException e) {
                WebLogger.getLogger(appName).printStackTrace(e);
                mPendingSuccess = false;
                if (e.getCause() != null) {
                    message = e.getCause().getMessage();
                } else {
                    message = e.getMessage();
                }
                if (entry != null) {
                    result.add(entry.getName() + " " + message);
                } else {
                    result.add("Error accessing zipfile resource " + message);
                }
            } finally {
                if (zipInputStream != null) {
                    try {
                        zipInputStream.close();
                    } catch (IOException e) {
                        WebLogger.getLogger(appName).printStackTrace(e);
                        WebLogger.getLogger(appName).e(t, "Closing of ZipFile failed: " + e.toString());
                    }
                }
            }
        } catch (Exception e) {
            WebLogger.getLogger(appName).printStackTrace(e);
            mPendingSuccess = false;
            if (e.getCause() != null) {
                message = e.getCause().getMessage();
            } else {
                message = e.getMessage();
            }
            result.add("Error accessing zipfile resource " + message);
        } finally {
            if (rawInputStream != null) {
                try {
                    rawInputStream.close();
                } catch (IOException e) {
                    WebLogger.getLogger(appName).printStackTrace(e);
                }
            }
        }
    } finally {
        if (fd != null) {
            try {
                fd.close();
            } catch (IOException e) {
                WebLogger.getLogger(appName).printStackTrace(e);
            }
        } else {
            result.add("Error accessing zipfile resource.");
        }
    }
}

From source file:edu.harvard.iq.dvn.core.web.study.AddFilesPage.java

private List<StudyFileEditBean> createStudyFilesFromZip(File uploadedInputFile) {
    List<StudyFileEditBean> fbList = new ArrayList<StudyFileEditBean>();

    // This is a Zip archive that we want to unpack, then upload/ingest individual
    // files separately

    ZipInputStream ziStream = null;
    ZipEntry zEntry = null;//ww w.j a  va2 s .  co m
    FileOutputStream tempOutStream = null;

    try {
        // Create ingest directory for the study: 
        File dir = new File(uploadedInputFile.getParentFile(), study.getId().toString());
        if (!dir.exists()) {
            dir.mkdir();
        }

        // Open Zip stream: 

        ziStream = new ZipInputStream(new FileInputStream(uploadedInputFile));

        if (ziStream == null) {
            return null;
        }
        while ((zEntry = ziStream.getNextEntry()) != null) {
            // Note that some zip entries may be directories - we 
            // simply skip them:
            if (!zEntry.isDirectory()) {

                String fileEntryName = zEntry.getName();

                if (fileEntryName != null && !fileEntryName.equals("")) {

                    String dirName = null;
                    String finalFileName = null;

                    int ind = fileEntryName.lastIndexOf('/');

                    if (ind > -1) {
                        finalFileName = fileEntryName.substring(ind + 1);
                        if (ind > 0) {
                            dirName = fileEntryName.substring(0, ind);
                            dirName = dirName.replace('/', '-');
                        }
                    } else {
                        finalFileName = fileEntryName;
                    }

                    // http://superuser.com/questions/212896/is-there-any-way-to-prevent-a-mac-from-creating-dot-underscore-files
                    if (!finalFileName.startsWith("._")) {
                        File tempUploadedFile = FileUtil.createTempFile(dir, finalFileName);

                        tempOutStream = new FileOutputStream(tempUploadedFile);

                        byte[] dataBuffer = new byte[8192];
                        int i = 0;

                        while ((i = ziStream.read(dataBuffer)) > 0) {
                            tempOutStream.write(dataBuffer, 0, i);
                            tempOutStream.flush();
                        }

                        tempOutStream.close();

                        // We now have the unzipped file saved in the upload directory;

                        StudyFileEditBean tempFileBean = new StudyFileEditBean(tempUploadedFile,
                                studyService.generateFileSystemNameSequence(), study);
                        tempFileBean.setSizeFormatted(tempUploadedFile.length());

                        // And, if this file was in a legit (non-null) directory, 
                        // we'll use its name as the file category: 

                        if (dirName != null) {
                            tempFileBean.getFileMetadata().setCategory(dirName);
                        }

                        fbList.add(tempFileBean);
                    }
                }
            }
            ziStream.closeEntry();

        }

    } catch (Exception ex) {
        String msg = "Failed ot unpack Zip file/create individual study files";

        dbgLog.warning(msg);
        dbgLog.warning(ex.getMessage());

        //return null; 
    } finally {
        if (ziStream != null) {
            try {
                ziStream.close();
            } catch (Exception zEx) {
            }
        }
        if (tempOutStream != null) {
            try {
                tempOutStream.close();
            } catch (Exception ioEx) {
            }
        }
    }

    // should we delete uploadedInputFile before return?
    return fbList;
}

From source file:org.openremote.modeler.cache.LocalFileCache.java

/**
 * Extracts a source resource archive to target path in local filesystem. Necessary
 * subdirectories will be created according to archive structure if necessary. Existing
 * files and directories matching the archive structure <b>will be deleted!</b>
 *
 * @param sourceArchive     file path to source archive in the local filesystem.
 * @param targetDirectory   file path to target directory where to extract the archive
 *
 * @throws CacheOperationException//www .j a  v  a2  s.co m
 *            if any file I/O errors occured during the extract operation
 *
 * @throws ConfigurationException
 *            if security manager has imposed access restrictions to the required files or
 *            directories
 */
private void extract(File sourceArchive, File targetDirectory)
        throws CacheOperationException, ConfigurationException {
    ZipInputStream archiveInput = null;
    ZipEntry zipEntry;

    try {
        archiveInput = new ZipInputStream(new BufferedInputStream(new FileInputStream(sourceArchive)));

        while ((zipEntry = archiveInput.getNextEntry()) != null) {
            if (zipEntry.isDirectory()) {
                // Do nothing -- relevant subdirectories will be created when handling the node files...

                continue;
            }

            File extractFile = new File(targetDirectory, zipEntry.getName());
            BufferedOutputStream extractOutput = null;

            try {
                FileUtilsExt.deleteQuietly(extractFile); // TODO : don't be quiet

                // create parent directories if necessary...

                if (!extractFile.getParentFile().exists()) {
                    boolean success = extractFile.getParentFile().mkdirs();

                    if (!success) {
                        throw new CacheOperationException(
                                "Unable to create cache folder directories ''{0}''. Reason unknown.",
                                extractFile.getParent());
                    }
                }

                extractOutput = new BufferedOutputStream(new FileOutputStream(extractFile));

                int len, bytecount = 0;
                byte[] buffer = new byte[4096];

                while ((len = archiveInput.read(buffer)) != -1) {
                    try {
                        extractOutput.write(buffer, 0, len);

                        bytecount += len;
                    }

                    catch (IOException e) {
                        throw new CacheOperationException("Error writing to ''{0}'' : {1}", e,
                                extractFile.getAbsolutePath(), e.getMessage());
                    }
                }

                cacheLog.debug("Wrote {0} bytes to ''{1}''...", bytecount, extractFile.getAbsolutePath());
            }

            catch (SecurityException e) {
                throw new ConfigurationException("Security manager has denied access to ''{0}'' : {1}", e,
                        extractFile.getAbsolutePath(), e.getMessage());
            }

            catch (FileNotFoundException e) {
                throw new CacheOperationException("Could not create file ''{0}'' : {1}", e,
                        extractFile.getAbsolutePath(), e.getMessage());
            }

            catch (IOException e) {
                throw new CacheOperationException("Error reading zip entry ''{0}'' from ''{1}'' : {2}", e,
                        zipEntry.getName(), sourceArchive.getAbsolutePath(), e.getMessage());
            }

            finally {
                if (extractOutput != null) {
                    try {
                        extractOutput.close();
                    }

                    catch (Throwable t) {
                        cacheLog.error("Could not close extracted file ''{0}'' : {1}", t,
                                extractFile.getAbsolutePath(), t.getMessage());
                    }
                }

                if (archiveInput != null) {
                    try {
                        archiveInput.closeEntry();
                    }

                    catch (Throwable t) {
                        cacheLog.warn("Could not close zip entry ''{0}'' in archive ''{1}'' : {2}", t,
                                zipEntry.getName(), t.getMessage());
                    }
                }
            }
        }
    }

    catch (SecurityException e) {
        throw new ConfigurationException("Security Manager has denied access to ''{0}'' : {1}", e,
                sourceArchive.getAbsolutePath(), e.getMessage());
    }

    catch (FileNotFoundException e) {
        throw new CacheOperationException("Archive ''{0}'' cannot be opened for reading : {1}", e,
                sourceArchive.getAbsolutePath(), e.getMessage());
    }

    catch (IOException e) {
        throw new CacheOperationException("Error reading archive ''{0}'' : {1}", e,
                sourceArchive.getAbsolutePath(), e.getMessage());
    }

    finally {
        try {
            if (archiveInput != null) {
                archiveInput.close();
            }
        }

        catch (Throwable t) {
            cacheLog.error("Error closing input stream to archive ''{0}'' : {1}", t,
                    sourceArchive.getAbsolutePath(), t.getMessage());
        }
    }
}

From source file:oscar.oscarDemographic.pageUtil.ImportDemographicDataAction4.java

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    admProviderNo = (String) request.getSession().getAttribute("user");
    programId = new EctProgram(request.getSession()).getProgram(admProviderNo);
    String tmpDir = oscarProperties.getProperty("TMP_DIR");
    tmpDir = Util.fixDirName(tmpDir);
    if (!Util.checkDir(tmpDir)) {
        logger.debug("Error! Cannot write to TMP_DIR - Check oscar.properties or dir permissions.");
    }/*from  ww w .j  a v a2  s  .  c o m*/

    ImportDemographicDataForm frm = (ImportDemographicDataForm) form;
    logger.info(
            "import to course id " + frm.getCourseId() + " using timeshift value " + frm.getTimeshiftInDays());
    List<Provider> students = new ArrayList<Provider>();
    int courseId = 0;
    if (frm.getCourseId() != null && frm.getCourseId().length() > 0) {
        courseId = Integer.valueOf(frm.getCourseId());
        if (courseId > 0) {
            logger.info("need to apply this import to a learning environment");
            //get all the students from this course
            List<ProgramProvider> courseProviders = programManager
                    .getProgramProviders(String.valueOf(courseId));
            for (ProgramProvider pp : courseProviders) {
                if (pp.getRole().getName().equalsIgnoreCase("student")) {
                    students.add(pp.getProvider());
                }
            }
        }
    }
    logger.info("apply this patient to " + students.size() + " students");
    matchProviderNames = frm.getMatchProviderNames();
    FormFile imp = frm.getImportFile();
    String ifile = tmpDir + imp.getFileName();
    ArrayList<String> warnings = new ArrayList<String>();
    ArrayList<String[]> logs = new ArrayList<String[]>();
    File importLog = null;

    if ("true"
            .equalsIgnoreCase(oscarProperties.getProperty("IMPORT_ALL_DEMOGRAPHIC_XML_FILES_IN_ONE_FOLDER"))) {
        try {
            File directory = new File(tmpDir);
            for (File file : directory.listFiles()) {
                String fileName = tmpDir + file.getName();
                warnings.add("*** Start to process file : " + fileName);
                if (matchFileExt(fileName, "xml")) {
                    logs.add(importXML(fileName, warnings, request, frm.getTimeshiftInDays(), students,
                            courseId));
                    demographicNo = null;
                    importNo++;
                }
            }
            importLog = makeImportLog(logs, tmpDir);
        } catch (Exception e) {
            warnings.add(
                    "Got exception when processing the file above. Please check error log in tomcat log file. ");
            logger.error("Import demographic xml files, got error : ", e);
        }
    } else {

        try {

            InputStream is = imp.getInputStream();
            OutputStream os = new FileOutputStream(ifile);
            byte[] buf = new byte[1024];
            int len;
            while ((len = is.read(buf)) > 0)
                os.write(buf, 0, len);
            is.close();
            os.close();

            if (matchFileExt(ifile, "zip")) {
                ZipInputStream in = new ZipInputStream(new FileInputStream(ifile));
                boolean noXML = true;
                ZipEntry entry = in.getNextEntry();
                String entryDir = "";

                while (entry != null) {
                    String entryName = entry.getName();
                    if (entry.isDirectory())
                        entryDir = entryName;
                    if (entryName.startsWith(entryDir))
                        entryName = entryName.substring(entryDir.length());

                    String ofile = tmpDir + entryName;
                    if (matchFileExt(ofile, "xml")) {
                        noXML = false;
                        OutputStream out = new FileOutputStream(ofile);
                        while ((len = in.read(buf)) > 0)
                            out.write(buf, 0, len);
                        out.close();
                        logs.add(importXML(ofile, warnings, request, frm.getTimeshiftInDays(), students,
                                courseId));
                        importNo++;
                        demographicNo = null;
                    }
                    entry = in.getNextEntry();
                }
                if (noXML) {
                    Util.cleanFile(ifile);
                    throw new Exception("Error! No .xml file in zip");
                } else {
                    importLog = makeImportLog(logs, tmpDir);
                }
                in.close();
                Util.cleanFile(ifile);

            } else if (matchFileExt(ifile, "xml")) {
                logs.add(importXML(ifile, warnings, request, frm.getTimeshiftInDays(), students, courseId));
                demographicNo = null;
                importLog = makeImportLog(logs, tmpDir);
            } else {
                Util.cleanFile(ifile);
                throw new Exception("Error! Import file must be .xml or .zip");
            }
        } catch (Exception e) {
            warnings.add("Error processing file: " + imp.getFileName());
            logger.error("Error", e);
        }
    }
    //channel warnings and importlog to browser
    request.setAttribute("warnings", warnings);
    if (importLog != null)
        request.setAttribute("importlog", importLog.getPath());

    return mapping.findForward("success");
}

From source file:org.crs4.entando.innomanager.aps.system.services.layer.LayerManager.java

@Override
public File unzipShapeFile(String layername, File zipFile, String zipFileName) {
    int page = 0;
    InputStream fis;/*w ww .  j  a  va 2  s .c o m*/
    ZipInputStream zis;
    FileOutputStream fos;
    byte[] buffer = new byte[1024];
    String type;
    File newFile;
    String path = "";
    WorkLayer layer;
    try {
        layer = this.getWorkLayer(layername);
        path = getShapeFileDiskFolder(layername);
        if (layer == null)
            return null;
    } catch (Throwable t) {
        ApsSystemUtils.logThrowable(t, this, "UnZipShapeFile");
        return null;
    }
    if (!zipFileName.substring(zipFileName.length() - 4).equals(".zip"))
        return null;
    String fileName = null;
    String shapefileName = null;
    //try to unzip 
    boolean reset = false;
    try {
        fis = FileUtils.openInputStream(zipFile);
        zis = new ZipInputStream(fis);
        //get the zipped file list entry
        ZipEntry ze = zis.getNextEntry();

        boolean[] ext = { true, true, true };
        // controllo contenuto zip ( only the first 3 files: .shx, .shp, .dbf with the same name)
        while (ze != null) {
            type = null;
            ApsSystemUtils.getLogger().info("parse file: " + ze.getName());
            if (ze.getName().substring(ze.getName().length() - 4).equals(".shp")
                    && (shapefileName == null
                            || ze.getName().substring(0, ze.getName().length() - 4).equals(shapefileName))
                    && ext[0]) {
                type = ".shp";
                ext[0] = false;
            } else if (ze.getName().substring(ze.getName().length() - 4).equals(".dbf")
                    && (shapefileName == null
                            || ze.getName().substring(0, ze.getName().length() - 4).equals(shapefileName))
                    && ext[1]) {
                type = ".dbf";
                ext[1] = false;
            } else if (ze.getName().substring(ze.getName().length() - 4).equals(".shx")
                    && (shapefileName == null
                            || ze.getName().substring(0, ze.getName().length() - 4).equals(shapefileName))
                    && ext[2]) {
                type = ".shx";
                ext[2] = false;
            }
            // else the shapefiles haven't good ext or name 
            ApsSystemUtils.getLogger().info("type: " + type);

            // set the correct name of the shapefiles  (the first valid)

            if (type != null) {
                if (fileName == null) {
                    shapefileName = ze.getName().substring(0, ze.getName().length() - 4);
                    fileName = zipFileName.substring(0, zipFileName.length() - 4);
                    boolean found = false;
                    /// if exist changename
                    while (!found) {
                        newFile = new File(path + fileName + ".shp");
                        if (newFile.exists())
                            fileName += "0";
                        else
                            found = true;
                    }
                }
                ApsSystemUtils.getLogger().info("file write: " + path + fileName + type);
                newFile = new File(path + fileName + type);
                if (newFile.exists())
                    FileUtils.forceDelete(newFile);
                newFile = new File(path + fileName + type);
                {
                    fos = new FileOutputStream(newFile);
                    int len;
                    while ((len = zis.read(buffer)) > 0) {
                        fos.write(buffer, 0, len);
                    }
                    fos.close();
                    zis.closeEntry();
                }
            }
            ze = zis.getNextEntry();
        }
        zis.close();
    } catch (Throwable t) {
        ApsSystemUtils.logThrowable(t, this, "UnZippingShapeFile");
        reset = true;
    }
    if (fileName != null) {
        if (reset) {
            removeShapeFile(layername, fileName + ".shp");
        } else {
            newFile = new File(path + fileName + ".shp");
            if (newFile.exists())
                return newFile;
        }
    }
    return null;
}

From source file:org.openbravo.erpCommon.modules.ImportModule.java

/**
 * Installs or updates the modules in the obx file
 * //  www. ja  v  a 2s.  com
 * @param obx
 * @param moduleID
 *          The ID for the current module to install
 * @throws Exception
 */
private void installModule(InputStream obx, String moduleID, Vector<DynaBean> dModulesToInstall,
        Vector<DynaBean> dDependencies, Vector<DynaBean> dDBprefix) throws Exception {

    // For local installations modules are temporary unzipped in tmp/localInstall directory, because
    // it is possible this version in obx is not going to be installed, in any case it must be
    // unzipped looking for other obx files inside it.
    String fileDestination = installLocally && !"0".equals(moduleID) ? obDir + "/tmp/localInstall" : obDir;

    if (!(new File(fileDestination + "/modules").canWrite())) {
        addLog("@CannotWriteDirectory@ " + fileDestination + "/modules. ", MSG_ERROR);
        throw new PermissionException("Cannot write on directory: " + fileDestination + "/modules");
    }

    final ZipInputStream obxInputStream = new ZipInputStream(obx);
    ZipEntry entry = null;
    while ((entry = obxInputStream.getNextEntry()) != null) {
        if (entry.getName().endsWith(".obx")) { // If it is a new module
            // install it
            if (installLocally) {
                final ByteArrayInputStream ba = new ByteArrayInputStream(
                        getBytesCurrentEntryStream(obxInputStream));

                installModule(ba, moduleID, dModulesToInstall, dDependencies, dDBprefix);
            } // If install remotely it is no necessary to install the .obx
              // because it will be get from CR
            obxInputStream.closeEntry();
        } else {
            // Unzip the contents
            final String fileName = fileDestination + (moduleID.equals("0") ? "/" : "/modules/")
                    + entry.getName().replace("\\", "/");
            final File entryFile = new File(fileName);
            // Check whether the directory exists, if not create

            File dir = null;
            if (entryFile.getParent() != null)
                dir = new File(entryFile.getParent());
            if (entry.isDirectory())
                dir = entryFile;

            if (entry.isDirectory() || entryFile.getParent() != null) {
                if (!dir.exists()) {
                    log4j.debug("Created dir: " + dir.getAbsolutePath());
                    dir.mkdirs();
                }
            }

            if (!entry.isDirectory()) {
                // It is a file
                byte[] entryBytes = null;
                boolean found = false;
                // Read the xml file to obtain module info
                if (entry.getName().replace("\\", "/").endsWith("src-db/database/sourcedata/AD_MODULE.xml")) {
                    entryBytes = getBytesCurrentEntryStream(obxInputStream);
                    final Vector<DynaBean> module = getEntryDynaBeans(entryBytes);
                    moduleID = (String) module.get(0).get("AD_MODULE_ID");
                    if (installingModule(moduleID)) {
                        dModulesToInstall.addAll(module);
                    }
                    obxInputStream.closeEntry();
                    found = true;
                } else if (entry.getName().replace("\\", "/")
                        .endsWith("src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml")) {
                    entryBytes = getBytesCurrentEntryStream(obxInputStream);
                    final Vector<DynaBean> dep = getEntryDynaBeans(entryBytes);
                    if (installingModule((String) dep.get(0).get("AD_MODULE_ID"))) {
                        dDependencies.addAll(dep);
                    }
                    obxInputStream.closeEntry();
                    found = true;
                } else if (entry.getName().replace("\\", "/")
                        .endsWith("src-db/database/sourcedata/AD_MODULE_DBPREFIX.xml")) {
                    entryBytes = getBytesCurrentEntryStream(obxInputStream);
                    final Vector<DynaBean> dbp = getEntryDynaBeans(entryBytes);
                    if (installingModule((String) dbp.get(0).get("AD_MODULE_ID"))) {
                        dDBprefix.addAll(dbp);
                    }
                    obxInputStream.closeEntry();
                    found = true;
                }

                // Unzip the file
                log4j.debug("Installing " + fileName);

                final FileOutputStream fout = new FileOutputStream(entryFile);

                if (found) {
                    // the entry is already read as a byte[]
                    fout.write(entryBytes);
                } else {
                    final byte[] buf = new byte[4096];
                    int len;
                    while ((len = obxInputStream.read(buf)) > 0) {
                        fout.write(buf, 0, len);
                    }
                }

                fout.close();
            }

            obxInputStream.closeEntry();
        }
    }
    obxInputStream.close();
}

From source file:lu.fisch.unimozer.Diagram.java

/**
 * http://snippets.dzone.com/posts/show/3468
 * modified to create the zip file if it does not exist
 * //from  w  w  w .  j a  va  2 s  . c  o m
 * @param zipFile
 * @param files
 * @throws IOException
 */
public void addFilesToExistingZip(File zipFile, String baseDir, File directory) throws IOException {
    ZipOutputStream out;
    File tempFile = null;

    byte[] buf = new byte[1024];
    boolean delete = false;

    if (zipFile.exists()) {
        delete = true;
        // get a temp file
        tempFile = File.createTempFile(zipFile.getName(), null);
        // delete it, otherwise you cannot rename your existing zip to it.
        tempFile.delete();

        boolean renameOk = zipFile.renameTo(tempFile);
        if (!renameOk) {
            throw new RuntimeException("could not rename the file " + zipFile.getAbsolutePath() + " to "
                    + tempFile.getAbsolutePath());
        }

        ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
        out = new ZipOutputStream(new FileOutputStream(zipFile));

        ZipEntry entry = zin.getNextEntry();
        while (entry != null) {
            String name = entry.getName();
            boolean notInFiles = true;
            /*
            for (File f : files)
            {
            if (f.getName().equals(name))
            {
                notInFiles = false;
                break;
            }
            }*/
            if (notInFiles) {
                // Add ZIP entry to output stream.
                out.putNextEntry(new ZipEntry(name));
                // Transfer bytes from the ZIP file to the output file
                int len;
                while ((len = zin.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
            }
            entry = zin.getNextEntry();
        }
        // Close the streams
        zin.close();
    } else {
        out = new ZipOutputStream(new FileOutputStream(zipFile));
    }
    /*
    // Compress the files
    for (int i = 0; i < files.length; i++)
    {
    InputStream in = new FileInputStream(files[i]);
    // Add ZIP entry to output stream.
    out.putNextEntry(new ZipEntry(files[i].getName()));
    // Transfer bytes from the file to the ZIP file
    int len;
    while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
    }
    // Complete the entry
    out.closeEntry();
    in.close();
    }
    */

    addToZip(out, baseDir, directory);

    // Complete the ZIP file
    out.close();

    if (delete == true)
        tempFile.delete();
}

From source file:com.portfolio.data.provider.MysqlAdminProvider.java

public static String unzip(String zipFile, String destinationFolder) throws FileNotFoundException, IOException {
    String folder = "";
    File zipfile = new File(zipFile);
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipfile)));

    ZipEntry ze = null;/*from  w  w w.j ava 2 s  . co m*/
    try {
        while ((ze = zis.getNextEntry()) != null) {

            //folder = zipfile.getCanonicalPath().substring(0, zipfile.getCanonicalPath().length()-4)+"/";
            folder = destinationFolder;
            File f = new File(folder, ze.getName());

            if (ze.isDirectory()) {
                f.mkdirs();
                continue;
            }

            f.getParentFile().mkdirs();
            OutputStream fos = new BufferedOutputStream(new FileOutputStream(f));
            try {
                try {
                    final byte[] buf = new byte[8192];
                    int bytesRead;
                    while (-1 != (bytesRead = zis.read(buf)))
                        fos.write(buf, 0, bytesRead);
                } finally {
                    fos.close();
                }
            } catch (final IOException ioe) {
                f.delete();
                throw ioe;
            }
        }
    } finally {
        zis.close();
    }
    return folder;
}