Example usage for java.util.zip ZipInputStream ZipInputStream

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

Introduction

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

Prototype

public ZipInputStream(InputStream in) 

Source Link

Document

Creates a new ZIP input stream.

Usage

From source file:edu.clemson.cs.nestbed.common.util.ZipUtils.java

public static File unzip(byte[] zipData, File directory) throws IOException {
    ByteArrayInputStream bais = new ByteArrayInputStream(zipData);
    ZipInputStream zis = new ZipInputStream(bais);
    ZipEntry entry = zis.getNextEntry();
    File root = null;/*from ww w. j  a va2  s  . c  o  m*/

    while (entry != null) {
        if (entry.isDirectory()) {
            File f = new File(directory, entry.getName());
            f.mkdir();

            if (root == null) {
                root = f;
            }
        } else {
            BufferedOutputStream out;
            out = new BufferedOutputStream(new FileOutputStream(new File(directory, entry.toString())),
                    BUFFER_SIZE);

            // ZipInputStream can only give us one byte at a time...
            for (int data = zis.read(); data != -1; data = zis.read()) {
                out.write(data);
            }
            out.close();
        }

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

    return root;
}

From source file:com.jcalvopinam.core.Unzipping.java

private static void joinAndUnzipFile(File inputFile, CustomFile customFile) throws IOException {

    ZipInputStream is = null;/*  w ww  . j  a v  a 2 s  . c  o  m*/
    File path = inputFile.getParentFile();

    List<InputStream> fileInputStream = new ArrayList<>();
    for (String fileName : path.list()) {
        if (fileName.startsWith(customFile.getFileName()) && fileName.endsWith(Extensions.ZIP.getExtension())) {
            fileInputStream.add(new FileInputStream(String.format("%s%s", customFile.getPath(), fileName)));
            System.out.println(String.format("File found: %s", fileName));
        }
    }

    if (fileInputStream.size() > 0) {
        String fileNameOutput = String.format("%s%s", customFile.getPath(), customFile.getFileName());
        OutputStream os = new BufferedOutputStream(new FileOutputStream(fileNameOutput));
        try {
            System.out.println("Please wait while the files are joined: ");

            ZipEntry ze;
            for (InputStream inputStream : fileInputStream) {
                is = new ZipInputStream(inputStream);
                ze = is.getNextEntry();
                customFile.setFileName(String.format("%s_%s", REBUILT, ze.getName()));

                byte[] buffer = new byte[CustomFile.BYTE_SIZE];

                for (int readBytes; (readBytes = is.read(buffer, 0, CustomFile.BYTE_SIZE)) > -1;) {
                    os.write(buffer, 0, readBytes);
                    System.out.print(".");
                }
            }
        } finally {
            os.flush();
            os.close();
            is.close();
            renameFinalFile(customFile, fileNameOutput);
        }
    } else {
        throw new FileNotFoundException("Error: The file not exist!");
    }
    System.out.println("\nEnded process!");
}

From source file:com.glue.feed.toulouse.open.data.venue.ToulouseEquipementsJob.java

@Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {

    try {/*w w  w.  j av  a  2  s .co  m*/
        URL url = new URL(
                "http://data.grandtoulouse.fr/web/guest/les-donnees/-/opendata/card/23851-equipements-culturels/resource/document?p_p_state=exclusive&_5_WAR_opendataportlet_jspPage=%2Fsearch%2Fview_card_license.jsp");
        ZipInputStream zin = new ZipInputStream(url.openStream());
        ZipEntry entry = GlueIOUtils.getEntry(zin, new FileExtensionFilter(".csv"));
        InputStream in = GlueIOUtils.getDeferredInputStream(zin, entry.getName());

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(new BOMInputStream(in), Charset.forName("UTF-8")));
        CSVFeedParser<VenueBean> parser = new CSVFeedParser<>(reader, VenueBean.class);

        final FeedMessageListener<Venue> delegate = new VenueMessageListener();
        final GlueObjectBuilder<VenueBean, Venue> venueBuilder = new VenueBeanVenueBuilder();

        parser.setFeedMessageListener(new FeedMessageListener<VenueBean>() {

            @Override
            public void newMessage(VenueBean msg) throws Exception {
                Venue venue = venueBuilder.build(msg);
                delegate.newMessage(venue);
            }

            @Override
            public void close() throws IOException {
                delegate.close();
            }
        });

        parser.read();
        parser.close();
        LOG.info("Done");
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        throw new JobExecutionException(e);
    }
}

From source file:com.googlesource.gerrit.plugins.xdocs.formatter.ZipFormatter.java

