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.asakusafw.bulkloader.testutil.UnitTestUtil.java

public static boolean assertZipFile(File[] expectedFile, File zipFile) throws IOException {

    ZipInputStream zipIs = new ZipInputStream(new FileInputStream(zipFile));
    ZipEntry zipEntry = null;/* ww  w.  j  ava  2  s .com*/
    int i = 0;
    while ((zipEntry = zipIs.getNextEntry()) != null) {
        if (zipEntry.isDirectory()) {
            continue;
        }
        i++;
        File tempFile = new File("target/asakusa-thundergate/tempdata" + String.valueOf(i));
        FileOutputStream fos = new FileOutputStream(tempFile);
        byte[] b = new byte[1024];
        while (true) {
            int read = zipIs.read(b);
            if (read == -1) {
                break;
            }
            fos.write(b, 0, read);
        }

        // ?
        if (!assertFile(expectedFile[i - 1], tempFile)) {
            tempFile.delete();
            return false;
        }

        // temp
        tempFile.delete();
    }
    return true;
}

From source file:com.xpn.xwiki.plugin.zipexplorer.ZipExplorerPlugin.java

/**
 * @param document the document containing the ZIP file as an attachment
 * @param attachmentName the name under which the ZIP file is attached in the document
 * @param context not used/*from w ww .j a  v  a 2s .co m*/
 * @return the list of file entries in the ZIP file attached under the passed attachment name inside the passed
 *         document
 * @see com.xpn.xwiki.plugin.zipexplorer.ZipExplorerPluginAPI#getFileList
 */
public List<String> getFileList(Document document, String attachmentName, XWikiContext context) {
    List<String> zipList = new ArrayList<String>();
    Attachment attachment = document.getAttachment(attachmentName);

    InputStream stream = null;
    try {
        stream = new ByteArrayInputStream(attachment.getContent());

        if (isZipFile(stream)) {
            ZipInputStream zis = new ZipInputStream(stream);
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                zipList.add(entry.getName());
            }
        }
    } catch (XWikiException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return zipList;
}

From source file:be.fedict.eid.applet.service.signer.ooxml.AbstractOOXMLSignatureService.java

