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:com.esminis.server.library.service.server.installpackage.InstallerPackage.java

private void install(Context context, File file, File targetDirectory) throws Throwable {
    sendBroadcast(context, STATE_INSTALL, 0);
    InputStream input = null;/*from   w  w w.  j a  v  a 2s  .c  o  m*/
    ZipInputStream zip = null;
    try {
        zip = new ZipInputStream(input = new FileInputStream(file));
        ZipEntry entry;
        int totalEntries = 0;
        while (zip.getNextEntry() != null) {
            totalEntries++;
        }
        zip.close();
        input.close();
        zip = new ZipInputStream(input = new FileInputStream(file));
        int position = 0;
        while ((entry = zip.getNextEntry()) != null) {
            if (entry.isDirectory()) {
                final File directory = new File(targetDirectory, entry.getName());
                if (!directory.isDirectory() && !directory.mkdirs()) {
                    throw new IOException("Cannot create directory: " + directory.getAbsolutePath());
                }
            } else {
                install(targetDirectory, entry.getName(), zip);
            }
            sendBroadcast(context, STATE_INSTALL, ((float) ++position / (float) totalEntries) * 0.99f);
        }
    } finally {
        if (zip != null) {
            try {
                zip.close();
            } catch (IOException ignored) {
            }
        }
        if (input != null) {
            try {
                input.close();
            } catch (IOException ignored) {
            }
        }
    }
    onInstallComplete(context);
    sendBroadcast(context, STATE_INSTALL, 1);
}

From source file:com.ariatemplates.attester.maven.ArtifactExtractor.java

public static void unzip(File zipFile, File outputFolder) throws IOException {
    ZipInputStream zipInputStream = null;
    try {/*from  ww w . ja v  a  2 s .  com*/
        ZipEntry entry = null;
        zipInputStream = new ZipInputStream(FileUtils.openInputStream(zipFile));
        while ((entry = zipInputStream.getNextEntry()) != null) {
            File outputFile = new File(outputFolder, entry.getName());

            if (entry.isDirectory()) {
                outputFile.mkdirs();
                continue;
            }

            OutputStream outputStream = null;
            try {
                outputStream = FileUtils.openOutputStream(outputFile);
                IOUtils.copy(zipInputStream, outputStream);
                outputStream.close();
            } catch (IOException exception) {
                outputFile.delete();
                throw new IOException(exception);
            } finally {
                IOUtils.closeQuietly(outputStream);
            }
        }
        zipInputStream.close();
    } finally {
        IOUtils.closeQuietly(zipInputStream);
    }
}

From source file:com.adaptris.core.lms.ZipFileBackedMessageTest.java

/**
 * This tests creates a compressed file//  w  ww . j  av a 2  s  .  co m
 */
@Test
public void testCreateCompressedFile() throws Exception {
    ZipFileBackedMessageFactory factory = getMessageFactory();
    factory.setCompressionMode(CompressionMode.Compress);
    FileBackedMessage orig = (FileBackedMessage) factory.newMessage();

    File srcFile = new File(BaseCase.PROPERTIES.getProperty("msg.initFromFile"));
    try (FileInputStream in = new FileInputStream(srcFile); OutputStream out = orig.getOutputStream()) {
        IOUtils.copy(in, out);
    }

    // File should now be compressed. Check if it's a zip file and if the compressed size equals the input file size
    try (ZipFile zipFile = new ZipFile(orig.currentSource())) {
        long size = 0;
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            size += entry.getSize();
        }

        assertEquals("message size", orig.getSize(), size);
        assertEquals("payload size", srcFile.length(), size);
    }

    // Check if the InputStream from the message also yields compressed data
    try (ZipInputStream zin = new ZipInputStream(orig.getInputStream());
            ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        zin.getNextEntry();
        IOUtils.copy(zin, out);
        assertEquals("payload size", srcFile.length(), out.size());
    }
}

From source file:com.github.stagirs.lingvo.build.Xml2Plain.java

private static List<String> extract(File file) throws IOException {
    ZipInputStream zis = new ZipInputStream(new FileInputStream(file));
    try {/*w  ww .  ja  v a  2  s .  c  o  m*/
        ZipEntry ze = zis.getNextEntry();
        if (ze == null) {
            throw new RuntimeException("can't unzip file");
        }
        return IOUtils.readLines(zis, Charset.forName("utf-8"));
    } finally {
        zis.close();
    }
}

