Example usage for java.util.zip ZipEntry isDirectory

List of usage examples for java.util.zip ZipEntry isDirectory

Introduction

In this page you can find the example usage for java.util.zip ZipEntry isDirectory.

Prototype

public boolean isDirectory() 

Source Link

Document

Returns true if this is a directory entry.

Usage

From source file:com.hichinaschool.flashcards.libanki.Utils.java

public static boolean unzipFiles(ZipFile zipFile, String targetDirectory, String[] zipEntries,
        HashMap<String, String> zipEntryToFilenameMap) {
    byte[] buf = new byte[FILE_COPY_BUFFER_SIZE];
    File dir = new File(targetDirectory);
    if (!dir.exists() && !dir.mkdirs()) {
        Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Could not create target directory: " + targetDirectory);
        return false;
    }//from w w w.j  a  v a 2  s  .co  m
    if (zipEntryToFilenameMap == null) {
        zipEntryToFilenameMap = new HashMap<String, String>();
    }
    BufferedInputStream zis = null;
    BufferedOutputStream bos = null;
    try {
        for (String requestedEntry : zipEntries) {
            ZipEntry ze = zipFile.getEntry(requestedEntry);
            if (ze != null) {
                String name = ze.getName();
                if (zipEntryToFilenameMap.containsKey(name)) {
                    name = zipEntryToFilenameMap.get(name);
                }
                File destFile = new File(dir, name);
                File parentDir = destFile.getParentFile();
                if (!parentDir.exists() && !parentDir.mkdirs()) {
                    return false;
                }
                if (!ze.isDirectory()) {
                    // Log.i(AnkiDroidApp.TAG, "uncompress " + name);
                    zis = new BufferedInputStream(zipFile.getInputStream(ze));
                    bos = new BufferedOutputStream(new FileOutputStream(destFile), FILE_COPY_BUFFER_SIZE);
                    int n;
                    while ((n = zis.read(buf, 0, FILE_COPY_BUFFER_SIZE)) != -1) {
                        bos.write(buf, 0, n);
                    }
                    bos.flush();
                    bos.close();
                    zis.close();
                }
            }
        }
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Error while unzipping archive.", e);
        return false;
    } finally {
        try {
            if (bos != null) {
                bos.close();
            }
        } catch (IOException e) {
            Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Error while closing output stream.", e);
        }
        try {
            if (zis != null) {
                zis.close();
            }
        } catch (IOException e) {
            Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Error while closing zip input stream.", e);
        }
    }
    return true;
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.experiment.AddExperimentWizardController.java

@Override
protected ModelAndView processFinish(HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, Object command, BindException e) throws Exception {
    log.debug("Processing measuration form - adding new measuration");
    ModelAndView mav = new ModelAndView("redirect:/experiments/my-experiments.html");

    mav.addObject("userIsExperimenter", auth.userIsExperimenter());

    AddExperimentWizardCommand data = (AddExperimentWizardCommand) command;

    Experiment experiment;/*from w  w w .  ja  v a 2 s.co m*/

    log.debug("Checking the permission level.");
    if (!auth.userIsExperimenter()) {
        log.debug("User is not experimenter - unable to add experiment. Returning MAV.");
        mav.setViewName("redirect:experiments/userNotExperimenter");
        return mav;
    }

    log.debug("Creating new Measuration object");
    experiment = new Experiment();

    // This assignment is commited only when new experiment is being created
    log.debug("Setting the owner to the logged user.");
    experiment.setPersonByOwnerId(personDao.getLoggedPerson());

    log.debug("Setting the group, which is the new experiment being added into.");
    ResearchGroup researchGroup = new ResearchGroup();
    researchGroup.setResearchGroupId(data.getResearchGroup());
    experiment.setResearchGroup(researchGroup);

    log.debug("Setting Weather object - ID " + data.getWeather());
    Weather weather = new Weather();
    weather.setWeatherId(data.getWeather());
    experiment.setWeather(weather);

    log.debug("Setting Scenario object - ID " + data.getScenario());
    Scenario scenario = new Scenario();
    scenario.setScenarioId(data.getScenario());
    experiment.setScenario(scenario);

    log.debug("Setting Person object (measured person) - ID " + data.getSubjectPerson());
    Person subjectPerson = new Person();
    subjectPerson.setPersonId(data.getSubjectPerson());
    experiment.setPersonBySubjectPersonId(subjectPerson);

    Date startDate = ControllerUtils.getDateFormatWithTime()
            .parse(data.getStartDate() + " " + data.getStartTime());
    experiment.setStartTime(new Timestamp(startDate.getTime()));
    log.debug("Setting start date - " + startDate);

    Date endDate = ControllerUtils.getDateFormatWithTime().parse(data.getEndDate() + " " + data.getEndTime());
    experiment.setEndTime(new Timestamp(endDate.getTime()));
    log.debug("Setting end date - " + endDate);

    log.debug("Setting the temperature - " + data.getTemperature());
    experiment.setTemperature(Integer.parseInt(data.getTemperature()));

    log.debug("Setting the weather note - " + data.getWeatherNote());
    experiment.setEnvironmentNote(data.getWeatherNote());

    log.debug("Started setting the Hardware objects");
    int[] hardwareArray = data.getHardware();
    Set<Hardware> hardwareSet = new HashSet<Hardware>();
    for (int hardwareId : hardwareArray) {
        System.out.println("hardwareId " + hardwareId);
        Hardware tempHardware = hardwareDao.read(hardwareId);
        hardwareSet.add(tempHardware);
        tempHardware.getExperiments().add(experiment);
        log.debug("Added Hardware object - ID " + hardwareId);
    }
    log.debug("Setting Hardware list to Measuration object");
    experiment.setHardwares(hardwareSet);

    log.debug("Started setting the Person objects (coExperimenters)");
    int[] coExperimentersArray = data.getCoExperimenters();
    Set<Person> coExperimenterSet = new HashSet<Person>();
    for (int personId : coExperimentersArray) {
        Person tempExperimenter = personDao.read(personId);
        coExperimenterSet.add(tempExperimenter);
        tempExperimenter.getExperiments().add(experiment);
        log.debug("Added Person object - ID " + tempExperimenter.getPersonId());
    }
    log.debug("Setting Person list to Measuration object");
    experiment.setPersons(coExperimenterSet);

    log.debug("Setting private/public access");
    experiment.setPrivateExperiment(data.isPrivateNote());
    float samplingRate = Float.parseFloat(data.getSamplingRate());
    Digitization digitization = digitizationDao.getDigitizationByParams(samplingRate, -1, "NotKnown");
    if (digitization == null) {
        digitization = new Digitization();
        digitization.setFilter("NotKnown");
        digitization.setGain(-1);
        digitization.setSamplingRate(samplingRate);
        digitizationDao.create(digitization);
    }

    experiment.setDigitization(digitization);
    experiment.setArtifact(artifactDao.read(1));
    experiment.setElectrodeConf(electrodeConfDao.read(1));
    experiment.setSubjectGroup(subjectGroupDao.read(1)); //default subject group

    if (data.getMeasurationId() > 0) { // editing existing measuration
        log.debug("Saving the Measuration object to database using DAO - update()");
        experimentDao.update(experiment);
    } else { // creating new measuration
        log.debug("Saving the Measuration object to database using DAO - create()");
        experimentDao.create(experiment);
    }

    //  log.debug("Creating measuration with ID " + addDataCommand.getMeasurationId());
    //     experiment.setExperimentId(addDataCommand.getMeasurationId());

    log.debug("Creating new Data object.");
    MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest) httpServletRequest;
    // the map containing file names mapped to files
    Map m = mpRequest.getFileMap();
    Set set = m.keySet();
    for (Object key : set) {
        MultipartFile file = (MultipartFile) m.get(key);
        if (file.getOriginalFilename().endsWith(".zip")) {
            ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(file.getBytes()));
            ZipEntry en = zis.getNextEntry();
            while (en != null) {
                if (en.isDirectory()) {
                    en = zis.getNextEntry();
                    continue;
                }
                DataFile dataFile = new DataFile();
                dataFile.setExperiment(experiment);
                String name[] = en.getName().split("/");
                dataFile.setFilename(name[name.length - 1]);
                data.setFileDescription(data.getFileDescription());
                dataFile.setFileContent(Hibernate.createBlob(zis));
                String[] partOfName = en.getName().split("[.]");
                dataFile.setMimetype(partOfName[partOfName.length - 1]);
                dataFileDao.create(dataFile);
                en = zis.getNextEntry();
            }
        } else {
            DataFile dataFile = new DataFile();
            dataFile.setExperiment(experiment);

            log.debug("Original name of uploaded file: " + file.getOriginalFilename());
            String filename = file.getOriginalFilename().replace(" ", "_");
            dataFile.setFilename(filename);

            log.debug("MIME type of the uploaded file: " + file.getContentType());
            if (file.getContentType().length() > MAX_MIMETYPE_LENGTH) {
                int index = filename.lastIndexOf(".");
                dataFile.setMimetype(filename.substring(index));
            } else {
                dataFile.setMimetype(file.getContentType());
            }

            log.debug("Parsing the sapmling rate.");
            dataFile.setDescription(data.getFileDescription());

            log.debug("Setting the binary data to object.");
            dataFile.setFileContent(Hibernate.createBlob(file.getBytes()));

            dataFileDao.create(dataFile);
            log.debug("Data stored into database.");
        }
    }

    log.debug("Returning MAV object");
    return mav;
}