@Override
public String format(String projectName, String path, String revision, String abbrRev, ConfigSection globalCfg,
        InputStream raw) throws IOException {
    html.startDocument().openHead().closeHead().openBody().openTable("xdoc-zip-table").appendCellHeader("name")
            .appendCellHeader("size").appendCellHeader("last modified");
    try (ZipInputStream zip = new ZipInputStream(raw)) {
        for (ZipEntry entry; (entry = zip.getNextEntry()) != null;) {
            html.openRow().appendCell(entry.getName());
            if (!entry.isDirectory()) {
                if (entry.getSize() != -1) {
                    html.appendCell(FileUtils.byteCountToDisplaySize(entry.getSize()));
                } else {
                    html.appendCell("n/a");
                }/*w w  w  .ja  va  2 s  .co  m*/
            } else {
                html.appendCell();
            }
            html.appendDateCell(entry.getTime()).closeRow();
        }
    }
    html.closeTable().closeBody().endDocument();

    return util.applyCss(html.toString(), NAME, projectName);
}

From source file:com.edgenius.core.util.ZipFileUtil.java

public static void expandZipToFolder(InputStream is, String destFolder) throws ZipFileUtilException {
    // got our directory, so write out the input file and expand the zip file
    // this is really a hack - write it out temporarily then read it back in again! urg!!!!
    ZipInputStream zis = new ZipInputStream(is);
    int count;//www. j  ava  2s .  c om
    byte data[] = new byte[BUFFER_SIZE];
    ZipEntry entry = null;
    BufferedOutputStream dest = null;
    String entryName = null;

    try {

        // work through each file, creating a node for each file
        while ((entry = zis.getNextEntry()) != null) {
            entryName = entry.getName();
            if (!entry.isDirectory()) {

                String destName = destFolder + File.separator + entryName;
                //It must sort out the directory information to current OS. 
                //e.g, if zip file is zipped under windows, but unzip in linux.  
                destName = FileUtil.makeCanonicalPath(destName);

                prepareDirectory(destName);

                FileOutputStream fos = new FileOutputStream(destName);
                dest = new BufferedOutputStream(fos, BUFFER_SIZE);
                while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                IOUtils.closeQuietly(dest);
                dest = null;
            } else {
                String destName = destFolder + File.separator + entryName;
                destName = FileUtil.makeCanonicalPath(destName);
                new File(destName).mkdirs();
            }

        }

    } catch (IOException ioe) {

        log.error("Exception occured processing entries in zip file. Entry was " + entryName, ioe);
        throw new ZipFileUtilException(
                "Exception occured processing entries in zip file. Entry was " + entryName, ioe);

    } finally {
        IOUtils.closeQuietly(dest);
        IOUtils.closeQuietly(zis);
    }
}

From source file:de.fhg.iais.cortex.services.ingest.ZipStreamAipBinaries.java

public ZipStreamAipBinaries(InputStream inputStreamInZipFormat) {
    this.zipInputStream = new ZipInputStream(inputStreamInZipFormat);
}

From source file:com.thinkbiganalytics.feedmgr.util.ImportUtil.java

public static Set<ImportComponentOption> inspectZipComponents(InputStream inputStream, ImportType importType)
        throws IOException {
    Set<ImportComponentOption> options = new HashSet<>();
    ZipInputStream zis = new ZipInputStream(inputStream);
    ZipEntry entry;/*from  w w w.j  a  v  a  2  s  . c o  m*/
    while ((entry = zis.getNextEntry()) != null) {
        if (entry.getName().startsWith(ExportImportTemplateService.NIFI_TEMPLATE_XML_FILE)) {
            options.add(new ImportComponentOption(ImportComponent.NIFI_TEMPLATE,
                    importType.equals(ImportType.TEMPLATE) ? true : false));
        } else if (entry.getName().startsWith(ExportImportTemplateService.TEMPLATE_JSON_FILE)) {
            options.add(new ImportComponentOption(ImportComponent.TEMPLATE_DATA,
                    importType.equals(ImportType.TEMPLATE) ? true : false));
        } else if (entry.getName()
                .startsWith(ExportImportTemplateService.NIFI_CONNECTING_REUSABLE_TEMPLATE_XML_FILE)) {
            options.add(new ImportComponentOption(ImportComponent.REUSABLE_TEMPLATE, false));
        } else if (importType.equals(ImportType.FEED)
                && entry.getName().startsWith(ExportImportFeedService.FEED_JSON_FILE)) {
            options.add(new ImportComponentOption(ImportComponent.FEED_DATA, true));
            options.add(new ImportComponentOption(ImportComponent.USER_DATASOURCES, true));
        }
    }
    zis.closeEntry();
    zis.close();

    return options;
}

From source file:com.arykow.autotools.generator.App.java

