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:nl.knaw.dans.common.lang.file.UnzipUtil.java

private static List<File> extract(final ZipInputStream zipInputStream, String destPath,
        final int initialCapacityForFiles, final UnzipListener unzipListener, final long totSize)
        throws FileNotFoundException, IOException {
    if (unzipListener != null)
        unzipListener.onUnzipStarted(totSize);

    final File destPathFile = new File(destPath);
    if (!destPathFile.exists())
        throw new FileNotFoundException(destPath);
    if (!destPathFile.isDirectory())
        throw new IOException("Expected directory, got file.");
    if (!destPath.endsWith(File.separator))
        destPath += File.separator;

    // now unzip//from  w  w w  .  j av  a2 s.c om
    BufferedOutputStream out = null;
    ZipEntry entry;
    int count;
    final byte data[] = new byte[BUFFER_SIZE];
    final ArrayList<File> files = new ArrayList<File>(initialCapacityForFiles);
    String entryname;
    String filename;
    String path;
    boolean cancel = false;
    final DefaultUnzipFilenameFilter filter = new DefaultUnzipFilenameFilter();

    try {
        long bytesWritten = 0;
        while (((entry = zipInputStream.getNextEntry()) != null) && !cancel) {
            entryname = entry.getName();
            final int fpos = entryname.lastIndexOf(File.separator);
            if (fpos >= 0) {
                path = entryname.substring(0, fpos);
                filename = entryname.substring(fpos + 1);
            } else {
                path = "";
                filename = new String(entryname);
            }

            if (!filter.accept(destPathFile, filename)) {
                // file filtered out
                continue;
            }

            if (entry.isDirectory()) {
                if (!createPath(destPath, entryname, files, filter))
                    // directory filtered out
                    continue;
            } else {
                if (!StringUtils.isBlank(path)) {
                    if (!createPath(destPath, path, files, filter))
                        // path filtered out
                        continue;
                }

                final String absFilename = destPath + entryname;
                final FileOutputStream fos = new FileOutputStream(absFilename);
                out = new BufferedOutputStream(fos, BUFFER_SIZE);
                try {
                    // inner loop
                    while ((count = zipInputStream.read(data, 0, BUFFER_SIZE)) != -1) {
                        out.write(data, 0, count);
                        bytesWritten += count;

                        if (unzipListener != null)
                            cancel = !unzipListener.onUnzipUpdate(bytesWritten, totSize);
                        if (cancel)
                            break;
                    }
                    out.flush();
                } finally {
                    out.close();
                    files.add(new File(absFilename));
                }
            }
        }
    } finally {
        zipInputStream.close();

        // rollback?
        if (cancel) {
            // first remove files
            for (final File file : files) {
                if (!file.isDirectory())
                    file.delete();
            }
            // then folders
            for (final File file : files) {
                if (file.isDirectory())
                    file.delete();
            }
            files.clear();
        }
    }

    if (unzipListener != null)
        unzipListener.onUnzipComplete(files, cancel);

    return files;
}

From source file:com.googlecode.android_scripting.ZipExtractorTask.java

