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.thoughtworks.go.server.initializers.PluginsInitializerTest.java

@Test
public void shouldUnzipPluginsAndRegisterZipUpdaterBeforeStartingPluginsFramework() throws IOException {
    ZipUtil zipUtil = mock(ZipUtil.class);
    pluginsInitializer = new PluginsInitializer(pluginManager, systemEnvironment, zipUtil,
            pluginExtensionsAndVersionValidator, elasticAgentInformationMigrator) {
        @Override/*from   w ww .  j  a  va 2  s. c om*/
        public void startDaemon() {

        }

        @Override
        ZipInputStream getPluginsZipStream() {
            return new ZipInputStream(getClass().getResourceAsStream("/dummy-plugins.zip"));
        }
    };
    pluginsInitializer.initialize();

    InOrder inOrder = inOrder(zipUtil, pluginManager);

    inOrder.verify(zipUtil).unzip(any(ZipInputStream.class), any(File.class));
    inOrder.verify(pluginManager, times(1)).startInfrastructure(true);
}

From source file:com.twinsoft.convertigo.engine.util.ZipUtils.java

public static void expandZip(String zipFileName, String rootDir, String prefixDir)
        throws FileNotFoundException, IOException {
    Engine.logEngine.debug("Expanding the zip file " + zipFileName);

    // Creating the root directory
    File ftmp = new File(rootDir);
    if (!ftmp.exists()) {
        ftmp.mkdirs();/*from   www  .ja v a 2 s  .  c  o  m*/
        Engine.logEngine.debug("Root directory created");
    }

    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFileName)));

    try {
        ZipEntry entry;
        int prefixSize = prefixDir != null ? prefixDir.length() : 0;

        while ((entry = zis.getNextEntry()) != null) {
            // Ignoring directories
            if (entry.isDirectory()) {

            } else {

                String entryName = entry.getName();
                Engine.logEngine.debug("+ Analyzing the entry: " + entryName);

                try {
                    // Ignore entry if does not belong to the project directory
                    if ((prefixDir == null) || entryName.startsWith(prefixDir)) {

                        // Ignore entry from _data or _private directory
                        if ((entryName.indexOf("/_data/") != prefixSize)
                                && (entryName.indexOf("/_private/") != prefixSize)) {
                            Engine.logEngine.debug("  The entry is accepted");
                            String s1 = rootDir + "/" + entryName;
                            String dir = s1.substring(0, s1.lastIndexOf('/'));

                            // Creating the directory if needed
                            ftmp = new File(dir);
                            if (!ftmp.exists()) {
                                ftmp.mkdirs();
                                Engine.logEngine.debug("  Directory created");
                            }

                            // Writing the files to the disk
                            File file = new File(rootDir + "/" + entryName);
                            FileOutputStream fos = new FileOutputStream(file);
                            try {
                                IOUtils.copy(zis, fos);
                            } finally {
                                fos.close();
                            }
                            file.setLastModified(entry.getTime());
                            Engine.logEngine.debug("  File written to: " + rootDir + "/" + entryName);
                        }
                    }
                } catch (IOException e) {
                    Engine.logEngine.error(
                            "Unable to expand the ZIP entry \"" + entryName + "\": " + e.getMessage(), e);
                }
            }
        }
    } finally {
        zis.close();
    }
}

From source file:com.graphhopper.reader.OSMInputFile.java

