Example usage for java.util.zip ZipInputStream closeEntry

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

Introduction

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

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for reading the next entry.

Usage

From source file:org.candlepin.sync.Importer.java

/**
 * Create a tar.gz archive of the exported directory.
 *
 * @param exportDir Directory where Candlepin data was exported.
 * @return File reference to the new archive tar.gz.
 *//*from  ww w .  j  a  v a 2  s  .  co  m*/
private File extractArchive(File tempDir, File exportFile) throws IOException, ImportExtractionException {
    log.debug("Extracting archive to: " + tempDir.getAbsolutePath());
    byte[] buf = new byte[1024];

    ZipInputStream zipinputstream = null;

    try {
        zipinputstream = new ZipInputStream(new FileInputStream(exportFile));
        ZipEntry zipentry = zipinputstream.getNextEntry();

        if (zipentry == null) {
            throw new ImportExtractionException(
                    i18n.tr("The archive {0} is not " + "a properly compressed file or is empty",
                            exportFile.getName()));
        }

        while (zipentry != null) {
            //for each entry to be extracted
            String entryName = zipentry.getName();
            if (log.isDebugEnabled()) {
                log.debug("entryname " + entryName);
            }
            File newFile = new File(entryName);
            String directory = newFile.getParent();
            if (directory != null) {
                new File(tempDir, directory).mkdirs();
            }

            FileOutputStream fileoutputstream = null;
            try {
                fileoutputstream = new FileOutputStream(new File(tempDir, entryName));
                int n;
                while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
                    fileoutputstream.write(buf, 0, n);
                }
            } finally {
                if (fileoutputstream != null) {
                    fileoutputstream.close();
                }
            }

            zipinputstream.closeEntry();
            zipentry = zipinputstream.getNextEntry();
        }
    } finally {
        if (zipinputstream != null) {
            zipinputstream.close();
        }
    }

    return new File(tempDir.getAbsolutePath(), "export");
}

From source file:org.pentaho.platform.plugin.services.importexport.CommandLineProcessor.java

/**
 * --import --url=http://localhost:8080/pentaho --username=admin --password=password --file-path=metadata.xmi
 * --resource-type=DATASOURCE --datasource-type=METADATA --overwrite=true --metadata-domain-id=steel-wheels
 * /*from  w  ww.j  a  v  a 2 s . c o m*/
 * @param contextURL
 * @param metadataDatasourceFile
 * @param overwrite
 * @throws ParseException
 * @throws IOException
 */