private ZipOutputStream copyOOXMLContent(String signatureZipEntryName, OutputStream signedOOXMLOutputStream)
        throws IOException, ParserConfigurationException, SAXException, TransformerConfigurationException,
        TransformerFactoryConfigurationError, TransformerException {
    ZipOutputStream zipOutputStream = new ZipOutputStream(signedOOXMLOutputStream);
    ZipInputStream zipInputStream = new ZipInputStream(this.getOfficeOpenXMLDocumentURL().openStream());
    ZipEntry zipEntry;// ww  w  .  j  a v a2  s . com
    boolean hasOriginSigsRels = false;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        LOG.debug("copy ZIP entry: " + zipEntry.getName());
        ZipEntry newZipEntry = new ZipEntry(zipEntry.getName());
        zipOutputStream.putNextEntry(newZipEntry);
        if ("[Content_Types].xml".equals(zipEntry.getName())) {
            Document contentTypesDocument = loadDocumentNoClose(zipInputStream);
            Element typesElement = contentTypesDocument.getDocumentElement();

            /*
             * We need to add an Override element.
             */
            Element overrideElement = contentTypesDocument.createElementNS(
                    "http://schemas.openxmlformats.org/package/2006/content-types", "Override");
            overrideElement.setAttribute("PartName", "/" + signatureZipEntryName);
            overrideElement.setAttribute("ContentType",
                    "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml");
            typesElement.appendChild(overrideElement);

            Element nsElement = contentTypesDocument.createElement("ns");
            nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns",
                    "http://schemas.openxmlformats.org/package/2006/content-types");
            NodeList nodeList = XPathAPI.selectNodeList(contentTypesDocument,
                    "/tns:Types/tns:Default[@Extension='sigs']", nsElement);
            if (0 == nodeList.getLength()) {
                /*
                 * Add Default element for 'sigs' extension.
                 */
                Element defaultElement = contentTypesDocument.createElementNS(
                        "http://schemas.openxmlformats.org/package/2006/content-types", "Default");
                defaultElement.setAttribute("Extension", "sigs");
                defaultElement.setAttribute("ContentType",
                        "application/vnd.openxmlformats-package.digital-signature-origin");
                typesElement.appendChild(defaultElement);
            }

            writeDocumentNoClosing(contentTypesDocument, zipOutputStream, false);
        } else if ("_rels/.rels".equals(zipEntry.getName())) {
            Document relsDocument = loadDocumentNoClose(zipInputStream);

            Element nsElement = relsDocument.createElement("ns");
            nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns",
                    "http://schemas.openxmlformats.org/package/2006/relationships");
            NodeList nodeList = XPathAPI.selectNodeList(relsDocument,
                    "/tns:Relationships/tns:Relationship[@Target='_xmlsignatures/origin.sigs']", nsElement);
            if (0 == nodeList.getLength()) {
                Element relationshipElement = relsDocument.createElementNS(
                        "http://schemas.openxmlformats.org/package/2006/relationships", "Relationship");
                relationshipElement.setAttribute("Id", "rel-id-" + UUID.randomUUID().toString());
                relationshipElement.setAttribute("Type",
                        "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/origin");
                relationshipElement.setAttribute("Target", "_xmlsignatures/origin.sigs");

                relsDocument.getDocumentElement().appendChild(relationshipElement);
            }

            writeDocumentNoClosing(relsDocument, zipOutputStream, false);
        } else if ("_xmlsignatures/_rels/origin.sigs.rels".equals(zipEntry.getName())) {
            hasOriginSigsRels = true;
            Document originSignRelsDocument = loadDocumentNoClose(zipInputStream);

            Element relationshipElement = originSignRelsDocument.createElementNS(
                    "http://schemas.openxmlformats.org/package/2006/relationships", "Relationship");
            String relationshipId = "rel-" + UUID.randomUUID().toString();
            relationshipElement.setAttribute("Id", relationshipId);
            relationshipElement.setAttribute("Type",
                    "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/signature");
            String target = FilenameUtils.getName(signatureZipEntryName);
            LOG.debug("target: " + target);
            relationshipElement.setAttribute("Target", target);
            originSignRelsDocument.getDocumentElement().appendChild(relationshipElement);

            writeDocumentNoClosing(originSignRelsDocument, zipOutputStream, false);
        } else {
            IOUtils.copy(zipInputStream, zipOutputStream);
        }
    }

    if (false == hasOriginSigsRels) {
        /*
         * Add signature relationships document.
         */
        addOriginSigsRels(signatureZipEntryName, zipOutputStream);
        addOriginSigs(zipOutputStream);
    }

    /*
     * Return.
     */
    zipInputStream.close();
    return zipOutputStream;
}

From source file:com.relicum.ipsum.io.PropertyIO.java

/**
 * Gets all files in jar.//  w w  w .  ja v  a2  s.  c  o  m
 *
 * @param clazz the clazz
 * @return the list of files and paths in jar
 */