@SuppressWarnings("unchecked")
private InputStream decode(File file) throws IOException {
    final String name = file.getName();

    InputStream ips = null;//from w  w w.  j a va  2 s.  c  o m
    try {
        ips = new BufferedInputStream(new FileInputStream(file), 50000);
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    }
    ips.mark(10);

    // check file header
    byte header[] = new byte[6];
    ips.read(header);

    /*     can parse bz2 directly with additional lib
     if (header[0] == 'B' && header[1] == 'Z')
     {
     return new CBZip2InputStream(ips);
     }
     */
    if (header[0] == 31 && header[1] == -117) {
        ips.reset();
        return new GZIPInputStream(ips, 50000);
    } else if (header[0] == 0 && header[1] == 0 && header[2] == 0 && header[4] == 10 && header[5] == 9
            && (header[3] == 13 || header[3] == 14)) {
        ips.reset();
        binary = true;
        return ips;
    } else if (header[0] == 'P' && header[1] == 'K') {
        ips.reset();
        ZipInputStream zip = new ZipInputStream(ips);
        zip.getNextEntry();

        return zip;
    } else if (name.endsWith(".osm") || name.endsWith(".xml")) {
        ips.reset();
        return ips;
    } else if (name.endsWith(".bz2") || name.endsWith(".bzip2")) {
        String clName = "org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream";
        try {
            Class clazz = Class.forName(clName);
            ips.reset();
            Constructor<InputStream> ctor = clazz.getConstructor(InputStream.class, boolean.class);
            return ctor.newInstance(ips, true);
        } catch (Exception e) {
            throw new IllegalArgumentException("Cannot instantiate " + clName, e);
        }
    } else {
        throw new IllegalArgumentException("Input file is not of valid type " + file.getPath());
    }
}

From source file:com.joliciel.lefff.LefffMemoryLoader.java