From source file:org.apache.stratos.python.cartridge.agent.integration.tests.PythonAgentIntegrationTest.java

private void unzip(String zipFilePath, String destDirectory) throws IOException {
    File destDir = new File(destDirectory);
    if (!destDir.exists()) {
        destDir.mkdir();/*from  w  w  w  . j a  v a2 s . c  o m*/
    }
    ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
    ZipEntry entry = zipIn.getNextEntry();
    // iterates over entries in the zip file
    while (entry != null) {
        String filePath = destDirectory + 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();
}

From source file:com.t3.persistence.PackedFile.java

public void save() throws IOException {
    CodeTimer saveTimer;/*from ww w  . j a v a2s.  c o  m*/

    if (!dirty) {
        return;
    }
    saveTimer = new CodeTimer("PackedFile.save");
    saveTimer.setEnabled(log.isDebugEnabled());

    // Create the new file
    File newFile = new File(tmpDir.getAbsolutePath() + "/" + new GUID() + ".pak");

    try (ZipOutputStream zout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(newFile)))) {
        zout.setLevel(1); // fast compression
        saveTimer.start("contentFile");
        if (hasFile(CONTENT_FILE)) {
            zout.putNextEntry(new ZipEntry(CONTENT_FILE));
            try (InputStream is = getFileAsInputStream(CONTENT_FILE)) { // When copying, always use an InputStream
                IOUtils.copy(is, zout);
            }
            zout.closeEntry();
        }
        saveTimer.stop("contentFile");

        saveTimer.start("propertyFile");
        if (getPropertyMap().isEmpty()) {
            removeFile(PROPERTY_FILE);
        } else {
            zout.putNextEntry(new ZipEntry(PROPERTY_FILE));
            Persister.newInstance().toXML(getPropertyMap(), zout);
            zout.closeEntry();
        }
        saveTimer.stop("propertyFile");

        // Now put each file
        saveTimer.start("addFiles");
        addedFileSet.remove(CONTENT_FILE);
        for (String path : addedFileSet) {
            zout.putNextEntry(new ZipEntry(path));
            try (InputStream is = getFileAsInputStream(path)) { // When copying, always use an InputStream
                IOUtils.copy(is, zout);
            }
            zout.closeEntry();
        }
        saveTimer.stop("addFiles");

        // Copy the rest of the zip entries over
        saveTimer.start("copyFiles");
        if (file.exists()) {
            Enumeration<? extends ZipEntry> entries = zFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                if (!entry.isDirectory() && !addedFileSet.contains(entry.getName())
                        && !removedFileSet.contains(entry.getName()) && !CONTENT_FILE.equals(entry.getName())
                        && !PROPERTY_FILE.equals(entry.getName())) {
                    zout.putNextEntry(entry);
                    try (InputStream is = getFileAsInputStream(entry.getName())) { // When copying, always use an InputStream
                        IOUtils.copy(is, zout);
                    }
                    zout.closeEntry();
                } else if (entry.isDirectory()) {
                    zout.putNextEntry(entry);
                    zout.closeEntry();
                }
            }
        }
        try {
            if (zFile != null)
                zFile.close();
        } catch (IOException e) {
            // ignore close exception
        }
        zFile = null;
        saveTimer.stop("copyFiles");

        saveTimer.start("close");
        zout.close();
        saveTimer.stop("close");

        // Backup the original
        saveTimer.start("backup");
        File backupFile = new File(tmpDir.getAbsolutePath() + "/" + new GUID() + ".mv");
        if (file.exists()) {
            backupFile.delete(); // Always delete the old backup file first; renameTo() is very platform-dependent
            if (!file.renameTo(backupFile)) {
                FileUtil.copyFile(file, backupFile);
                file.delete();
            }
        }
        saveTimer.stop("backup");

        saveTimer.start("finalize");
        // Finalize
        if (!newFile.renameTo(file))
            FileUtil.copyFile(newFile, file);

        if (backupFile.exists())
            backupFile.delete();
        saveTimer.stop("finalize");

        dirty = false;
    } finally {
        saveTimer.start("cleanup");
        try {
            if (zFile != null)
                zFile.close();
        } catch (IOException e) {
            // ignore close exception
        }
        if (newFile.exists())
            newFile.delete();
        saveTimer.stop("cleanup");

        if (log.isDebugEnabled())
            log.debug(saveTimer);
        saveTimer = null;
    }
}

