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:aurelienribon.gdxsetupui.ProjectSetup.java

/**
 * Selected libraries are inflated from their zip files, and put in the
 * libs folders of the projects./*ww  w. j  a va 2s.  c  o  m*/
 * @throws IOException
 */
public void inflateLibraries() throws IOException {
    File commonPrjLibsDir = new File(tmpDst, "/prj-common/libs");
    File desktopPrjLibsDir = new File(tmpDst, "/prj-desktop/libs");
    File androidPrjLibsDir = new File(tmpDst, "/prj-android/libs");
    File htmlPrjLibsDir = new File(tmpDst, "/prj-html/war/WEB-INF/lib");
    File iosPrjLibsDir = new File(tmpDst, "/prj-ios/libs");
    File dataDir = new File(tmpDst, "/prj-android/assets");

    for (String library : cfg.libraries) {
        InputStream is = new FileInputStream(cfg.librariesZipPaths.get(library));
        ZipInputStream zis = new ZipInputStream(is);
        ZipEntry entry;

        LibraryDef def = libs.getDef(library);

        while ((entry = zis.getNextEntry()) != null) {
            if (entry.isDirectory())
                continue;
            String entryName = entry.getName();

            for (String elemName : def.libsCommon)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, commonPrjLibsDir);
            for (String elemName : def.libsDesktop)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, desktopPrjLibsDir);
            for (String elemName : def.libsAndroid)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, androidPrjLibsDir);
            for (String elemName : def.libsHtml)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, htmlPrjLibsDir);
            for (String elemName : def.libsIos)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, iosPrjLibsDir);
            for (String elemName : def.data)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, dataDir);
        }

        zis.close();
    }
}

From source file:org.adl.samplerte.server.LMSPackageHandler.java

/****************************************************************************
**
** Method:   extract()//from w w  w .  java 2s  .co m
** Input:  String zipFileName  --  The name of the zip file to be used
**         Sting  extractedFile  --  The name of the file to be extracted 
**                                   from the zip    
** Output:   none
**
** Description: This method takes in the name of a zip file and a file to
**              be extracted from the zip format.  The method locates the
**              file and extracts into the '.' directory.
**              
*****************************************************************************/
public static String extract(String zipFileName, String extractedFile, String pathOfExtract) {
    if (_Debug) {
        System.out.println("***********************");
        System.out.println("in extract()           ");
        System.out.println("***********************");
        System.out.println("zip file: " + zipFileName);
        System.out.println("file to extract: " + extractedFile);
    }

    String nameOfExtractedFile = new String("");
    System.out.println("-----LMSPackageHandler-extract()----");
    System.out.println("zipFileName=" + zipFileName);
    System.out.println("extractedFile=" + extractedFile);
    System.out.println("pathOfExtract=" + pathOfExtract);
    try {
        String pathAndName = new String("");
        int index = zipFileName.lastIndexOf("\\") + 1;
        zipFileName = zipFileName.substring(index);
        System.out.println("---zipFileName=" + zipFileName);
        //  Input stream for the zip file (package)
        ZipInputStream in = new ZipInputStream(new FileInputStream(pathOfExtract + "\\" + zipFileName));

        //  Cut the path off of the name of the file. (for writing the file)
        int indexOfFileBeginning = extractedFile.lastIndexOf("/") + 1;
        System.out.println("---indexOfFileBeginning=" + indexOfFileBeginning);
        nameOfExtractedFile = extractedFile.substring(indexOfFileBeginning);
        System.out.println("---nameOfExtractedFile=" + nameOfExtractedFile);
        pathAndName = pathOfExtract + "\\" + nameOfExtractedFile;
        System.out.println("pathAndName=" + pathAndName);
        //  Ouput stream for the extracted file
        //*************************************
        //*************************************
        OutputStream out = new FileOutputStream(pathAndName);
        //OutputStream out = new FileOutputStream(nameOfExtractedFile);

        ZipEntry entry;
        byte[] buf = new byte[1024];
        int len;
        int flag = 0;

        while (flag != 1) {
            entry = in.getNextEntry();

            if ((entry.getName()).equalsIgnoreCase(extractedFile)) {
                if (_Debug) {
                    System.out.println("Found file to extract...  extracting to " + pathOfExtract);
                }
                flag = 1;
            }
        }

        while ((len = in.read(buf)) > 0) {

            out.write(buf, 0, len);
        }

        out.close();
        in.close();
    } catch (IOException e) {
        if (_Debug) {
            System.out.println("IO Exception Caught: " + e);
        }
        e.printStackTrace();
    }
    return nameOfExtractedFile;
}