default List<String> getAllFilesInJar(Class<?> clazz) {

    List<String> list = new ArrayList<>();
    CodeSource src = clazz.getProtectionDomain().getCodeSource();
    if (src != null) {
        try {
            URL jar = src.getLocation();
            ZipInputStream zip = new ZipInputStream(jar.openStream());
            while (true) {
                ZipEntry e = zip.getNextEntry();
                if (e == null)
                    break;
                String name = e.getName();
                if (name.contains(".properties")) {
                    list.add(name);
                    System.out.println(name);
                }

            }
            zip.close();
            jar = null;
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    return list;
}

From source file:gov.nasa.jpl.mudrod.main.MudrodEngine.java

private String decompressSVMWithSGDModel(String archiveName) throws IOException {

    URL scmArchive = getClass().getClassLoader().getResource(archiveName);
    if (scmArchive == null) {
        throw new IOException("Unable to locate " + archiveName + " as a classpath resource.");
    }/*from w  w  w. j a  v a2s  .  c o m*/
    File tempDir = Files.createTempDirectory("mudrod").toFile();
    assert tempDir.setWritable(true);
    File archiveFile = new File(tempDir, archiveName);
    FileUtils.copyURLToFile(scmArchive, archiveFile);

    // Decompress archive
    int BUFFER_SIZE = 512000;
    ZipInputStream zipIn = new ZipInputStream(new FileInputStream(archiveFile));
    ZipEntry entry;
    while ((entry = zipIn.getNextEntry()) != null) {
        File f = new File(tempDir, entry.getName());
        // If the entry is a directory, create the directory.
        if (entry.isDirectory() && !f.exists()) {
            boolean created = f.mkdirs();
            if (!created) {
                LOG.error("Unable to create directory '{}', during extraction of archive contents.",
                        f.getAbsolutePath());
            }
        } else if (!entry.isDirectory()) {
            boolean created = f.getParentFile().mkdirs();
            if (!created && !f.getParentFile().exists()) {
                LOG.error("Unable to create directory '{}', during extraction of archive contents.",
                        f.getParentFile().getAbsolutePath());
            }
            int count;
            byte data[] = new byte[BUFFER_SIZE];
            FileOutputStream fos = new FileOutputStream(new File(tempDir, entry.getName()), false);
            try (BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE)) {
                while ((count = zipIn.read(data, 0, BUFFER_SIZE)) != -1) {
                    dest.write(data, 0, count);
                }
            }
        }
    }

    return new File(tempDir, StringUtils.removeEnd(archiveName, ".zip")).toURI().toString();
}

From source file:com.alcatel_lucent.nz.wnmsextract.reader.FileSelector.java

/**
 * The nested unzip method. Given a zip stream, decompress and store in file in temp_dir.
 * Replaced by unzip3.//from  w w w .jav a  2 s.c  o m
 */
protected File unzip2(File zf) throws FileNotFoundException {
    //File f = null;
    String rename = zf.getAbsolutePath().replaceFirst("\\.zip", identifier + ".xml");//.replaceFirst("\\.gz", ".xml");
    File f = new File(rename);
    try {
        FileInputStream fis = new FileInputStream(zf);
        FileOutputStream fos = new FileOutputStream(rename);
        ZipInputStream zin = new ZipInputStream(fis);
        final byte[] content = new byte[BUFFER];
        int n = 0;
        while (-1 != (n = zin.read(content))) {
            fos.write(content, 0, n);
        }

        fos.flush();
        fos.close();

        fis.close();
        zin.close();
    } catch (IOException ioe) {
        jlog.error("Error processing Zip " + zf + " Excluding! :: " + ioe);
        return null;
    }
    //try again... what could go wrong
    if (checkMinFileSize(f) && retry_counter < MAX_UNGZIP_RETRIES) {
        retry_counter++;
        f.delete();
        f = unzip2(zf);
    }
    return f;
}

From source file:cz.zcu.kiv.eegdatabase.wui.core.experiments.ExperimentDownloadProvider.java

@Transactional
public FileDTO generatePackageFile(ExperimentPackage pckg, MetadataCommand mc, License license,
        List<Experiment> selectList, Person loggedUser, DownloadPackageManager manager) {

    ZipOutputStream zipOutputStream = null;
    FileOutputStream fileOutputStream = null;
    File tempZipFile = null;/* www .  j  av a  2  s  .c  om*/
    ZipInputStream in = null;
    File file = null;

    try {
        FileDTO dto = new FileDTO();
        dto.setFileName(pckg.getName().replaceAll("\\s", "_") + ".zip");

        // create temp zip file
        tempZipFile = File.createTempFile("experimentDownload_", ".zip");
        // open stream to temp zip file
        fileOutputStream = new FileOutputStream(tempZipFile);
        // prepare zip stream
        zipOutputStream = new ZipOutputStream(fileOutputStream);

        for (Experiment tmp : selectList) {

            Experiment exp = service.getExperimentForDetail(tmp.getExperimentId());
            String experimentDirPrefix = "";

            // create directory for each experiment.
            String scenarioName = exp.getScenario().getTitle();
            if (scenarioName != null) {
                experimentDirPrefix = "Experiment_" + exp.getExperimentId() + "_"
                        + scenarioName.replaceAll("\\s", "_") + "/";
            } else
                experimentDirPrefix = "Experiment_data_" + exp.getExperimentId() + "/";
            // generate temp zip file with experiment
            byte[] licenseFile = licenseService.getLicenseAttachmentContent(license.getLicenseId());
            file = zipGenerator.generate(exp, mc, exp.getDataFiles(), licenseFile,
                    license.getAttachmentFileName());
            in = new ZipInputStream(new FileInputStream(file));
            ZipEntry entryIn = null;

            // copy unziped experiment in package zip file.
            // NOTE: its easier solution copy content of one zip in anoter instead create directory structure via java.io.File.
            while ((entryIn = in.getNextEntry()) != null) {
                zipOutputStream.putNextEntry(new ZipEntry(experimentDirPrefix + entryIn.getName()));
                IOUtils.copyLarge(in, zipOutputStream);
                zipOutputStream.closeEntry();
            }

            // mark all temp files for package for delete on exit
            FileUtils.deleteOnExitQuietly(file);
            IOUtils.closeQuietly(in);
            FileUtils.deleteQuietly(file);

            createHistoryRecordAboutDownload(exp, loggedUser);
            synchronized (this) {
                manager.setNumberOfDownloadedExperiments(manager.getNumberOfDownloadedExperiments() + 1);
            }
        }

        dto.setFile(tempZipFile);

        // no problem detected - close all streams and mark file for delete on exit.
        // file is deleted after download action
        FileUtils.deleteOnExitQuietly(tempZipFile);
        IOUtils.closeQuietly(zipOutputStream);
        IOUtils.closeQuietly(fileOutputStream);

        return dto;
    } catch (Exception e) {

        log.error(e.getMessage(), e);

        // problem detected - close all streams, mark files for delete on exit and try delete them.
        IOUtils.closeQuietly(zipOutputStream);
        IOUtils.closeQuietly(fileOutputStream);
        FileUtils.deleteOnExitQuietly(tempZipFile);
        FileUtils.deleteOnExitQuietly(file);
        FileUtils.deleteQuietly(tempZipFile);
        FileUtils.deleteQuietly(file);

        return null;
    }
}

From source file:mashapeautoloader.MashapeAutoloader.java

/**
 * @param libraryName//from  w  w w.j a va  2 s  .c  om
 *
 * Returns false if something wrong, otherwise true (API interface
 * already exists or just well downloaded)
 */
private static boolean downloadLib(String libraryName) {
    URL url;
    URLConnection urlConn;

    // check (or make) for apiStore directory
    File apiStoreDir = new File(apiStore);
    if (!apiStoreDir.isDirectory())
        apiStoreDir.mkdir();

    String javaFilePath = apiStore + libraryName + ".java";
    File javaFile = new File(javaFilePath);

    // check if the API interface exists
    if (javaFile.exists())
        return true;
    try {
        // download the API interface's archive
        url = new URL(MASHAPE_DOWNLOAD_ROOT + libraryName);
        urlConn = url.openConnection();

        HttpURLConnection httpConn = (HttpURLConnection) urlConn;
        httpConn.setInstanceFollowRedirects(false);

        urlConn.setDoInput(true);
        urlConn.setDoOutput(false);
        urlConn.setUseCaches(false);

        // extract the archive stream
        ZipInputStream zip = new ZipInputStream(urlConn.getInputStream());
        String expectedEntryName = libraryName + ".java";
        while (true) {
            ZipEntry nextEntry = zip.getNextEntry();
            if (nextEntry == null)
                return false;

            String name = nextEntry.getName();
            if (name.equals(expectedEntryName)) {
                // save .java locally
                FileOutputStream javaFileStream = new FileOutputStream(javaFilePath);
                byte[] buf = new byte[1024];
                int n;
                while ((n = zip.read(buf, 0, 1024)) > -1)
                    javaFileStream.write(buf, 0, n);

                // compile it into .class file
                JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
                int result = compiler.run(null, null, null, javaFilePath);
                System.out.println(result);
                return result == 0;
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:net.sf.smbt.touchosc.utils.TouchOSCUtils.java

/**
 * Initialize UI model from a .jzml file
 * //from  w w w  . j av a  2 s.  c  om
 * @param zipTouchoscFilePath a .jzml file
 * 
 * @return UI model
 */
public TouchOscApp loadAppFromTouchOscXML(String zipTouchoscFilePath) {
    //
    // Create a resource set.
    //
    ResourceSet resourceSet = new ResourceSetImpl();

    IPath path = new Path(zipTouchoscFilePath);

    //
    // Register the default resource factory -- only needed for stand-alone!
    //
    resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(TouchoscPackage.eNS_PREFIX,
            new TouchoscResourceFactoryImpl());
    resourceSet.getPackageRegistry().put(TouchoscPackage.eNS_URI, TouchoscPackage.eINSTANCE);
    resourceSet.getPackageRegistry().put(TouchoscappPackage.eNS_URI, TouchoscappPackage.eINSTANCE);

    List<String> touchoscFilePathList = new ArrayList<String>();
    try {
        FileInputStream touchoscFile = new FileInputStream(zipTouchoscFilePath);
        ZipInputStream fileIS = new ZipInputStream(touchoscFile);

        ZipEntry zEntry = null;
        while ((zEntry = fileIS.getNextEntry()) != null) {
            if (zEntry.getName().endsWith(".xml")) {
                touchoscFilePathList.add(path.removeLastSegments(1) + "/_" + path.lastSegment());
            }
            FileOutputStream os = new FileOutputStream(path.removeLastSegments(1) + "/_" + path.lastSegment());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
            BufferedReader reader = new BufferedReader(new InputStreamReader(fileIS, Charset.forName("UTF-8")));
            CharBuffer charBuffer = CharBuffer.allocate(65535);
            while (reader.read(charBuffer) != -1)

                charBuffer.append("</touchosc:TOP>\n");
            charBuffer.flip();

            String content = charBuffer.toString();
            content = content.replace("<touchosc>", "");
            content = content.replace("</touchosc>", "");
            content = content.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", TOUCHOSC_XMLNS_HEADER);
            content = content.replace("numberX=", "number_x=");
            content = content.replace("numberY=", "number_y=");
            content = content.replace("invertedX=", "inverted_x=");
            content = content.replace("invertedY=", "inverted_y=");
            content = content.replace("localOff=", "local_off=");
            content = content.replace("oscCs=", "osc_cs=");

            writer.write(content);
            writer.flush();
            os.flush();
            os.close();
        }
        fileIS.close();
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e2) {
        e2.printStackTrace();
    }

    //
    // Get the URI of the model file.
    //
    URI touchoscURI = URI.createFileURI(touchoscFilePathList.get(0));

    //
    // Demand load the resource for this file.
    //
    Resource resource = resourceSet.getResource(touchoscURI, true);

    Object obj = (Object) resource.getContents().get(0);
    if (obj instanceof TOP) {
        TOP top = (TOP) obj;
        reverseZOrders(top);
        return initAppFromTouchOsc(top.getLayout(), "horizontal".equals(top.getLayout().getOrientation()),
                "0".equals(top.getLayout().getMode()));
    }
    return null;
}

From source file:fr.fastconnect.factory.tibco.bw.fcunit.PrepareTestMojo.java

private void removeFileInZipContaining(List<String> contentFilter, File zipFile)
        throws ZipException, IOException {
    ZipScanner zs = new ZipScanner();
    zs.setSrc(zipFile);/*from   w w  w. jav  a2s . co m*/
    String[] includes = { "**/*.process" };
    zs.setIncludes(includes);
    //zs.setCaseSensitive(true);
    zs.init();
    zs.scan();

    File originalProjlib = zipFile; // to be overwritten
    File tmpProjlib = new File(zipFile.getAbsolutePath() + ".tmp"); // to read
    FileUtils.copyFile(originalProjlib, tmpProjlib);

    ZipFile listZipFile = new ZipFile(tmpProjlib);
    ZipInputStream readZipFile = new ZipInputStream(new FileInputStream(tmpProjlib));
    ZipOutputStream writeZipFile = new ZipOutputStream(new FileOutputStream(originalProjlib));

    ZipEntry zipEntry;
    boolean keep;
    while ((zipEntry = readZipFile.getNextEntry()) != null) {
        keep = true;
        for (String filter : contentFilter) {
            keep = keep && !containsString(filter, listZipFile.getInputStream(zipEntry));
        }
        //         if (!containsString("<pd:type>com.tibco.pe.core.OnStartupEventSource</pd:type>", listZipFile.getInputStream(zipEntry))
        //          && !containsString("<pd:type>com.tibco.plugin.jms.JMSTopicEventSource</pd:type>", listZipFile.getInputStream(zipEntry))) {
        if (keep) {
            writeZipFile.putNextEntry(zipEntry);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = readZipFile.read(buf)) >= 0) {
                writeZipFile.write(buf, 0, len);
            }
            writeZipFile.closeEntry();
            //getLog().info("written");
        } else {
            getLog().info("removed " + zipEntry.getName());
        }

    }

    writeZipFile.close();
    readZipFile.close();
    listZipFile.close();

    originalProjlib.setLastModified(originalProjlib.lastModified() - 100000);
}