From source file:com.phonegap.plugin.files.ExtractZipFilePlugin.java

@Override
public boolean execute(String action, JSONArray args, CallbackContext cbc) {
    PluginResult.Status status = PluginResult.Status.OK;
    try {/*from  w  w  w  .j av a2  s  .c  o  m*/
        String filename = args.getString(0);
        URL url;
        try {
            url = new URL(filename);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
        File file = new File(url.getFile());
        String[] dirToSplit = url.getFile().split(File.separator);
        String dirToInsert = "";
        for (int i = 0; i < dirToSplit.length - 1; i++) {
            dirToInsert += dirToSplit[i] + File.separator;
        }

        ZipEntry entry;
        ZipFile zipfile;
        try {
            zipfile = new ZipFile(file);
            Enumeration e = zipfile.entries();
            while (e.hasMoreElements()) {
                entry = (ZipEntry) e.nextElement();
                BufferedInputStream is = null;
                try {
                    is = new BufferedInputStream(zipfile.getInputStream(entry));
                    int count;
                    byte data[] = new byte[102222];
                    String fileName = dirToInsert + entry.getName();
                    File outFile = new File(fileName);
                    if (entry.isDirectory()) {
                        if (!outFile.exists() && !outFile.mkdirs()) {
                            Log.v("info", "Unable to create directories: " + outFile.getAbsolutePath());
                            cbc.sendPluginResult(new PluginResult(IO_EXCEPTION));
                            return false;
                        }
                    } else {
                        File parent = outFile.getParentFile();
                        if (parent.mkdirs()) {
                            Log.v("info", "created directory leading to file");
                        }
                        FileOutputStream fos = null;
                        BufferedOutputStream dest = null;
                        try {
                            fos = new FileOutputStream(outFile);
                            dest = new BufferedOutputStream(fos, 102222);
                            while ((count = is.read(data, 0, 102222)) != -1) {
                                dest.write(data, 0, count);
                            }
                        } finally {
                            if (dest != null) {
                                dest.flush();
                                dest.close();
                            }
                            if (fos != null) {
                                fos.close();
                            }
                        }
                    }
                } finally {
                    if (is != null) {
                        is.close();
                    }
                }
            }
        } catch (ZipException e1) {
            Log.v("error", e1.getMessage(), e1);
            cbc.sendPluginResult(new PluginResult(MALFORMED_URL_EXCEPTION));
            return false;
        } catch (IOException e1) {
            Log.v("error", e1.getMessage(), e1);
            cbc.sendPluginResult(new PluginResult(IO_EXCEPTION));
            return false;
        }

    } catch (JSONException e) {
        cbc.sendPluginResult(new PluginResult(JSON_EXCEPTION));
        return false;
    }
    cbc.sendPluginResult(new PluginResult(status));
    return true;
}

From source file:com.jivesoftware.os.routing.bird.endpoints.base.LocateStringResource.java

String getStringResource() {
    Map<String, Long> htSizes = new HashMap<>();
    try {/*from   w w  w .j  av a 2  s  .  c  om*/
        try (final ZipFile zf = new ZipFile(jarFileName)) {
            Enumeration<? extends ZipEntry> e = zf.entries();
            while (e.hasMoreElements()) {
                ZipEntry ze = e.nextElement();
                if (!ze.getName().equals(resourceName)) {
                    continue;
                }
                htSizes.put(ze.getName(), ze.getSize());
            }
        }
        // extract resources and put them into the hashtable.
        FileInputStream fis = new FileInputStream(jarFileName);
        BufferedInputStream bis = new BufferedInputStream(fis);
        try (final ZipInputStream zis = new ZipInputStream(bis)) {
            ZipEntry ze;
            while ((ze = zis.getNextEntry()) != null) {
                if (!ze.getName().equals(resourceName)) {
                    continue;
                }
                if (ze.isDirectory()) {
                    continue;
                }
                int size = (int) ze.getSize();
                // -1 means unknown size.
                if (size == -1) {
                    size = htSizes.get(ze.getName()).intValue();
                }
                byte[] b = new byte[size];
                int rb = 0;
                int chunk = 0;
                while ((size - rb) > 0) {
                    chunk = zis.read(b, rb, size - rb);
                    if (chunk == -1) {
                        break;
                    }
                    rb += chunk;
                }
                InputStream inputStream = new ByteArrayInputStream(b);
                StringWriter writer = new StringWriter();
                IOUtils.copy(inputStream, writer, "UTF-8");
                return writer.toString();
            }
        }
    } catch (Exception e) {
        LOG.warn("Failed to locate " + resourceName, e);
    }
    return null;
}

From source file:com.moss.fskit.Unzipper.java

public void unzipFile(File zipFile, File destination, boolean unwrap) throws UnzipException {
    try {/*  w ww .j  a  va 2  s.  co m*/
        ZipInputStream in = new ZipInputStream(new FileInputStream(zipFile));
        boolean done = false;
        while (!done) {
            ZipEntry nextEntry = in.getNextEntry();

            if (nextEntry == null)
                done = true;
            else {
                String name = nextEntry.getName();
                if (unwrap) {
                    name = name.substring(name.indexOf('/'));
                }
                File outputFile = new File(destination, name);
                log.info("   " + outputFile.getAbsolutePath());

                if (!outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs())
                    throw new UnzipException("Could not create directory " + outputFile.getParent());

                if (nextEntry.isDirectory()) {
                    if (!outputFile.exists() && !outputFile.mkdir())
                        throw new UnzipException("Ddirectory does not exist and could not be created:"
                                + outputFile.getAbsolutePath());
                } else {
                    if (!outputFile.createNewFile())
                        throw new UnzipException("Could not create file " + outputFile.getAbsolutePath());
                    FileOutputStream out = new FileOutputStream(outputFile);
                    copyStreams(in, out, 1024 * 100);
                    out.close();
                    in.closeEntry();
                }

            }
        }

    } catch (Exception e) {
        throw new UnzipException("There was an error executing the unzip of file " + zipFile.getAbsolutePath(),
                e);
    }

    //      String pathOfZipFile = zipFile.getAbsolutePath();
    //      
    //      String command = "unzip -o "  + pathOfZipFile + " -d " + destination.getAbsolutePath() ;
    //      
    //      try {
    //         log.info("Running " + command);
    //         
    //         int result = new CommandRunner().runCommand(command);
    //         if(result!=0) throw new UnzipException("Unzip command exited with status " + result);
    //         log.info("Unzip complete");
    //      } catch (CommandException e) {
    //         throw new UnzipException("There was an error executing the unzip command: \"" + command + "\"", e);
    //      }
}

From source file:com.rover12421.shaka.apktool.lib.AndrolibAj.java

private void copyExistingFiles(ZipFile inputFile, ZipOutputStream outputFile, Map<String, String> excludeFiles)
        throws IOException {
    // First, copy the contents from the existing outFile:
    Enumeration<? extends ZipEntry> entries = inputFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = new ZipEntry(entries.nextElement());
        if (excludeFiles.get(entry.getName()) != null) {
            //??.
            continue;
        }/*from  w  ww .  j av  a 2 s.com*/
        // We can't reuse the compressed size because it depends on compression sizes.
        entry.setCompressedSize(-1);
        outputFile.putNextEntry(entry);

        // No need to create directory entries in the final apk
        if (!entry.isDirectory()) {
            BrutIO.copy(inputFile, outputFile, entry);
        }

        outputFile.closeEntry();
    }
}