private void performMetadataDatasourceImport(String contextURL, File metadataDatasourceFile, String overwrite)
        throws ParseException, IOException {
    File metadataFileInZip = null;
    InputStream metadataFileInZipInputStream = null;

    String metadataImportURL = contextURL + METADATA_DATASOURCE_IMPORT;

    String domainId = getOptionValue(
            Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_METADATA_DOMAIN_ID_KEY"),
            Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_METADATA_DOMAIN_ID_NAME"), true,
            false);

    WebResource resource = client.resource(metadataImportURL);

    FormDataMultiPart part = new FormDataMultiPart();

    final String name = RepositoryFilenameUtils.separatorsToRepository(metadataDatasourceFile.getName());
    final String ext = RepositoryFilenameUtils.getExtension(name);

    try {
        if (ext.equals(ZIP_EXT)) {
            ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(metadataDatasourceFile));
            ZipEntry entry = zipInputStream.getNextEntry();
            while (entry != null) {
                final String entryName = RepositoryFilenameUtils.separatorsToRepository(entry.getName());
                final String extension = RepositoryFilenameUtils.getExtension(entryName);
                File tempFile = null;
                boolean isDir = entry.getSize() == 0;
                if (!isDir) {
                    tempFile = File.createTempFile("zip", null);
                    tempFile.deleteOnExit();
                    FileOutputStream fos = new FileOutputStream(tempFile);
                    IOUtils.copy(zipInputStream, fos);
                    fos.close();
                }
                if (extension.equals(METADATA_DATASOURCE_EXT)) {
                    if (metadataFileInZip == null) {
                        metadataFileInZip = new File(entryName);
                        metadataFileInZipInputStream = new FileInputStream(metadataFileInZip);
                    }
                }

                zipInputStream.closeEntry();
                entry = zipInputStream.getNextEntry();
            }
            zipInputStream.close();

            part.field("overwrite", "true".equals(overwrite) ? "true" : "false",
                    MediaType.MULTIPART_FORM_DATA_TYPE);
            part.field("domainId", domainId, MediaType.MULTIPART_FORM_DATA_TYPE).field("metadataFile",
                    metadataFileInZipInputStream, MediaType.MULTIPART_FORM_DATA_TYPE);

            // If the import service needs the file name do the following.
            part.getField("metadataFile").setContentDisposition(FormDataContentDisposition.name("metadataFile")
                    .fileName(metadataFileInZip.getName()).build());

            // Response response
            ClientResponse response = resource.type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class,
                    part);
            if (response != null) {
                String message = response.getEntity(String.class);
                System.out.println(Messages.getInstance()
                        .getString("CommandLineProcessor.INFO_REST_RESPONSE_RECEIVED", message));
            }

        } else {
            FileInputStream metadataDatasourceInputStream = new FileInputStream(metadataDatasourceFile);

            part.field("overwrite", "true".equals(overwrite) ? "true" : "false",
                    MediaType.MULTIPART_FORM_DATA_TYPE);
            part.field("domainId", domainId, MediaType.MULTIPART_FORM_DATA_TYPE).field("metadataFile",
                    metadataDatasourceInputStream, MediaType.MULTIPART_FORM_DATA_TYPE);

            // If the import service needs the file name do the following.
            part.getField("metadataFile").setContentDisposition(FormDataContentDisposition.name("metadataFile")
                    .fileName(metadataDatasourceFile.getName()).build());

            // Response response
            ClientResponse response = resource.type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class,
                    part);
            if (response != null) {
                String message = response.getEntity(String.class);
                System.out.println(Messages.getInstance()
                        .getString("CommandLineProcessor.INFO_REST_RESPONSE_RECEIVED", message));
            }
            metadataDatasourceInputStream.close();
        }
    } finally {
        metadataFileInZipInputStream.close();
        part.cleanup();
    }

}

From source file:com.thinkbiganalytics.feedmgr.service.template.ExportImportTemplateService.java

/**
 * Open the zip file and populate the {@link ImportTemplate} object with the components in the file/archive
 *
 * @param fileName    the file name/*from w  ww.j  a  v  a  2 s  . c  o m*/
 * @param inputStream the file
 * @return the template data to import
 */
private ImportTemplate openZip(String fileName, InputStream inputStream) throws IOException {
    byte[] buffer = new byte[1024];
    ZipInputStream zis = new ZipInputStream(inputStream);
    ZipEntry zipEntry;
    ImportTemplate importTemplate = new ImportTemplate(fileName);
    while ((zipEntry = zis.getNextEntry()) != null) {
        String zipEntryContents = ZipFileUtil.zipEntryToString(buffer, zis, zipEntry);
        if (zipEntry.getName().startsWith(NIFI_TEMPLATE_XML_FILE)) {
            importTemplate.setNifiTemplateXml(zipEntryContents);
        } else if (zipEntry.getName().startsWith(TEMPLATE_JSON_FILE)) {
            importTemplate.setTemplateJson(zipEntryContents);
        } else if (zipEntry.getName().startsWith(NIFI_CONNECTING_REUSABLE_TEMPLATE_XML_FILE)) {
            importTemplate.addNifiConnectingReusableTemplateXml(zipEntryContents);
        }
    }
    zis.closeEntry();
    zis.close();
    if (!importTemplate.hasValidComponents()) {
        throw new UnsupportedOperationException(
                " The file you uploaded is not a valid archive.  Please ensure the Zip file has been exported from the system and has 2 valid files named: "
                        + NIFI_TEMPLATE_XML_FILE + ", and " + TEMPLATE_JSON_FILE);
    }
    importTemplate.setZipFile(true);
    return importTemplate;

}

From source file:nl.coinsweb.sdk.FileManager.java

/**
 * Extracts all the content of the .ccr-file specified in the constructor to [TEMP_ZIP_PATH] / [internalRef].
 *
 *//*from   ww w  .  j  av a 2  s .  c  o  m*/