private void generate() throws Exception {
    File directory = new File(projectDirectory);
    if (!directory.isDirectory()) {
        throw new RuntimeException();
    }/* ww w. j a  va 2  s.  co m*/
    File output = new File(directory, projectName);
    if (output.exists()) {
        if (projectForced) {
            if (!output.isDirectory()) {
                throw new RuntimeException();
            }
        } else {
            throw new RuntimeException();
        }
    } else if (!output.mkdir()) {
        throw new RuntimeException();
    }

    CodeSource src = getClass().getProtectionDomain().getCodeSource();
    if (src != null) {
        URL jar = src.getLocation();
        ZipInputStream zip = new ZipInputStream(jar.openStream());
        while (true) {
            ZipEntry e = zip.getNextEntry();
            if (e == null)
                break;
            if (!e.isDirectory() && e.getName().startsWith(String.format("%s", templateName))) {
                // generate(output, e);

                StringWriter writer = new StringWriter();
                IOUtils.copy(zip, writer);
                String content = writer.toString();

                Map<String, String> expressions = new HashMap<String, String>();
                expressions.put("author", "Karim DRIDI");
                expressions.put("name_undescore", projectName);
                expressions.put("license", "<Place your desired license here.>");
                expressions.put("name", projectName);
                expressions.put("version", "1.0");
                expressions.put("copyright", "Your copyright notice");
                expressions.put("description", "Hello World in C++,");

                for (Map.Entry<String, String> entry : expressions.entrySet()) {
                    content = content.replaceAll(String.format("<project\\.%s>", entry.getKey()),
                            entry.getValue());
                }

                String name = e.getName().substring(templateName.length() + 1);
                if ("gitignore".equals(name)) {
                    name = ".gitignore";
                }
                File file = new File(output, name);
                File parent = file.getParentFile();
                if (parent.exists()) {
                    if (!parent.isDirectory()) {
                        throw new RuntimeException();
                    }
                } else {
                    if (!parent.mkdirs()) {
                        throw new RuntimeException();
                    }
                }
                OutputStream stream = new FileOutputStream(file);
                IOUtils.copy(new StringReader(content), stream);
                IOUtils.closeQuietly(stream);
            }
        }
    }
}

From source file:com.jlgranda.fede.ejb.url.reader.FacturaElectronicaURLReader.java

/**
 * Obtiene la lista de objetos factura para el sujeto en fede
 *
 * @param urls URLs hacia los archivo XML o ZIP a leer
 * @return una lista de instancias FacturaReader
 *///from w ww  .  java2 s . c om
public static FacturaReader getFacturaElectronica(String url) throws Exception {
    FacturaReader facturaReader = null;

    if (url.endsWith(".xml")) {
        String xml = FacturaElectronicaURLReader.read(url);
        facturaReader = new FacturaReader(FacturaUtil.read(xml), xml, url);
    } else if (url.endsWith(".zip")) {
        URL url_ = new URL(url);
        InputStream is = url_.openStream();
        ZipInputStream zis = new ZipInputStream(is);
        try {

            ZipEntry entry = null;
            String tmp = null;
            ByteArrayOutputStream fout = null;
            while ((entry = zis.getNextEntry()) != null) {
                if (entry.getName().toLowerCase().endsWith(".xml")) {
                    fout = new ByteArrayOutputStream();
                    for (int c = zis.read(); c != -1; c = zis.read()) {
                        fout.write(c);
                    }

                    tmp = new String(fout.toByteArray(), Charset.defaultCharset());
                    facturaReader = new FacturaReader(FacturaUtil.read(tmp), tmp, url);
                    fout.close();
                }
                zis.closeEntry();
            }
            zis.close();

        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(zis);
        }
    }

    return facturaReader;
}

From source file:ch.admin.suis.msghandler.util.ZipUtils.java

/**
 * Decompress the given file to the specified directory.
 *
 * @param zipFile the ZIP file to decompress
 * @param toDir   the directory where the files from the archive must be placed; the
 *                file will be replaced if it already exists
 * @return a list of files that were extracted into the destination directory
 * @throws IllegalArgumentException if the provided file does not exist or the specified destination
 *                                  is not a directory
 * @throws IOException              if an IO error has occured (probably, a corrupted ZIP file?)
 *//*from  w  ww  . j a va 2s  .  c om*/
public static List<File> decompress(File zipFile, File toDir) throws IOException {
    Validate.isTrue(zipFile.exists(), "ZIP file does not exist", zipFile.getAbsolutePath());
    Validate.isTrue(toDir.isDirectory(), toDir.getAbsolutePath() + " is not a directory");

    final ArrayList<File> files = new ArrayList<>();

    try (ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile)))) {

        // read the entries
        ZipEntry entry;
        while (null != (entry = zis.getNextEntry())) {
            if (entry.isDirectory()) {
                LOG.error(MessageFormat.format(
                        "cannot extract the entry {0} from the {1}. because it is a directory", entry.getName(),
                        zipFile.getAbsolutePath()));
                continue;
            }

            // extract the file to the provided destination
            // we have to watch out for a unique name of the file to be extracted:
            // it can happen, that several at the same time incoming messages have a file with the same name
            File extracted = new File(FileUtils.getFilename(toDir, entry.getName()));
            if (!extracted.getParentFile().mkdirs()) {
                LOG.debug("cannot make all the necessary directories for the file "
                        + extracted.getAbsolutePath() + " or " + "the path is already created ");
            }

            try (BufferedOutputStream dest = new BufferedOutputStream(new FileOutputStream(extracted),
                    BUFFER_SIZE)) {
                byte[] data = new byte[BUFFER_SIZE];
                int count;
                while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
                    dest.write(data, 0, count);
                }

                files.add(extracted);
            }
        }

    }

    return files;
}