From source file:com.netflix.ice.processor.BillingFileProcessor.java

private void processBillingZipFile(File file, boolean withTags) throws IOException {

    InputStream input = new FileInputStream(file);
    ZipInputStream zipInput;//w  ww . j  a v a 2s . c  o m

    zipInput = new ZipInputStream(input);

    try {
        ZipEntry entry;
        while ((entry = zipInput.getNextEntry()) != null) {
            if (entry.isDirectory())
                continue;

            processBillingFile(entry.getName(), zipInput, withTags);
        }
    } catch (IOException e) {
        if (e.getMessage().equals("Stream closed"))
            logger.info("reached end of file.");
        else
            logger.error("Error processing " + file, e);
    } finally {
        try {
            zipInput.close();
        } catch (IOException e) {
            logger.error("Error closing " + file, e);
        }
        try {
            input.close();
        } catch (IOException e1) {
            logger.error("Cannot close input for " + file, e1);
        }
    }
}

From source file:de.elomagic.maven.http.HTTPMojo.java

/**
 * @todo Must may be refactored. Only a prototype
 * @param file/*from  w w  w .ja va2 s. c o  m*/
 * @param destDirectory
 * @throws MojoExecutionException
 */
private void unzipToFile(final File file, final File destDirectory) throws Exception {
    getLog().info("Extracting downloaded file to folder \"" + destDirectory + "\".");

    int filesCount = 0;

    // create the destination directory structure (if needed)
    destDirectory.mkdirs();

    // open archive for reading
    try (ZipFile zipFile = new ZipFile(file, ZipFile.OPEN_READ)) {
        // For every zip archive entry do
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            ZipEntry entry = zipFileEntries.nextElement();
            getLog().debug("Extracting entry: " + entry);

            //create destination file
            // TODO Check entry path on path injections
            File destFile = new File(destDirectory, entry.getName());

            //create parent directories if needed
            File parentDestFile = destFile.getParentFile();
            parentDestFile.mkdirs();

            if (!entry.isDirectory()) {
                BufferedInputStream bufIS = new BufferedInputStream(zipFile.getInputStream(entry));

                // write the current file to disk
                Files.copy(bufIS, destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                filesCount++;
            }
        }
    }

    getLog().info(filesCount + " files extracted.");
}