public static void unzipTo(File sourceFile, Path destinationPath) {

    byte[] buffer = new byte[1024];
    String startFolder = null;

    try {

        // Get the zip file content
        ZipInputStream zis = new ZipInputStream(new FileInputStream(sourceFile));
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {

            if (ze.isDirectory()) {
                ze = zis.getNextEntry();
                continue;
            }

            String fileName = ze.getName();

            log.info("Dealing with file " + fileName);

            // If the first folder is a somename/bim/file.ref skip it
            Path filePath = Paths.get(fileName);
            Path pathPath = filePath.getParent();

            if (pathPath.endsWith("bim") || pathPath.endsWith("bim/repository") || pathPath.endsWith("doc")
                    || pathPath.endsWith("woa")) {

                Path pathRoot = pathPath.endsWith("repository") ? pathPath.getParent().getParent()
                        : pathPath.getParent();

                String prefix = "";
                if (pathRoot != null) {
                    prefix = pathRoot.toString();
                }

                if (startFolder == null) {
                    startFolder = prefix;
                    log.debug("File root set to: " + startFolder);

                } else if (startFolder != null && !prefix.equals(startFolder)) {
                    throw new InvalidContainerFileException(
                            "The container file has an inconsistent file root, was " + startFolder
                                    + ", now dealing with " + prefix + ".");
                }
            } else {
                log.debug("Skipping file: " + filePath.toString());
                continue;
            }

            String insideStartFolder = filePath.toString().substring(startFolder.length());
            File newFile = new File(destinationPath + "/" + insideStartFolder);
            log.info("Extract " + newFile);

            // Create all non exists folders
            // else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();

            FileOutputStream fos = new FileOutputStream(newFile);

            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }

            fos.close();
            ze = zis.getNextEntry();
        }

        zis.closeEntry();
        zis.close();

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:org.infoscoop.service.GadgetResourceService.java

public void updateResources(String type, String moduleName, ZipInputStream zin) throws GadgetResourceException {
    gadgetDAO.deleteType(type);//from w  w w.j  a va 2 s  . co  m
    //gadgetIconDAO.deleteByType(type);

    boolean findModule = false;
    try {
        ZipEntry entry;
        while ((entry = getNextEntry(zin)) != null) {
            if (!entry.isDirectory()) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buf = new byte[5120];
                int reads = 0;
                while (!((reads = zin.read(buf)) < 0))
                    baos.write(buf, 0, reads);
                byte[] data = baos.toByteArray();

                String zipName = entry.getName();
                String path = "/" + zipName.substring(0, zipName.lastIndexOf("/") + 1);
                String name = zipName.substring(path.length() - 1);

                try {
                    if (path.length() > 1 && path.endsWith("/"))
                        path = path.substring(0, path.length() - 1);

                    if ("/".equals(path) && (moduleName + ".xml").equalsIgnoreCase(name)) {
                        findModule = true;
                        name = type + ".xml";

                        data = validateGadgetData(type, path, name, data);
                    }

                    insertResource(type, path, name, data);
                } catch (Exception ex) {
                    throw new GadgetResourceArchiveException(path, name,
                            "It is an entry of an invalid archive.  error at [" + path + "/" + name + "]"
                                    + ex.getMessage(),
                            "ams_gadgetResourceInvalidArchiveEntry", ex);
                }
            }

            zin.closeEntry();
        }
    } catch (GadgetResourceException ex) {
        throw ex;
    } catch (Exception ex) {
        log.error("", ex);

        throw new GadgetResourceException("It is an invalid archive.", "ams_gadgetResourceInvalidArchive");
    }

    if (!findModule)
        throw new GadgetResourceException(
                "Not found gadget module( /" + moduleName + ".xml" + " ) in an uploaded archive.",
                "ams_gadgetResourceNotFoundGadgetModule");
}

From source file:ninja.command.PackageCommand.java