private long unzip() throws Exception {
    long extractedSize = 0l;
    Enumeration<? extends ZipEntry> entries;
    if (mInput.isFile() && mInput.getName().contains(".gz")) {
        InputStream stream = new FileInputStream(mInput);
        GZIPInputStream gzipStream = new GZIPInputStream(stream);
        InputSource is = new InputSource(gzipStream);
        InputStream input = new BufferedInputStream(is.getByteStream());
        File destination = new File(mOutput, "php");
        ByteArrayBuffer baf = new ByteArrayBuffer(255000);
        int current = 0;
        while ((current = input.read()) != -1) {
            baf.append((byte) current);
        }/*from ww w .  java2 s .c o  m*/

        FileOutputStream output = new FileOutputStream(destination);
        output.write(baf.toByteArray());
        output.close();
        Log.d("written!");
        return baf.toByteArray().length;
    }
    ZipFile zip = new ZipFile(mInput);
    long uncompressedSize = getOriginalSize(zip);

    publishProgress(0, (int) uncompressedSize);

    entries = zip.entries();

    try {
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                // Not all zip files actually include separate directory entries.
                // We'll just ignore them
                // and create them as necessary for each actual entry.
                continue;
            }
            File destination = new File(mOutput, entry.getName());
            if (!destination.getParentFile().exists()) {
                destination.getParentFile().mkdirs();
            }
            if (destination.exists() && mContext != null && !mReplaceAll) {
                Replace answer = showDialog(entry.getName());
                switch (answer) {
                case YES:
                    break;
                case NO:
                    continue;
                case YESTOALL:
                    mReplaceAll = true;
                    break;
                default:
                    return extractedSize;
                }
            }
            ProgressReportingOutputStream outStream = new ProgressReportingOutputStream(destination);
            extractedSize += IoUtils.copy(zip.getInputStream(entry), outStream);
            outStream.close();
        }
    } finally {
        try {
            zip.close();
        } catch (Exception e) {
            // swallow this exception, we are only interested in the original one
        }
    }
    Log.v("Extraction is complete.");
    return extractedSize;
}

From source file:io.sledge.core.impl.extractor.SledgeApplicationPackageExtractor.java