From source file:edu.indiana.d2i.htrc.dataapi.DataAPIWrapper.java

private static void openZipStream(InputStream inputStream, Map<String, Map<String, String>> volPageContents,
        boolean isConcat) throws IOException {
    ZipInputStream zipInputStream = new ZipInputStream(inputStream);
    ZipEntry zipEntry = null;// w  ww .ja  v  a2  s  . com
    String currentVolID = null;

    if (!isConcat) {
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            String name = zipEntry.getName();

            /**
             * check whether encounter ERROR.err
             */
            if (ERROR_FNAME.equals(name)) {
                log.error("Encountered ERROR.err file in the zip stream");
                // log the content of ERROR.err file
                log.error("*************** Start of Content of ERROR.err ***************");
                StringBuilder sb = new StringBuilder();
                BufferedReader reader = new BufferedReader(new InputStreamReader(zipInputStream));
                String line = null;
                while ((line = reader.readLine()) != null)
                    sb.append(line + "\n");

                log.error(sb.toString());
                log.error("*************** End of Content of ERROR.err ***************");

                continue;
            }

            if (zipEntry.isDirectory()) {
                // get volume name
                currentVolID = name.split("/")[0];
                volPageContents.put(currentVolID, new HashMap<String, String>());

                if (log.isDebugEnabled())
                    log.debug("Encounter volueme directory : " + currentVolID);

            } else {
                String[] names = name.split("/");

                // each page is a separate entry
                //               assert names.length == 2;
                //               assert names[0].equals(currentVolID);

                // get page(s) content
                StringBuilder sb = new StringBuilder();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(zipInputStream, Charset.forName("UTF-8")));
                String line = null;
                while ((line = reader.readLine()) != null)
                    sb.append(line + "\n");

                Map<String, String> contents = volPageContents.get(currentVolID);

                int idx = names[1].indexOf(".txt");
                //               assert idx != -1;

                contents.put(names[1].substring(0, idx), sb.toString());
            }
        }
    } else {
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            assert !zipEntry.isDirectory();
            String name = zipEntry.getName();

            /**
             * check whether encounter ERROR.err
             */
            if (ERROR_FNAME.equals(name)) {
                log.error("Encountered ERROR.err file in the zip stream");
                // log the content of ERROR.err file
                log.error("*************** Start of Content of ERROR.err ***************");
                StringBuilder sb = new StringBuilder();
                BufferedReader reader = new BufferedReader(new InputStreamReader(zipInputStream));
                String line = null;
                while ((line = reader.readLine()) != null)
                    sb.append(line + "\n");

                log.error(sb.toString());
                log.error("*************** End of Content of ERROR.err ***************");

                continue;
            }

            int idx = name.indexOf(".txt");
            //            assert idx != -1;
            String cleanedVolId = name.substring(0, idx);

            if (log.isDebugEnabled())
                log.debug("Encounter volueme whole entry : " + cleanedVolId);

            StringBuilder sb = new StringBuilder();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(zipInputStream, Charset.forName("UTF-8")));
            String line = null;
            while ((line = reader.readLine()) != null)
                sb.append(line + "\n");

            HashMap<String, String> concatContent = new HashMap<String, String>();
            concatContent.put(DataAPIWrapper.WHOLE_CONTENT, sb.toString());
            volPageContents.put(cleanedVolId, concatContent);
        }
    }
}

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. ja  v a 2  s . co m*/
@Test
public void testGenerateFull() throws IOException {
    OpenApi2Thorntail generator = new OpenApi2Thorntail();
    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-full.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-full/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:JarMaker.java

/**
 * Unpack the jar file to a directory, till teaf files
 * @param file The source file name/*from  w w  w .  j a v a2  s. com*/
 * @param file1 The target directory
 * @author wangxp
 * @version 2003/11/07
 */
public static void unpackAppJar(String file, String file1) throws IOException {

    // m_log.debug("unpackAppJar begin. file="+file+"|||file1="+file1);

    BufferedInputStream bufferedinputstream = new BufferedInputStream(new FileInputStream(file));
    ZipInputStream zipinputstream = new ZipInputStream(bufferedinputstream);
    byte abyte0[] = new byte[1024];
    for (ZipEntry zipentry = zipinputstream.getNextEntry(); zipentry != null; zipentry = zipinputstream
            .getNextEntry()) {
        File file2 = new File(file1, zipentry.getName());
        if (zipentry.isDirectory()) {
            if (!file2.exists() && !file2.mkdirs())
                throw new IOException("Could not make directory " + file2.getPath());
        } else {
            File file3 = file2.getParentFile();
            if (file3 != null && !file3.exists() && !file3.mkdirs())
                throw new IOException("Could not make directory " + file3.getPath());
            BufferedOutputStream bufferedoutputstream = new BufferedOutputStream(new FileOutputStream(file2));
            int i;
            try {
                while ((i = zipinputstream.read(abyte0, 0, abyte0.length)) != -1)
                    bufferedoutputstream.write(abyte0, 0, i);
            } catch (IOException ie) {
                ie.printStackTrace();
                // m_logger.error(ie);
                throw ie;
            }
            bufferedoutputstream.close();
        }
    }
    zipinputstream.close();
    bufferedinputstream.close();
    // m_log.debug("unpackAppJar end.");
}

From source file:cc.recommenders.utils.gson.GsonUtil.java

public static <T> List<T> deserializeZip(File zip, Class<T> classOfT) throws IOException {

    List<T> res = Lists.newLinkedList();
    ZipInputStream zis = null;//w w  w  . j  a  va 2s . c  o  m
    try {
        InputSupplier<FileInputStream> fis = Files.newInputStreamSupplier(zip);
        zis = new ZipInputStream(fis.getInput());
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                final InputStreamReader reader = new InputStreamReader(zis);
                final T data = getInstance().fromJson(reader, classOfT);
                res.add(data);
            }
        }
    } finally {
        Closeables.closeQuietly(zis);
    }
    return res;
}