public void unzip(File zipFile, File outputFolder) {

    byte[] buffer = new byte[1024];

    try {//from ww  w .  j av  a 2s. c  om

        // create output directory is not exists
        File folder = outputFolder;
        if (!folder.exists()) {
            folder.mkdir();
        }

        // get the zip file content
        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        // get the zipped file list entry
        ZipEntry ze = zis.getNextEntry();
        String zipFilename = zipFile.getName();
        while (ze != null) {
            if (ze.isDirectory()) {
                ze = zis.getNextEntry();
                continue;
            }
            String fileName = ze.getName();
            File newFile = new File(outputFolder, fileName);

            String parentFolder = newFile.getParentFile().getName();
            // (!"META-INF".equals(parentFolder))
            if (newFile.exists() && !"about.html".equals(fileName) && !"META-INF/DEPENDENCIES".equals(fileName)
                    && !"META-INF/LICENSE".equals(fileName) && !"META-INF/NOTICE".equals(fileName)
                    && !"META-INF/NOTICE.txt".equals(fileName) && !"META-INF/MANIFEST.MF".equals(fileName)
                    && !"META-INF/LICENSE.txt".equals(fileName) && !"META-INF/INDEX.LIST".equals(fileName)) {
                String conflicted = zipManifest.get(newFile.getAbsolutePath());
                if (conflicted == null)
                    conflicted = "unknown";
                info(String.format("Conflicts for '%s' with '%s'. File alreay exists '%s", zipFilename,
                        conflicted, newFile));
                conflicts++;
            } else
                zipManifest.put(newFile.getAbsolutePath(), zipFile.getName());
            // create all non exists folders
            // else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();

            FileOutputStream fos = new FileOutputStream(newFile);

            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }

            fos.close();
            ze = zis.getNextEntry();
            count++;
        }

        zis.closeEntry();
        zis.close();

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.gatf.generator.core.GatfTestGeneratorMojo.java

/**
 * @param zipFile//from  www . j a  va2s  .  c o  m
 * @param directoryToExtractTo Provides file unzip functionality
 */
public void unzipZipFile(InputStream zipFile, String directoryToExtractTo) {
    ZipInputStream in = new ZipInputStream(zipFile);
    try {
        File directory = new File(directoryToExtractTo);
        if (!directory.exists()) {
            directory.mkdirs();
            getLog().info("Creating directory for Extraction...");
        }
        ZipEntry entry = in.getNextEntry();
        while (entry != null) {
            try {
                File file = new File(directory, entry.getName());
                if (entry.isDirectory()) {
                    file.mkdirs();
                } else {
                    FileOutputStream out = new FileOutputStream(file);
                    byte[] buffer = new byte[2048];
                    int len;
                    while ((len = in.read(buffer)) > 0) {
                        out.write(buffer, 0, len);
                    }
                    out.close();
                }
                in.closeEntry();
                entry = in.getNextEntry();
            } catch (Exception e) {
                getLog().error(e);
            }
        }
    } catch (IOException ioe) {
        getLog().error(ioe);
        return;
    }
}

From source file:org.openmrs.module.dhisconnector.api.impl.DHISConnectorServiceImpl.java

private void unZipDHIS2APIBackupToTemp(String zipFile) {
    byte[] buffer = new byte[1024];
    String outputFolder = OpenmrsUtil.getApplicationDataDirectory() + DHISCONNECTOR_TEMP_FOLDER;

    try {// w w  w. j a v a  2s  .c o m
        File destDir = new File(outputFolder);
        if (!destDir.exists()) {
            destDir.mkdir();
        }
        ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry entry = zipIn.getNextEntry();

        while (entry != null) {
            String filePath = outputFolder + File.separator + entry.getName();
            if (!entry.isDirectory()) {
                if (!(new File(filePath)).getParentFile().exists()) {
                    (new File(filePath)).getParentFile().mkdirs();
                }
                (new File(filePath)).createNewFile();
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
                byte[] bytesIn = buffer;
                int read = 0;
                while ((read = zipIn.read(bytesIn)) != -1) {
                    bos.write(bytesIn, 0, read);
                }
                bos.close();
            } else {
                // if the entry is a directory, make the directory
                File dir = new File(filePath);
                dir.mkdir();
            }
            zipIn.closeEntry();
            entry = zipIn.getNextEntry();
        }
        zipIn.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.griddynamics.deming.ecommerce.api.endpoint.catalog.CatalogManagerEndpoint.java

@POST
@Path("import")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response importCatalog(@FormDataParam("file") InputStream uploadInputStream)
        throws ServiceException, IOException {
    removeCatalog();//from ww  w  .  j  av a2 s  . co m

    try {
        ZipInputStream inputStream = new ZipInputStream(uploadInputStream);

        try {
            byte[] buf = new byte[1024];

            for (ZipEntry entry = inputStream.getNextEntry(); entry != null; entry = inputStream
                    .getNextEntry()) {
                try {
                    String entryName = entry.getName();
                    entryName = entryName.replace('/', File.separatorChar);
                    entryName = entryName.replace('\\', File.separatorChar);

                    LOGGER.debug("Entry name: {}", entryName);

                    if (entry.isDirectory()) {
                        LOGGER.debug("Entry ({}) is directory", entryName);
                    } else if (PRODUCT_CATALOG_FILE.equals(entryName)) {
                        ByteArrayOutputStream jsonBytes = new ByteArrayOutputStream(1024);

                        for (int n = inputStream.read(buf, 0, 1024); n > -1; n = inputStream.read(buf, 0,
                                1024)) {
                            jsonBytes.write(buf, 0, n);
                        }

                        byte[] bytes = jsonBytes.toByteArray();

                        ObjectMapper mapper = new ObjectMapper();

                        JaxbAnnotationModule jaxbAnnotationModule = new JaxbAnnotationModule();
                        mapper.registerModule(jaxbAnnotationModule);

                        ImportCategoryWrapper catalog = mapper.readValue(bytes, ImportCategoryWrapper.class);
                        escape(catalog);
                        saveCategoryTree(catalog);
                    } else {
                        MultipartFile file = new MultipartFileAdapter(inputStream, entryName);
                        dmgStaticAssetStorageService.createStaticAssetStorageFromFile(file);
                    }

                } finally {
                    inputStream.closeEntry();
                }
            }
        } finally {
            inputStream.close();
        }

    } catch (IOException e) {
        return Response.status(Response.Status.BAD_REQUEST).entity("Unable load catalog.\n").build();
    }

    Thread rebuildSearchIndex = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(10000);
                searchService.rebuildIndex();
            } catch (Exception e) {
                /* nothing */}
        }
    });
    rebuildSearchIndex.start();

    return Response.status(Response.Status.OK).entity("Catalog was imported successfully!\n").build();
}