public LefffMemoryBase deserializeMemoryBase(File memoryBaseFile) {
    LOG.debug("deserializeMemoryBase");
    boolean isZip = false;
    if (memoryBaseFile.getName().endsWith(".zip"))
        isZip = true;/*  w w  w  .j  a  v a2s. c  om*/

    LefffMemoryBase memoryBase = null;
    ZipInputStream zis = null;
    FileInputStream fis = null;
    ObjectInputStream in = null;

    try {
        fis = new FileInputStream(memoryBaseFile);
        if (isZip) {
            zis = new ZipInputStream(fis);
            memoryBase = this.deserializeMemoryBase(zis);
        } else {
            in = new ObjectInputStream(fis);
            memoryBase = (LefffMemoryBase) in.readObject();
            in.close();
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    } catch (ClassNotFoundException cnfe) {
        throw new RuntimeException(cnfe);
    }

    return memoryBase;
}

From source file:fll.web.FullTournamentTest.java

/**
 * Load the test data into the specified database.
 *//*w  w w  .j a  va2 s  .c  o m*/
private static void loadTestData(final Connection testDataConn) throws SQLException, IOException {
    try (final InputStream dbResourceStream = FullTournamentTest.class
            .getResourceAsStream("data/99-final.flldb")) {
        Assert.assertNotNull("Missing test data", dbResourceStream);
        final ZipInputStream zipStream = new ZipInputStream(dbResourceStream);
        ImportDB.loadFromDumpIntoNewDB(zipStream, testDataConn);
    }
}

From source file:utils.APIImporter.java

/**
 * function to unzip the imported folder
 * @param zipFile zip file path// ww  w .  j  a v a2  s. co m
 * @param outputFolder folder to copy the zip content
 * @throws APIImportException
 */
private static void unzipFolder(String zipFile, String outputFolder) throws APIImportException {
    byte[] buffer = new byte[1024];

    try {
        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        //get the zipped file list entry
        ZipEntry ze = zis.getNextEntry();
        FileOutputStream fos = null;
        while (ze != null) {
            String fileName = ze.getName();
            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();
            fos = new FileOutputStream(newFile);
            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
            ze = zis.getNextEntry();
        }
        zis.closeEntry();
        IOUtils.closeQuietly(zis);
        IOUtils.closeQuietly(fos);
        //            ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        //            //get the zipped file list entry
        //            ZipEntry ze = zis.getNextEntry();
        //            FileOutputStream fos = null;
        //            while(ze!=null){
        //                String fileName = ze.getName();
        //                File newFile = new File(outputFolder + File.separator + fileName);
        //                //create all non exists folders
        //                //else it hit FileNotFoundException for compressed folder
        //                boolean directoryStatus = new File(newFile.getParent()).mkdirs();
        //                while (directoryStatus){
        //                     fos = new FileOutputStream(newFile);
        //                    int len;
        //                    while ((len = zis.read(buffer)) > 0) {
        //                        fos.write(buffer, 0, len);
        //                    }
        //                    ze = zis.getNextEntry();
        //                }
        //            }
        //            zis.closeEntry();
        //            IOUtils.closeQuietly(fos);
        //            IOUtils.closeQuietly(zis);
    } catch (IOException e) {
        String errorMsg = "Cannot extract the zip entries ";
        log.error(errorMsg, e);
        throw new APIImportException(errorMsg, e);
    }
}

From source file:com.thoughtworks.go.server.web.FileViewTest.java

@Test
public void testShouldZipFileIfZipIsRequired() throws Exception {
    Map<String, Object> model = new HashMap<>();
    model.put("targetFile", file);
    model.put(FileView.NEED_TO_ZIP, true);

    view.render(model, mockRequest, mockResponse);

    // Unzip from the response and verify that the we can read the file back
    File unzipHere = temporaryFolder.newFolder();
    new ZipUtil().unzip(new ZipInputStream(new ByteArrayInputStream(mockResponse.getContentAsByteArray())),
            unzipHere);/*  w ww.  j  a  v  a2  s  .  c  o  m*/
    assertEquals(FileUtils.readFileToString(new File(unzipHere, file.getName()), UTF_8), "hello");
}

From source file:com.formkiq.core.service.ArchiveServiceImpl.java

@Override
public ArchiveDTO extractJSONFromZipFile(final byte[] bytes) {

    ArchiveDTO archive = new ArchiveDTO();

    ByteArrayInputStream is = new ByteArrayInputStream(bytes);
    ZipInputStream zipStream = new ZipInputStream(is);

    try {/*from  www.  ja v  a2  s  .  co m*/

        ZipEntry entry = null;
        while ((entry = zipStream.getNextEntry()) != null) {

            String filename = entry.getName();

            if (filename.endsWith(".form")) {

                String data = IOUtils.toString(zipStream, CHARSET_UTF8);
                archive.addForm(this.jsonService.readValue(data, FormJSON.class));

            } else if (filename.endsWith(".workflow")) {

                String data = IOUtils.toString(zipStream, CHARSET_UTF8);
                archive.setWorkflow(this.jsonService.readValue(data, Workflow.class));

            } else if (filename.endsWith(".pdf")) {

                byte[] data = IOUtils.toByteArray(zipStream);
                archive.addPDF(filename, data);

            } else if (filename.endsWith(".signature")) {

                String s = filename.replaceAll("\\.signature", "");
                byte[] data = IOUtils.toByteArray(zipStream);
                archive.addSignature(s, data);

            } else if (filename.endsWith(".route")) {

                String data = IOUtils.toString(zipStream, CHARSET_UTF8);
                archive.addRoute(this.jsonService.readValue(data, WorkflowRoute.class));

            } else {

                byte[] data = IOUtils.toByteArray(zipStream);
                archive.addObject(filename, data);
            }
        }

        archive.finish();

    } catch (IOException e) {
        LOG.log(Level.WARNING, e.getMessage(), e);
        throw new InvalidRequestBodyException();

    } finally {

        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(zipStream);
    }

    return archive;
}

From source file:edu.wustl.xipHost.caGrid.RetrieveNBIASecuredTest.java

@Test
public void test() throws Exception {
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");
    Login login = new GridLogin();
    String userName = "<JIRAusername>";
    String password = "<JIRApassword>";
    DcmFileFilter dcmFilter = new DcmFileFilter();
    login.login(userName, password);//from  w  w  w. j a v  a 2 s  .c om
    GlobusCredential globusCred = login.getGlobusCredential();
    boolean isConnectionSecured = login.isConnectionSecured();
    logger.debug("Acquired NBIA GlobusCredential. Connection secured = " + isConnectionSecured);
    if (!isConnectionSecured) {
        fail("Unable to acquire NBIA GlobusCredential. Check username and password.");
        return;
    }
    NCIACoreServiceClient client = new NCIACoreServiceClient(gridServiceUrl, globusCred);
    client.setAnonymousPrefered(false);
    TransferServiceContextReference tscr = client.retrieveDicomDataBySeriesUID("1.3.6.1.4.1.9328.50.1.4718");
    TransferServiceContextClient tclient = new TransferServiceContextClient(tscr.getEndpointReference(),
            globusCred);
    InputStream istream = TransferClientHelper.getData(tclient.getDataTransferDescriptor(), globusCred);
    ZipInputStream zis = new ZipInputStream(istream);
    ZipEntryInputStream zeis = null;
    BufferedInputStream bis = null;
    File importDir = new File("./test-content/NBIA5");
    if (!importDir.exists()) {
        importDir.mkdirs();
    } else {
        File[] files = importDir.listFiles(dcmFilter);
        for (int j = 0; j < files.length; j++) {
            File file = files[j];
            file.delete();
        }
    }
    while (true) {
        try {
            zeis = new ZipEntryInputStream(zis);
        } catch (EOFException e) {
            break;
        } catch (IOException e) {
            logger.error(e, e);
        }
        String unzzipedFile = null;
        try {
            unzzipedFile = importDir.getCanonicalPath();
        } catch (IOException e) {
            logger.error(e, e);
        }
        logger.debug(" filename: " + zeis.getName());
        bis = new BufferedInputStream(zeis);
        byte[] data = new byte[8192];
        int bytesRead = 0;
        String retrievedFilePath = unzzipedFile + File.separator + zeis.getName();
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(retrievedFilePath));
            while ((bytesRead = (bis.read(data, 0, data.length))) != -1) {
                bos.write(data, 0, bytesRead);
            }
            bos.flush();
            bos.close();
        } catch (IOException e) {
            logger.error(e, e);
        }
    }
    try {
        zis.close();
        tclient.destroy();
    } catch (IOException e) {
        logger.error(e, e);
    }
    File[] retrievedFiles = importDir.listFiles(dcmFilter);
    int numbOfRetreivedFiles = retrievedFiles.length;
    assertEquals("Number of retrieved files should be 2 but is. " + numbOfRetreivedFiles, numbOfRetreivedFiles,
            2);
    //Assert file names. They should be equal to items' SeriesInstanceUIDs
    Map<String, File> mapRetrievedFiles = new HashMap<String, File>();
    for (int i = 0; i < numbOfRetreivedFiles; i++) {
        File file = retrievedFiles[i];
        mapRetrievedFiles.put(file.getName(), file);
    }
    boolean retrievedFilesCorrect = false;
    if (mapRetrievedFiles.containsKey("1.3.6.1.4.1.9328.50.1.4716.dcm")
            && mapRetrievedFiles.containsKey("1.3.6.1.4.1.9328.50.1.4720.dcm")) {
        retrievedFilesCorrect = true;
    }
    assertTrue("Retrieved files are not as expected.", retrievedFilesCorrect);
}

From source file:org.statmantis.mport.retro.event.RetrosheetEventReader.java

@Override
protected EventInformation read(InputStream stream) throws IOException {
    ZipInputStream zis = new ZipInputStream(stream);
    try {/*  w  w w. java 2 s.  c o  m*/
        EventInformation info = new EventInformation();
        ZipEntry entry = zis.getNextEntry();
        while (entry != null) {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(zis));
                if (entry.getName().equals("TEAM" + year)) {
                    readTeamFile(entry.getName(), reader, info);
                } else if (entry.getName().endsWith(".ROS")) {
                    readRosterFile(entry.getName(), reader, info);
                } else if (entry.getName().endsWith(".EVA") || entry.getName().endsWith(".EVN")
                        || entry.getName().endsWith(".eba") || entry.getName().endsWith(".ebn")) {
                    readEventFile(entry.getName(), reader, info);
                } else {
                    throw new RetrosheetRuntimeException("Unknown zip entry: " + entry);
                }
            } catch (Exception e) {
                throw new RetrosheetRuntimeException("Error reading zip entry " + entry.getName(), e);
            }
            entry = zis.getNextEntry();
        }
        return info;
    } finally {
        try {
            zis.close();
        } catch (Exception e) {
            //no-op
        }
    }
}