From source file:it.jnrpe.plugins.factory.CPluginFactory.java

/**
 * @deprecated/*from   www.  j  a v a  2 s .c o  m*/
 */
private void configurePlugins(File fDir) {
    m_Logger.trace("READING PLUGIN CONFIGURATION FROM DIRECTORY " + fDir.getName());
    CStreamManager streamMgr = new CStreamManager();
    File[] vfJars = fDir.listFiles(new FileFilter() {

        public boolean accept(File f) {
            return f.getName().endsWith(".jar");
        }

    });

    // Initializing classloader
    URL[] urls = new URL[vfJars.length];
    URLClassLoader ul = null;

    for (int j = 0; j < vfJars.length; j++) {
        try {
            urls[j] = vfJars[j].toURI().toURL();
        } catch (MalformedURLException e) {
            // should never happen
        }
    }

    ul = URLClassLoader.newInstance(urls);

    for (int i = 0; i < vfJars.length; i++) {
        File file = vfJars[i];

        try {
            m_Logger.info("READING PLUGINS DATA IN FILE '" + file.getName() + "'");

            ZipInputStream jin = (ZipInputStream) streamMgr
                    .handle(new ZipInputStream(new FileInputStream(file)));
            ZipEntry ze = null;

            while ((ze = jin.getNextEntry()) != null) {
                if (ze.getName().equals("plugin.xml")) {
                    parsePluginXmlFile(jin);
                    break;
                }
            }
        } catch (Exception e) {
            m_Logger.error("UNABLE TO READ DATA FROM FILE '" + file.getName() + "'. THE FILE WILL BE IGNORED.",
                    e);
        } finally {
            streamMgr.closeAll();
        }

    }
}

From source file:functionalTests.vfsprovider.TestProActiveProvider.java

private void setUpTestDir() throws URISyntaxException, IOException {
    // create dir 
    if (testDir.exists()) {
        removeTestDir();//from ww w .jav a2 s. c  o  m
    }
    Assert.assertFalse(testDir.exists());
    Assert.assertTrue(testDir.mkdirs());

    // extract files from archive with VFS provider test data
    final ZipInputStream zipInputStream = new ZipInputStream(
            new BufferedInputStream(TEST_DATA_SRC_ZIP_URL.openStream()));
    try {
        extractZip(zipInputStream, testDir);
    } finally {
        zipInputStream.close();
    }

    // set VFS tests property
    System.setProperty("test.basedir", testDir.getAbsolutePath());
}

From source file:com.bukanir.android.utils.Utils.java

