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.geoserver.kml.KMLTest.java

@Test
public void testKMZMixed() throws Exception {
    // force vector layers to be vector dumps (kmscore 100)
    MockHttpServletResponse response = getAsServletResponse("wms?request=getmap&service=wms&version=1.1.1"
            + "&format=" + KMZMapOutputFormat.MIME_TYPE + "&layers=" + getLayerId(MockData.BASIC_POLYGONS) + ","
            + getLayerId(MockData.WORLD) + "&styles=" + MockData.BASIC_POLYGONS.getLocalPart() + ","
            + "&height=1024&width=1024&bbox=-180,-90,180,90&srs=EPSG:4326&format_options=kmscore:100");

    // check the contents of the zip file
    assertEquals(KMZMapOutputFormat.MIME_TYPE, response.getContentType());
    ByteArrayInputStream bis = getBinaryInputStream(response);
    ZipInputStream zis = new ZipInputStream(bis);

    // first entry, the kml document itself
    ZipEntry entry = zis.getNextEntry();
    assertEquals("wms.kml", entry.getName());
    // we need to clone the input stream, as dom(is) closes the stream
    byte[] data = IOUtils.toByteArray(zis);
    Document dom = dom(new ByteArrayInputStream(data));
    // print(dom);
    // we have the placemarks in the first folder (vector), and no ground overlays
    assertXpathEvaluatesTo("3", "count(//kml:Folder[1]/kml:Placemark)", dom);
    assertXpathEvaluatesTo("0", "count(//kml:Folder[1]/kml:GroundOverlay)", dom);
    // we have only the ground overlay in the second folder
    assertXpathEvaluatesTo("0", "count(//kml:Folder[2]/kml:Placemark)", dom);
    assertXpathEvaluatesTo("1", "count(//kml:Folder[2]/kml:GroundOverlay)", dom);
    assertXpathEvaluatesTo("images/layers_1.png", "//kml:Folder[2]/kml:GroundOverlay/kml:Icon/kml:href", dom);
    zis.closeEntry();

    // the images folder
    entry = zis.getNextEntry();//from www.j  av a 2 s.  c  o  m
    assertEquals("images/", entry.getName());
    zis.closeEntry();

    // the ground overlay for the raster layer
    entry = zis.getNextEntry();
    assertEquals("images/layers_1.png", entry.getName());
    zis.closeEntry();
    assertNull(zis.getNextEntry());
}

From source file:com.sastix.cms.server.services.content.impl.ZipFileHandlerServiceImpl.java