From source file:com.mg.merp.bpm.support.BusinessProccessManagerServiceBean.java

/**
 *  ?-??/*  w  ww . j  a  va2s  .  co m*/
 *
 * @param inputStream - 
 */
protected void doDeployProcess(InputStream inputStream) {
    JbpmContext context = BPMManagerLocator.locate().getCurrentBpmContext();
    try {
        ZipInputStream zipInputStream = new ZipInputStream(inputStream);
        ProcessDefinition processDefinition = ProcessDefinition.parseParZipInputStream(zipInputStream);
        context.getGraphSession().deployProcessDefinition(processDefinition);
    } finally {
        context.close();
    }
}

From source file:ca.uhn.fhir.jpa.term.TerminologyLoaderSvc.java

private void iterateOverZipFile(List<byte[]> theZipBytes, String fileNamePart, IRecordHandler handler,
        char theDelimiter, QuoteMode theQuoteMode) {
    boolean found = false;

    for (byte[] nextZipBytes : theZipBytes) {
        ZipInputStream zis = new ZipInputStream(
                new BufferedInputStream(new ByteArrayInputStream(nextZipBytes)));
        try {// w  w  w  .j  a  v  a 2  s  . com
            for (ZipEntry nextEntry; (nextEntry = zis.getNextEntry()) != null;) {
                ZippedFileInputStream inputStream = new ZippedFileInputStream(zis);

                String nextFilename = nextEntry.getName();
                if (nextFilename.contains(fileNamePart)) {
                    ourLog.info("Processing file {}", nextFilename);
                    found = true;

                    Reader reader = null;
                    CSVParser parsed = null;
                    try {
                        reader = new InputStreamReader(zis, Charsets.UTF_8);
                        CSVFormat format = CSVFormat.newFormat(theDelimiter).withFirstRecordAsHeader();
                        if (theQuoteMode != null) {
                            format = format.withQuote('"').withQuoteMode(theQuoteMode);
                        }
                        parsed = new CSVParser(reader, format);
                        Iterator<CSVRecord> iter = parsed.iterator();
                        ourLog.debug("Header map: {}", parsed.getHeaderMap());

                        int count = 0;
                        int logIncrement = LOG_INCREMENT;
                        int nextLoggedCount = 0;
                        while (iter.hasNext()) {
                            CSVRecord nextRecord = iter.next();
                            handler.accept(nextRecord);
                            count++;
                            if (count >= nextLoggedCount) {
                                ourLog.info(" * Processed {} records in {}", count, nextFilename);
                                nextLoggedCount += logIncrement;
                            }
                        }

                    } catch (IOException e) {
                        throw new InternalErrorException(e);
                    }
                }
            }
        } catch (IOException e) {
            throw new InternalErrorException(e);
        } finally {
            IOUtils.closeQuietly(zis);
        }
    }

    // This should always be true, but just in case we've introduced a bug...
    Validate.isTrue(found);
}