@Override
public DeploymentConfiguration getDeploymentConfiguration(InputStream appPackageInputStream) {
    DeploymentConfiguration deploymentConfig = null;
    ZipInputStream zipStream = new ZipInputStream(new BufferedInputStream(appPackageInputStream),
            Charset.forName("UTF-8"));

    try {/*w w w  . ja v  a2  s  .  c o m*/
        byte[] buffer = new byte[2048];
        ZipEntry zipEntry = null;

        while ((zipEntry = zipStream.getNextEntry()) != null) {

            if (zipEntry.isDirectory()) {
                zipStream.closeEntry();
                continue;
            }

            if (zipEntry.getName().startsWith(SLEDGEFILE_XML)) {
                ByteArrayOutputStream output = new ByteArrayOutputStream();

                int length;
                while ((length = zipStream.read(buffer, 0, buffer.length)) >= 0) {
                    output.write(buffer, 0, length);
                }

                DeploymentConfigurationReader deploymentConfigReader = new DeploymentConfigurationReaderXml();
                deploymentConfig = deploymentConfigReader
                        .parseDeploymentConfiguration(new ByteArrayInputStream(output.toByteArray()));

                zipStream.closeEntry();

                // Stop here, the file is read
                break;
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        try {
            zipStream.close();
            appPackageInputStream.reset();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    return deploymentConfig;
}

From source file:com.skcraft.launcher.launch.JavaRuntimeFetcher.java

private void extract(File zip, File destination) {
    if (!zip.exists()) {
        throw new UnsupportedOperationException("Attempted to extract non-existent file: " + zip);
    }/* w w w.  ja  va  2s. c o m*/

    if (destination.mkdirs()) {
        log.log(Level.INFO, "Creating dir: {0}", destination);
    }

    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(zip);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (!entry.isDirectory()) {
                InputStream inputStream = zipFile.getInputStream(entry);
                File file = new File(destination, entry.getName());
                copyFile(inputStream, file, SharedLocale.tr("runtimeFetcher.extract", file.getName()), -1);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        Closer.close(zipFile);
    }
}

From source file:gobblin.aws.AWSJobConfigurationManager.java

/***
 * Unzip a zip archive/*  w  ww. ja va 2  s . co m*/
 * @param file Zip file to unarchive
 * @param outputDir Output directory for the unarchived file
 * @throws IOException If any issue occurs in unzipping the file
 */
public void unzipArchive(String file, File outputDir) throws IOException {

    try (ZipFile zipFile = new ZipFile(file)) {

        final Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            final File entryDestination = new File(outputDir, entry.getName());

            if (entry.isDirectory()) {
                // If entry is directory, create directory
                if (!entryDestination.mkdirs() && !entryDestination.exists()) {
                    throw new IOException("Could not create directory: " + entryDestination
                            + " while un-archiving zip: " + file);
                }
            } else {
                // Create parent dirs if required
                if (!entryDestination.getParentFile().mkdirs() && !entryDestination.getParentFile().exists()) {
                    throw new IOException("Could not create parent directory for: " + entryDestination
                            + " while un-archiving zip: " + file);
                }

                // Extract and save the conf file
                InputStream in = null;
                OutputStream out = null;
                try {
                    in = zipFile.getInputStream(entry);
                    out = new FileOutputStream(entryDestination);
                    IOUtils.copy(in, out);
                } finally {
                    if (null != in)
                        IOUtils.closeQuietly(in);
                    if (null != out)
                        IOUtils.closeQuietly(out);
                }
            }
        }
    }
}

From source file:aurelienribon.gdxsetupui.ProjectUpdate.java

/**
 * Selected libraries are inflated from their zip files, and put in the
 * correct folders of the projects./* w  ww .j  av  a  2  s. co m*/
 * @throws IOException
 */
public void inflateLibraries() throws IOException {
    File commonPrjLibsDir = new File(Helper.getCorePrjPath(cfg) + "libs");
    File desktopPrjLibsDir = new File(Helper.getDesktopPrjPath(cfg) + "libs");
    File androidPrjLibsDir = new File(Helper.getAndroidPrjPath(cfg) + "libs");
    File htmlPrjLibsDir = new File(Helper.getHtmlPrjPath(cfg) + "war/WEB-INF/lib");
    File iosPrjLibsDir = new File(Helper.getIosPrjPath(cfg) + "libs");
    File dataDir = new File(Helper.getAndroidPrjPath(cfg) + "assets");

    for (String library : cfg.libraries) {
        InputStream is = new FileInputStream(cfg.librariesZipPaths.get(library));
        ZipInputStream zis = new ZipInputStream(is);
        ZipEntry entry;

        LibraryDef def = libs.getDef(library);

        while ((entry = zis.getNextEntry()) != null) {
            if (entry.isDirectory())
                continue;
            String entryName = entry.getName();

            for (String elemName : def.libsCommon)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, commonPrjLibsDir);

            if (cfg.isDesktopIncluded) {
                for (String elemName : def.libsDesktop)
                    if (entryName.endsWith(elemName))
                        copyEntry(zis, elemName, desktopPrjLibsDir);
            }

            if (cfg.isAndroidIncluded) {
                for (String elemName : def.libsAndroid)
                    if (entryName.endsWith(elemName))
                        copyEntry(zis, elemName, androidPrjLibsDir);
                for (String elemName : def.data)
                    if (entryName.endsWith(elemName))
                        copyEntry(zis, elemName, dataDir);
            }

            if (cfg.isHtmlIncluded) {
                for (String elemName : def.libsHtml)
                    if (entryName.endsWith(elemName))
                        copyEntry(zis, elemName, htmlPrjLibsDir);
            }

            if (cfg.isIosIncluded) {
                for (String elemName : def.libsIos)
                    if (entryName.endsWith(elemName))
                        copyEntry(zis, elemName, iosPrjLibsDir);
            }
        }

        zis.close();
    }
}

From source file:io.apicurio.hub.api.codegen.OpenApi2ThorntailTest.java

/**
 * Test method for {@link io.apicurio.hub.api.codegen.OpenApi2Thorntail#generate()}.
 *///from ww w. ja  va  2 s .com
@Test
public void testGenerateOnly() throws IOException {
    OpenApi2Thorntail generator = new OpenApi2Thorntail() {
        /**
         * @see io.apicurio.hub.api.codegen.OpenApi2Thorntail#processApiDoc()
         */
        @Override
        protected String processApiDoc() {
            try {
                return IOUtils.toString(OpenApi2ThorntailTest.class.getClassLoader()
                        .getResource("OpenApi2ThorntailTest/beer-api.codegen.json"));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    };
    generator.setUpdateOnly(false);
    generator
            .setOpenApiDocument(getClass().getClassLoader().getResource("OpenApi2ThorntailTest/beer-api.json"));
    ByteArrayOutputStream outputStream = generator.generate();

    //FileUtils.writeByteArrayToFile(new File("C:\\Users\\ewittman\\tmp\\output.zip"), outputStream.toByteArray());

    // Validate the result
    try (ZipInputStream zipInputStream = new ZipInputStream(
            new ByteArrayInputStream(outputStream.toByteArray()))) {
        ZipEntry zipEntry = zipInputStream.getNextEntry();
        while (zipEntry != null) {
            if (!zipEntry.isDirectory()) {
                String name = zipEntry.getName();
                //                    System.out.println(name);
                Assert.assertNotNull(name);

                URL expectedFile = getClass().getClassLoader()
                        .getResource(getClass().getSimpleName() + "/_expected/generated-api/" + name);
                Assert.assertNotNull("Could not find expected file for entry: " + name, expectedFile);
                String expected = IOUtils.toString(expectedFile);

                String actual = IOUtils.toString(zipInputStream);
                //                    System.out.println("-----");
                //                    System.out.println(actual);
                //                    System.out.println("-----");
                Assert.assertEquals("Expected vs. actual failed for entry: " + name, normalizeString(expected),
                        normalizeString(actual));
            }
            zipEntry = zipInputStream.getNextEntry();
        }
    }

}

From source file:com.seer.datacruncher.services.ftp.FTPPollJobProcessor.java

@Override
public void process(Exchange exchange) throws Exception {
    String result = "";
    GenericFile file = (GenericFile) exchange.getIn().getBody();
    Message message = exchange.getOut();
    String inputFileName = file.getFileName();
    Map<String, byte[]> resultMap = new HashMap<String, byte[]>();
    if (isValidFileName(inputFileName)) {
        long schemaId = getSchemaIdUsingFileName(inputFileName);
        long userId = getUserIdFromFileName(inputFileName);
        if (!usersDao.isUserAssoicatedWithSchema(userId, schemaId)) {
            result = "User not authorized";
        } else {//  www .  j  a  v a 2s.c  o m
            resultMap.put(inputFileName, file.getBody().toString().getBytes());
            SchemaEntity schemaEntity = schemasDao.find(schemaId);
            if (schemaEntity == null) {
                result = "No schema found in database with Id [" + schemaId + "]";
            } else {
                if (inputFileName.endsWith(FileExtensionType.ZIP.getAbbreviation())) {
                    // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one   
                    ZipInputStream inStream = null;
                    try {
                        inStream = new ZipInputStream(new ByteArrayInputStream(resultMap.get(inputFileName)));
                        ZipEntry entry;
                        while (!(isStreamClose(inStream)) && (entry = inStream.getNextEntry()) != null) {
                            if (!entry.isDirectory()) {
                                DatastreamsInput datastreamsInput = new DatastreamsInput();
                                datastreamsInput.setUploadedFileName(entry.getName());
                                byte[] byteInput = IOUtils.toByteArray(inStream);
                                result += datastreamsInput.datastreamsInput(new String(byteInput), schemaId,
                                        byteInput);
                            }
                            inStream.closeEntry();
                        }
                    } catch (IOException ex) {
                        result = "Error occured during fetch records from ZIP file.";
                    } finally {
                        if (inStream != null)
                            inStream.close();
                    }
                } else {
                    DatastreamsInput datastreamsInput = new DatastreamsInput();
                    datastreamsInput.setUploadedFileName(inputFileName);
                    result = datastreamsInput.datastreamsInput(new String(resultMap.get(inputFileName)),
                            schemaId, resultMap.get(inputFileName));
                }
            }
        }
    } else {
        result = "File Name not in specified format.";
    }

    // Store in Ftp location
    CamelContext context = exchange.getContext();
    FtpComponent component = context.getComponent("ftp", FtpComponent.class);
    FtpEndpoint<?> endpoint = (FtpEndpoint<?>) component.createEndpoint(getFTPEndPoint());

    Exchange outExchange = endpoint.createExchange();
    outExchange.getIn().setBody(result);
    outExchange.getIn().setHeader("CamelFileName", getFileNameWithoutExtensions(inputFileName) + ".txt");
    Producer producer = endpoint.createProducer();
    producer.start();
    producer.process(outExchange);
    producer.stop();
}

From source file:io.apicurio.hub.api.codegen.OpenApi2ThorntailTest.java

/**
 * Test method for {@link io.apicurio.hub.api.codegen.OpenApi2Thorntail#generate()}.
 *//*from  w  w  w. j  a  v  a 2 s.c  o  m*/
@Test
public void testGenerateOnly_GatewayApiNoTypes() throws IOException {
    OpenApi2Thorntail generator = new OpenApi2Thorntail() {
        /**
         * @see io.apicurio.hub.api.codegen.OpenApi2Thorntail#processApiDoc()
         */
        @Override
        protected String processApiDoc() {
            try {
                return IOUtils.toString(OpenApi2ThorntailTest.class.getClassLoader()
                        .getResource("OpenApi2ThorntailTest/gateway-api-notypes.codegen.json"));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    };
    generator.setUpdateOnly(false);
    generator.setSettings(new ThorntailProjectSettings("io.openapi.simple", "simple-api", "io.openapi.simple"));
    generator.setOpenApiDocument(
            getClass().getClassLoader().getResource("OpenApi2ThorntailTest/gateway-api.json"));
    ByteArrayOutputStream outputStream = generator.generate();

    //        FileUtils.writeByteArrayToFile(new File("C:\\Users\\ewittman\\tmp\\output.zip"), outputStream.toByteArray());

    // Validate the result
    try (ZipInputStream zipInputStream = new ZipInputStream(
            new ByteArrayInputStream(outputStream.toByteArray()))) {
        ZipEntry zipEntry = zipInputStream.getNextEntry();
        while (zipEntry != null) {
            if (!zipEntry.isDirectory()) {
                String name = zipEntry.getName();
                //                    System.out.println(name);
                Assert.assertNotNull(name);

                URL expectedFile = getClass().getClassLoader().getResource(
                        getClass().getSimpleName() + "/_expected-gatewayApiNoTypes/simple-api/" + name);
                Assert.assertNotNull("Could not find expected file for entry: " + name, expectedFile);
                String expected = IOUtils.toString(expectedFile);

                String actual = IOUtils.toString(zipInputStream);
                //                    System.out.println("-----");
                //                    System.out.println(actual);
                //                    System.out.println("-----");
                Assert.assertEquals("Expected vs. actual failed for entry: " + name, normalizeString(expected),
                        normalizeString(actual));
            }
            zipEntry = zipInputStream.getNextEntry();
        }
    }

}

From source file:com.cloudant.sync.datastore.DatastoreSchemaTests.java

@SuppressWarnings("ResultOfMethodCallIgnored") // mkdirs result should be fine
private boolean unzipToDirectory(File zipPath, File outputDirectory) {
    try {// w  w w  .  java  2  s  .  c  o  m

        ZipFile zipFile = new ZipFile(zipPath);
        try {
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                File entryDestination = new File(outputDirectory, entry.getName());
                if (entry.isDirectory())
                    entryDestination.mkdirs();
                else {
                    entryDestination.getParentFile().mkdirs();
                    InputStream in = zipFile.getInputStream(entry);
                    OutputStream out = new FileOutputStream(entryDestination);
                    IOUtils.copy(in, out);
                    IOUtils.closeQuietly(in);
                    out.close();
                }
            }
        } finally {
            zipFile.close();
        }

        return true;

    } catch (Exception ex) {
        return false;
    }
}