@Override
public DataMaps unzip(byte[] bytes) throws IOException {
    Map<String, String> foldersMap = new HashMap<>();

    Map<String, byte[]> extractedBytesMap = new HashMap<>();
    InputStream byteInputStream = new ByteArrayInputStream(bytes);
    //validate that it is a zip file
    if (isZipFile(bytes)) {
        try {//from   ww w . java 2s  .  co  m
            //get the zip file content
            ZipInputStream zis = new ZipInputStream(byteInputStream);
            //get the zipped file list entry
            ZipEntry ze = zis.getNextEntry();

            while (ze != null) {
                String fileName = ze.getName();
                if (!ze.isDirectory()) {//if entry is a directory, we should not add it as a file
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    try {
                        ByteBuffer bufIn = ByteBuffer.allocate(1024);
                        int bytesRead;
                        while ((bytesRead = zis.read(bufIn.array())) > 0) {
                            baos.write(bufIn.array(), 0, bytesRead);
                            bufIn.rewind();
                        }
                        bufIn.clear();
                        extractedBytesMap.put(fileName, baos.toByteArray());
                    } finally {
                        baos.close();
                    }
                } else {
                    foldersMap.put(fileName, fileName);
                }
                ze = zis.getNextEntry();
            }
            zis.closeEntry();
            zis.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    DataMaps dataMaps = new DataMaps();
    dataMaps.setBytesMap(extractedBytesMap);
    dataMaps.setFoldersMap(foldersMap);
    return dataMaps;
}

From source file:dpfmanager.shell.modules.report.core.ReportGenerator.java

/**
 * Read the file of the path./*from w w w .  j  a  v  a2  s . com*/
 *
 * @param pathStr the file path to read.
 * @return the content of the file in path
 */
public String readFile(String pathStr) {
    String text = "";
    String name = pathStr.substring(pathStr.lastIndexOf("/") + 1, pathStr.length());
    Path path = Paths.get(pathStr);
    try {
        if (Files.exists(path)) {
            // Look in current dir
            BufferedReader br = new BufferedReader(new FileReader(pathStr));
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                line = br.readLine();
            }
            text = sb.toString();
            br.close();
        } else {
            // Look in JAR
            CodeSource src = ReportGenerator.class.getProtectionDomain().getCodeSource();
            if (src != null) {
                URL jar = src.getLocation();
                ZipInputStream zip;

                zip = new ZipInputStream(jar.openStream());
                ZipEntry zipFile;
                boolean found = false;
                while ((zipFile = zip.getNextEntry()) != null && !found) {
                    if (zipFile.getName().endsWith(name)) {
                        BufferedReader br = new BufferedReader(new InputStreamReader(zip));
                        String line = br.readLine();
                        while (line != null) {
                            text += line + System.lineSeparator();
                            line = br.readLine();
                        }
                        found = true;
                    }
                    zip.closeEntry();
                }
            }
        }
    } catch (FileNotFoundException e) {
        context.send(BasicConfig.MODULE_MESSAGE,
                new LogMessage(getClass(), Level.ERROR, "Template for html not found in dir."));
    } catch (IOException e) {
        context.send(BasicConfig.MODULE_MESSAGE,
                new LogMessage(getClass(), Level.ERROR, "Error reading " + pathStr));
    }

    return text;
}

From source file:edu.harvard.mcz.dwcaextractor.DwCaExtractor.java

/**
 * Setup conditions to run./*  w ww . jav a  2  s. c  om*/
 * 
 * @param args command line arguments
 * @return true if setup was successful, false otherwise.
 */
protected boolean setup(String[] args) {
    boolean setupOK = false;
    CmdLineParser parser = new CmdLineParser(this);
    //parser.setUsageWidth(4096);
    try {
        parser.parseArgument(args);

        if (help) {
            parser.printUsage(System.out);
            System.exit(0);
        }

        if (archiveFilePath != null) {
            String filePath = archiveFilePath;
            logger.debug(filePath);
            File file = new File(filePath);
            if (!file.exists()) {
                // Error
                logger.error(filePath + " not found.");
            }
            if (!file.canRead()) {
                // error
                logger.error("Unable to read " + filePath);
            }
            if (file.isDirectory()) {
                // check if it is an unzipped dwc archive.
                dwcArchive = openArchive(file);
            }
            if (file.isFile()) {
                // unzip it
                File outputDirectory = new File(file.getName().replace(".", "_") + "_content");
                if (!outputDirectory.exists()) {
                    outputDirectory.mkdir();
                    try {
                        byte[] buffer = new byte[1024];
                        ZipInputStream inzip = new ZipInputStream(new FileInputStream(file));
                        ZipEntry entry = inzip.getNextEntry();
                        while (entry != null) {
                            String fileName = entry.getName();
                            File expandedFile = new File(outputDirectory.getPath() + File.separator + fileName);
                            new File(expandedFile.getParent()).mkdirs();
                            FileOutputStream expandedfileOutputStream = new FileOutputStream(expandedFile);
                            int len;
                            while ((len = inzip.read(buffer)) > 0) {
                                expandedfileOutputStream.write(buffer, 0, len);
                            }

                            expandedfileOutputStream.close();
                            entry = inzip.getNextEntry();
                        }
                        inzip.closeEntry();
                        inzip.close();
                        logger.debug("Unzipped archive into " + outputDirectory.getPath());
                    } catch (FileNotFoundException e) {
                        logger.error(e.getMessage());
                    } catch (IOException e) {
                        logger.error(e.getMessage(), e);
                    }
                }
                // look into the unzipped directory
                dwcArchive = openArchive(outputDirectory);
            }
            if (dwcArchive != null) {
                if (checkArchive()) {
                    // Check output 
                    csvPrinter = new CSVPrinter(new FileWriter(outputFilename, append),
                            CSVFormat.DEFAULT.withQuoteMode(QuoteMode.NON_NUMERIC));
                    // no exception thrown
                    setupOK = true;
                }
            } else {
                System.out.println("Problem opening archive.");
                logger.error("Unable to unpack archive file.");
            }
            logger.debug(setupOK);
        }

    } catch (CmdLineException e) {
        logger.error(e.getMessage());
        parser.printUsage(System.err);
    } catch (IOException e) {
        logger.error(e.getMessage());
        System.out.println(e.getMessage());
        parser.printUsage(System.err);
    }
    return setupOK;
}

From source file:at.ac.tuwien.auto.iotsys.gateway.connectors.knx.KNXDeviceLoaderETSImpl.java

public void unZip(String zipFile, String outputFolder) {
    byte[] buffer = new byte[1024];

    try {//from  w  w w .  ja  v  a  2s.  co  m
        File folder = new File(outputFolder);
        if (!folder.exists()) {
            folder.mkdir();
        }

        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));

        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {

            String fileName = ze.getName();
            File newFile = new File(outputFolder + File.separator + fileName);

            log.info("file unzip : " + newFile.getAbsoluteFile());

            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.inaturalist.android.GuideXML.java

/**
 * Extracts a downloaded NGZ file into the offline guide directory
 * @param ngzFilename the NGZ file path/*  w ww. j  a  v  a  2s .  c  om*/
 * @return true/false status
 */
public boolean extractOfflineGuide(String ngzFilename) {
    // First, create the offline guide directory, if it doesn't exist
    File offlineGuidesDir = new File(mContext.getExternalCacheDir() + OFFLINE_GUIDE_PATH + mGuideId);
    offlineGuidesDir.mkdirs();

    // Next, extract the NGZ file into that directory
    String basePath = offlineGuidesDir.getPath();
    InputStream is;
    ZipInputStream zis;
    try {
        String filename;
        is = new FileInputStream(ngzFilename);
        zis = new ZipInputStream(new BufferedInputStream(is));
        ZipEntry ze;
        byte[] buffer = new byte[1024];
        int count;

        // Extract all files in the zip file - one by one
        while ((ze = zis.getNextEntry()) != null) {
            // Get current filename
            filename = ze.getName();

            // Need to create directories if doesn't exist, or it will generate an Exception...
            if (ze.isDirectory()) {
                File fmd = new File(basePath + "/" + filename);
                fmd.mkdirs();
                continue;
            }

            FileOutputStream fout = new FileOutputStream(basePath + "/" + filename);

            // Extract current file
            while ((count = zis.read(buffer)) != -1) {
                fout.write(buffer, 0, count);
            }

            fout.close();
            zis.closeEntry();
        }

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

    return true;
}

From source file:org.jevis.commons.drivermanagment.ClassImporter.java

public List<File> unZipIt(String outputFolder, File zipFile) {
    List<File> files = new ArrayList<>();

    byte[] buffer = new byte[1024];

    try {/* w  w w .  ja v a  2  s . c  o m*/

        //create output directory is not exists
        File folder = new File(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();

        while (ze != null) {

            String fileName = ze.getName();
            File newFile = new File(outputFolder + File.separator + fileName);
            newFile.deleteOnExit();
            files.add(newFile);

            //                System.out.println("file unzip : " + newFile.getAbsoluteFile());
            //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();
    }
    return files;
}

From source file:com.jlgranda.fede.ejb.mail.reader.FacturaElectronicaMailReader.java

/**
 * Obtiene una lista de objetos <tt>FacturaReader</tt> desde el mensaje de correo, si existe
 *
 * @param mime4jMessage//w  w  w. ja v  a2  s.c  o  m
 * @return lista de instancias instancia <tt>FacturaReader</tt> si existe la factura, null
 * en caso contrario
 */
private List<FacturaReader> handleMessage(org.apache.james.mime4j.dom.Message mime4jMessage)
        throws IOException, Exception {
    List<FacturaReader> result = new ArrayList<>();
    ByteArrayOutputStream os = null;
    String filename = null;
    Factura factura = null;
    EmailHelper emailHelper = new EmailHelper();
    if (mime4jMessage.isMultipart()) {
        org.apache.james.mime4j.dom.Multipart mime4jMultipart = (org.apache.james.mime4j.dom.Multipart) mime4jMessage
                .getBody();
        emailHelper.parseBodyParts(mime4jMultipart);
        //Obtener la factura en los adjuntos
        if (emailHelper.getAttachments().isEmpty()) {
            //If it's single part message, just get text body  
            String text = emailHelper.getHtmlBody().toString();
            emailHelper.getTxtBody().append(text);
            if (mime4jMessage.getSubject().contains("Ghost")) {

                String url = FacturaUtil.extraerURL(emailHelper.getHtmlBody().toString(), "<a href=\"",
                        "\" target=\"_blank\">Descarga formato XML</a>");
                if (url != null) {
                    result.add(FacturaElectronicaURLReader.getFacturaElectronica(url));
                }
            }
        } else {
            for (Entity entity : emailHelper.getAttachments()) {
                filename = EmailHelper.getFilename(entity);

                //if (entity.getBody() instanceof BinaryBody) {
                if (("application/octet-stream".equalsIgnoreCase(entity.getMimeType())
                        || "application/xml".equalsIgnoreCase(entity.getMimeType())
                        || "text/xml".equalsIgnoreCase(entity.getMimeType())
                        || "text/plain".equalsIgnoreCase(entity.getMimeType()))
                        && (filename != null && filename.endsWith(".xml"))) {
                    //attachFiles += part.getFileName() + ", ";
                    os = EmailHelper.writeBody(entity.getBody());
                    factura = FacturaUtil.read(os.toString());
                    if (factura != null) {
                        result.add(new FacturaReader(factura, os.toString(), entity.getFilename(),
                                mime4jMessage.getFrom().get(0).getAddress()));
                    }
                } else if (("application/octet-stream".equalsIgnoreCase(entity.getMimeType())
                        || "aplication/xml".equalsIgnoreCase(entity.getMimeType())
                        || "text/xml".equalsIgnoreCase(entity.getMimeType()))
                        && (filename != null && filename.endsWith(".zip"))) {
                    //http://www.java2s.com/Tutorial/Java/0180__File/UnzipusingtheZipInputStream.htm    
                    os = EmailHelper.writeBody(entity.getBody());
                    ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(os.toByteArray()));
                    try {
                        ZipEntry entry = null;
                        String tmp = null;
                        ByteArrayOutputStream fout = null;
                        while ((entry = zis.getNextEntry()) != null) {
                            if (entry.getName().endsWith(".xml")) {
                                //logger.debug("Unzipping {}", entry.getFilename());
                                fout = new ByteArrayOutputStream();
                                for (int c = zis.read(); c != -1; c = zis.read()) {
                                    fout.write(c);
                                }

                                tmp = new String(fout.toByteArray(), Charset.defaultCharset());

                                factura = FacturaUtil.read(tmp);
                                if (factura != null) {
                                    result.add(new FacturaReader(factura, tmp, entity.getFilename()));
                                }
                                fout.close();
                            }
                            zis.closeEntry();
                        }
                        zis.close();

                    } finally {
                        IOUtils.closeQuietly(os);
                        IOUtils.closeQuietly(zis);
                    }
                } else if ("message/rfc822".equalsIgnoreCase(entity.getMimeType())) {
                    if (entity.getBody() instanceof org.apache.james.mime4j.message.MessageImpl) {
                        result.addAll(
                                handleMessage((org.apache.james.mime4j.message.MessageImpl) entity.getBody()));
                    }
                }
            }
        }
    } else {
        //If it's single part message, just get text body  
        String text = emailHelper.getTxtPart(mime4jMessage);
        emailHelper.getTxtBody().append(text);
        if (mime4jMessage.getSubject().contains("Ghost")) {

            String url = FacturaUtil.extraerURL(emailHelper.getHtmlBody().toString(), "<a href=\"",
                    "\" target=\"_blank\">Descarga formato XML</a>");
            if (url != null) {
                result.add(FacturaElectronicaURLReader.getFacturaElectronica(url));
            }
        }
    }
    return result;
}

From source file:nl.imvertor.common.file.ZipFile.java

/**
 * Unzip it/*from  w w  w  . ja  va  2 s  .  c  om*/
 * @param zipFile input zip file
 * @param outputFolder zip file output folder
 * @param requestedFilePattern Pattern to match the file name.
 * 
 * @throws Exception 
 */
private void unZipIt(String zipFile, String outputFolder, Pattern requestedFilePattern) throws Exception {

    byte[] buffer = new byte[1024];

    //create output folder is not exists
    AnyFolder folder = new AnyFolder(outputFolder);
    folder.mkdir();

    //get the zip file content
    ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
    //get the zipped file list entry
    ZipEntry ze = zis.getNextEntry();

    while (ze != null) {
        if (!ze.isDirectory()) {
            String fileName = ze.getName();
            // if the pattern specified, use a matcher. Otherwise accept any file.
            Matcher m = (requestedFilePattern != null) ? requestedFilePattern.matcher(fileName) : null;
            if (requestedFilePattern == null || m.find()) {
                File newFile = new File(outputFolder + File.separator + fileName);
                //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();
}

From source file:org.wso2.carbon.apimgt.hostobjects.TenantManagerHostObject.java

private static void deployTenantTheme(FileHostObject themeFile, String tenant) throws APIManagementException {
    ZipInputStream zis = null;
    byte[] buffer = new byte[1024];

    String outputFolder = TenantManagerHostObject.getStoreTenantThemesPath() + tenant;

    InputStream zipInputStream = null;
    try {//from ww w  .j a va2 s  .c  o  m
        zipInputStream = themeFile.getInputStream();
    } catch (ScriptException e) {
        handleException("Error occurred while deploying tenant theme file", e);
    }

    try {

        //create output directory if it is not exists
        File folder = new File(outputFolder);
        if (!folder.exists()) {
            if (!folder.mkdirs()) {
                handleException("Unable to create tenant theme directory");
            }
        }

        //get the zip file content
        zis = new ZipInputStream(zipInputStream);
        //get the zipped file list entry
        ZipEntry ze = zis.getNextEntry();
        String ext = null;

        while (ze != null) {

            String fileName = ze.getName();
            File newFile = new File(outputFolder + File.separator + fileName);
            if (ze.isDirectory()) {
                if (!newFile.exists()) {
                    boolean status = newFile.mkdir();
                    if (status) {
                        //todo handle exception
                    }
                }
            } else {
                ext = FilenameUtils.getExtension(ze.getName());
                if (TenantManagerHostObject.EXTENTION_WHITELIST.contains(ext)) {
                    //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();
                } else {
                    log.warn("Unsupported file is uploaded with tenant theme by " + tenant + " : file name : "
                            + ze.getName());
                }

            }
            ze = zis.getNextEntry();
        }

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

    } catch (IOException ex) {
        handleException("Failed to deploy tenant theme", ex);
        //todo remove if the tenant theme directory is created.
    } finally {
        IOUtils.closeQuietly(zis);
        IOUtils.closeQuietly(zipInputStream);
    }
}