public static String unzipSubtitle(String zip, String path) {
    InputStream is;//w w w  . j  a  v a2  s  .c  o m
    ZipInputStream zis;
    try {
        String filename = null;
        is = new FileInputStream(zip);
        zis = new ZipInputStream(new BufferedInputStream(is));
        ZipEntry ze;
        byte[] buffer = new byte[1024];
        int count;

        while ((ze = zis.getNextEntry()) != null) {
            filename = ze.getName();

            if (ze.isDirectory()) {
                File fmd = new File(path + "/" + filename);
                fmd.mkdirs();
                continue;
            }

            if (filename.endsWith(".srt") || filename.endsWith(".sub")) {
                FileOutputStream fout = new FileOutputStream(path + "/" + filename);
                while ((count = zis.read(buffer)) != -1) {
                    fout.write(buffer, 0, count);
                }
                fout.close();
                zis.closeEntry();
                break;
            }
            zis.closeEntry();
        }
        zis.close();

        File z = new File(zip);
        z.delete();

        return path + "/" + filename;

    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

}

From source file:br.gov.jfrj.siga.wf.servlet.UploadServlet.java

/**
 * Coloca as informaes do arquivo da definio do processo no banco de
 * dados.// ww  w.j  a  va 2 s .co m
 * 
 * @param fileItem
 * @return
 */
private String doDeployment(FileItem fileItem) {
    try {
        ZipInputStream zipInputStream = new ZipInputStream(fileItem.getInputStream());
        JbpmContext jbpmContext = WfContextBuilder.getJbpmContext().getJbpmContext();
        ProcessDefinition processDefinition = ProcessDefinition.parseParZipInputStream(zipInputStream);
        jbpmContext.deployProcessDefinition(processDefinition);
        zipInputStream.close();
        long id = processDefinition.getId();

        String sReturn = "Deployed archive " + processDefinition.getName() + " successfully";

        // ProcessDefinition pi = jbpmContext.getGraphSession()
        // .loadProcessDefinition(id);

        Delegation d = new Delegation("br.gov.jfrj.siga.wf.util.WfAssignmentHandler");

        for (Swimlane s : ((Collection<Swimlane>) processDefinition.getTaskMgmtDefinition().getSwimlanes()
                .values())) {
            if (s.getTasks() != null)
                for (Object t : s.getTasks()) {
                    System.out.println(((Task) t).toString());
                }
            if (s.getAssignmentDelegation() == null)
                s.setAssignmentDelegation(d);
        }

        for (Task t : ((Collection<Task>) processDefinition.getTaskMgmtDefinition().getTasks().values())) {
            if (t.getSwimlane() == null && t.getAssignmentDelegation() == null)
                t.setAssignmentDelegation(d);
        }

        return sReturn;
    } catch (IOException e) {
        return "IOException";
    }
}

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

/**
 * Setup conditions to run.// w  w  w. jav  a 2 s.c o m
 * 
 * @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:com.thoughtworks.go.util.ZipUtilTest.java

@Test
void shouldReadContentsOfAFileWhichIsInsideAZip() throws Exception {
    FileUtils.writeStringToFile(new File(srcDir, "some-file.txt"), "some-text-here", UTF_8);
    zipFile = zipUtil.zip(srcDir, temporaryFolder.newFile(), Deflater.NO_COMPRESSION);

    String someStuff = zipUtil.getFileContentInsideZip(new ZipInputStream(new FileInputStream(zipFile)),
            "some-file.txt");

    assertThat(someStuff).isEqualTo("some-text-here");
}

From source file:com.funtl.framework.smoke.core.modules.act.service.ActProcessService.java

/**
 * ? - ?//from  w  w w.j  av a 2  s  . c  om
 *
 * @param file
 * @return
 */
@Transactional(readOnly = false)
public String deploy(String exportDir, String category, MultipartFile file) {

    String message = "";

    String fileName = file.getOriginalFilename();

    try {
        InputStream fileInputStream = file.getInputStream();
        Deployment deployment = null;
        String extension = FilenameUtils.getExtension(fileName);
        if (extension.equals("zip") || extension.equals("bar")) {
            ZipInputStream zip = new ZipInputStream(fileInputStream);
            deployment = repositoryService.createDeployment().addZipInputStream(zip).deploy();
        } else if (extension.equals("png")) {
            deployment = repositoryService.createDeployment().addInputStream(fileName, fileInputStream)
                    .deploy();
        } else if (fileName.indexOf("bpmn20.xml") != -1) {
            deployment = repositoryService.createDeployment().addInputStream(fileName, fileInputStream)
                    .deploy();
        } else if (extension.equals("bpmn")) { // bpmn????bpmn20.xml
            String baseName = FilenameUtils.getBaseName(fileName);
            deployment = repositoryService.createDeployment()
                    .addInputStream(baseName + ".bpmn20.xml", fileInputStream).deploy();
        } else {
            message = "??" + extension;
        }

        List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deployment.getId()).list();

        // ?
        for (ProcessDefinition processDefinition : list) {
            //               ActUtils.exportDiagramToFile(repositoryService, processDefinition, exportDir);
            repositoryService.setProcessDefinitionCategory(processDefinition.getId(), category);
            message += "??ID=" + processDefinition.getId() + "<br/>";
        }

        if (list.size() == 0) {
            message = "?";
        }

    } catch (Exception e) {
        throw new ActivitiException("?", e);
    }
    return message;
}

From source file:com.wakatime.eclipse.plugin.Dependencies.java

private void unzip(String zipFile, File outputDir) throws IOException {
    if (!outputDir.exists())
        outputDir.mkdirs();// www .ja  v  a 2  s.c  o m

    byte[] buffer = new byte[1024];
    ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
    ZipEntry ze = zis.getNextEntry();

    while (ze != null) {
        String fileName = ze.getName();
        File newFile = new File(outputDir, fileName);

        if (ze.isDirectory()) {
            // WakaTime.log("Creating directory: "+newFile.getParentFile().getAbsolutePath());
            newFile.mkdirs();
        } else {
            // WakaTime.log("Extracting File: "+newFile.getAbsolutePath());
            FileOutputStream fos = new FileOutputStream(newFile.getAbsolutePath());
            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
        }

        ze = zis.getNextEntry();
    }

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