From source file:nl.nn.adapterframework.webcontrol.pipes.UploadConfig.java

private String processZipFile(IPipeLineSession session, String fileName) throws PipeRunException, IOException {
    String result = "";
    Object form_file = session.get("file");
    if (form_file != null) {
        if (form_file instanceof InputStream) {
            InputStream inputStream = (InputStream) form_file;
            String form_fileEncoding = (String) session.get("fileEncoding");
            if (inputStream.available() > 0) {
                /*/*ww w.  j av a  2s.  co  m*/
                 * String fileEncoding; if
                 * (StringUtils.isNotEmpty(form_fileEncoding)) {
                 * fileEncoding = form_fileEncoding; } else { fileEncoding =
                 * Misc.DEFAULT_INPUT_STREAM_ENCODING; }
                 */ZipInputStream archive = new ZipInputStream(inputStream);
                int counter = 1;
                for (ZipEntry entry = archive.getNextEntry(); entry != null; entry = archive.getNextEntry()) {
                    String entryName = entry.getName();
                    int size = (int) entry.getSize();
                    if (size > 0) {
                        byte[] b = new byte[size];
                        int rb = 0;
                        int chunk = 0;
                        while (((int) size - rb) > 0) {
                            chunk = archive.read(b, rb, (int) size - rb);
                            if (chunk == -1) {
                                break;
                            }
                            rb += chunk;
                        }
                        ByteArrayInputStream bais = new ByteArrayInputStream(b, 0, rb);
                        String fileNameSessionKey = "file_zipentry" + counter;
                        session.put(fileNameSessionKey, bais);
                        if (StringUtils.isNotEmpty(result)) {
                            result += "\n";
                        }
                        String name = "";
                        String version = "";
                        String[] fnArray = splitFilename(entryName);
                        if (fnArray[0] != null) {
                            name = fnArray[0];
                        }
                        if (fnArray[1] != null) {
                            version = fnArray[1];
                        }
                        result += entryName + ":"
                                + processJarFile(session, name, version, entryName, fileNameSessionKey);
                        session.remove(fileNameSessionKey);
                    }
                    archive.closeEntry();
                    counter++;
                }
                archive.close();
            }
        }
    }
    return result;
}