Example usage for java.util.zip ZipInputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:org.jboss.tools.tycho.sitegenerator.GenerateRepositoryFacadeMojo.java

/**
 * Alter content.xml, content.jar, content.xml.xz to:
 * remove default "Uncategorized" category, 
 * remove 3rd party associate sites, and 
 * add associate sites defined in site's pom.xml
 *
 * @param p2repository/*  w  w  w  . j a  v  a2  s . c  o  m*/
 * @throws FileNotFoundException
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws TransformerFactoryConfigurationError
 * @throws TransformerConfigurationException
 * @throws TransformerException
 * @throws MojoFailureException
 */
private void alterContentJar(File p2repository) throws FileNotFoundException, IOException, SAXException,
        ParserConfigurationException, TransformerFactoryConfigurationError, TransformerConfigurationException,
        TransformerException, MojoFailureException {
    File contentJar = new File(p2repository, "content.jar");
    ZipInputStream contentStream = new ZipInputStream(new FileInputStream(contentJar));
    ZipEntry entry = null;
    Document contentDoc = null;
    boolean done = false;
    while (!done && (entry = contentStream.getNextEntry()) != null) {
        if (entry.getName().equals("content.xml")) {
            contentDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(contentStream);
            Element repoElement = (Element) contentDoc.getElementsByTagName("repository").item(0);
            {
                NodeList references = repoElement.getElementsByTagName("references");
                // remove default references
                for (int i = 0; i < references.getLength(); i++) {
                    Node currentRef = references.item(i);
                    currentRef.getParentNode().removeChild(currentRef);
                }
                // add associateSites
                if (this.associateSites != null && this.associateSites.size() > 0
                        && this.referenceStrategy == ReferenceStrategy.embedReferences) {
                    Element refElement = contentDoc.createElement("references");
                    refElement.setAttribute("size", Integer.valueOf(2 * associateSites.size()).toString());
                    for (String associate : associateSites) {
                        Element rep0 = contentDoc.createElement("repository");
                        rep0.setAttribute("uri", associate);
                        rep0.setAttribute("url", associate);
                        rep0.setAttribute("type", "0");
                        rep0.setAttribute("options", "1");
                        refElement.appendChild(rep0);
                        Element rep1 = (Element) rep0.cloneNode(true);
                        rep1.setAttribute("type", "1");
                        refElement.appendChild(rep1);
                    }
                    repoElement.appendChild(refElement);
                }
            }
            // remove default "Uncategorized" category
            if (this.removeDefaultCategory) {
                Element unitsElement = (Element) repoElement.getElementsByTagName("units").item(0);
                NodeList units = unitsElement.getElementsByTagName("unit");
                for (int i = 0; i < units.getLength(); i++) {
                    Element unit = (Element) units.item(i);
                    String id = unit.getAttribute("id");
                    if (id != null && id.contains(".Default")) {
                        unit.getParentNode().removeChild(unit);
                    }
                }
                unitsElement.setAttribute("size",
                        Integer.toString(unitsElement.getElementsByTagName("unit").getLength()));
            }
            done = true;
        }
    }
    // .close and .closeEntry raise exception:
    // https://issues.apache.org/bugzilla/show_bug.cgi?id=3862
    ZipOutputStream outContentStream = new ZipOutputStream(new FileOutputStream(contentJar));
    ZipEntry contentXmlEntry = new ZipEntry("content.xml");
    outContentStream.putNextEntry(contentXmlEntry);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
    DOMSource source = new DOMSource(contentDoc);
    StreamResult result = new StreamResult(outContentStream);
    transformer.transform(source, result);
    contentStream.close();
    outContentStream.closeEntry();
    outContentStream.close();
    alterXzFile(new File(p2repository, "content.xml"), new File(p2repository, "content.xml.xz"), transformer,
            source);
}

From source file:com.pianobakery.complsa.MainGui.java

public void unzip(String zipFilePath, String destDirectory) throws IOException {
    File destDir = new File(destDirectory);
    if (!destDir.exists()) {
        destDir.mkdir();/*from w ww  .jav  a 2 s.c om*/
    }
    ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
    ZipEntry entry = zipIn.getNextEntry();
    // iterates over entries in the zip file
    while (entry != null) {
        String filePath = destDirectory + File.separator + entry.getName();
        if (!entry.isDirectory()) {
            // if the entry is a file, extracts it
            extractFile(zipIn, filePath);
        } else {
            // if the entry is a directory, make the directory
            File dir = new File(filePath);
            dir.mkdir();
        }
        zipIn.closeEntry();
        entry = zipIn.getNextEntry();
    }
    zipIn.close();
}

From source file:edu.harvard.iq.dvn.core.web.study.AddFilesPage.java

private List<StudyFileEditBean> createStudyFilesFromZip(File uploadedInputFile) {
    List<StudyFileEditBean> fbList = new ArrayList<StudyFileEditBean>();

    // This is a Zip archive that we want to unpack, then upload/ingest individual
    // files separately

    ZipInputStream ziStream = null;
    ZipEntry zEntry = null;/* w  w  w  . j a  va2 s  .  co  m*/
    FileOutputStream tempOutStream = null;

    try {
        // Create ingest directory for the study: 
        File dir = new File(uploadedInputFile.getParentFile(), study.getId().toString());
        if (!dir.exists()) {
            dir.mkdir();
        }

        // Open Zip stream: 

        ziStream = new ZipInputStream(new FileInputStream(uploadedInputFile));

        if (ziStream == null) {
            return null;
        }
        while ((zEntry = ziStream.getNextEntry()) != null) {
            // Note that some zip entries may be directories - we 
            // simply skip them:
            if (!zEntry.isDirectory()) {

                String fileEntryName = zEntry.getName();

                if (fileEntryName != null && !fileEntryName.equals("")) {

                    String dirName = null;
                    String finalFileName = null;

                    int ind = fileEntryName.lastIndexOf('/');

                    if (ind > -1) {
                        finalFileName = fileEntryName.substring(ind + 1);
                        if (ind > 0) {
                            dirName = fileEntryName.substring(0, ind);
                            dirName = dirName.replace('/', '-');
                        }
                    } else {
                        finalFileName = fileEntryName;
                    }

                    // http://superuser.com/questions/212896/is-there-any-way-to-prevent-a-mac-from-creating-dot-underscore-files
                    if (!finalFileName.startsWith("._")) {
                        File tempUploadedFile = FileUtil.createTempFile(dir, finalFileName);

                        tempOutStream = new FileOutputStream(tempUploadedFile);

                        byte[] dataBuffer = new byte[8192];
                        int i = 0;

                        while ((i = ziStream.read(dataBuffer)) > 0) {
                            tempOutStream.write(dataBuffer, 0, i);
                            tempOutStream.flush();
                        }

                        tempOutStream.close();

                        // We now have the unzipped file saved in the upload directory;

                        StudyFileEditBean tempFileBean = new StudyFileEditBean(tempUploadedFile,
                                studyService.generateFileSystemNameSequence(), study);
                        tempFileBean.setSizeFormatted(tempUploadedFile.length());

                        // And, if this file was in a legit (non-null) directory, 
                        // we'll use its name as the file category: 

                        if (dirName != null) {
                            tempFileBean.getFileMetadata().setCategory(dirName);
                        }

                        fbList.add(tempFileBean);
                    }
                }
            }
            ziStream.closeEntry();

        }

    } catch (Exception ex) {
        String msg = "Failed ot unpack Zip file/create individual study files";

        dbgLog.warning(msg);
        dbgLog.warning(ex.getMessage());

        //return null; 
    } finally {
        if (ziStream != null) {
            try {
                ziStream.close();
            } catch (Exception zEx) {
            }
        }
        if (tempOutStream != null) {
            try {
                tempOutStream.close();
            } catch (Exception ioEx) {
            }
        }
    }

    // should we delete uploadedInputFile before return?
    return fbList;
}

From source file:com.github.mavenplugins.doctest.ReportMojo.java

/**
 * Gets the doctest results and transforms them into {@link DoctestsContainer} objects.
 *///  www.  j a  va 2 s . c o m
protected void parseDoctestResults(File doctestResultDirectory, String doctestResultDirectoryName) {
    String tmp;
    String key;
    String className;
    String doctestName;
    String requestDataClass;
    String sourceName;
    String source;
    DoctestsContainer endpoint;
    DoctestData doctest;
    RequestResultWrapper requestResult;
    ResponseResultWrapper responseResult;
    Map<String, RequestResultWrapper> requestResults = new HashMap<String, RequestResultWrapper>();
    Map<String, ResponseResultWrapper> responseResults = new HashMap<String, ResponseResultWrapper>();
    ZipInputStream zipInputStream;
    ZipEntry zipEntry;

    for (File resultFile : FileUtils.listFiles(doctestResultDirectory, new String[] { "zip" }, false)) {
        zipInputStream = null;

        try {
            zipInputStream = new ZipInputStream(new BufferedInputStream(new FileInputStream(resultFile)));

            while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                tmp = zipEntry.getName();

                className = getClassName(tmp);
                doctestName = getDoctestName(tmp);
                requestDataClass = getRequestDataClass(tmp);
                sourceName = getSourceName(className);
                key = getKey(tmp);

                if (isRequest(tmp)) {
                    requestResults.put(key, mapper.readValue(new FilterInputStream(zipInputStream) {

                        @Override
                        public void close() throws IOException {
                        }

                    }, RequestResultWrapper.class));
                } else if (isResponse(tmp)) {
                    responseResults.put(key, mapper.readValue(new FilterInputStream(zipInputStream) {

                        @Override
                        public void close() throws IOException {
                        }

                    }, ResponseResultWrapper.class));
                }

                if (requestResults.containsKey(key) && responseResults.containsKey(key)) {
                    try {
                        requestResult = requestResults.get(key);
                        responseResult = responseResults.get(key);

                        requestResults.remove(key);
                        responseResults.remove(key);

                        source = FileUtils.readFileToString(
                                new File(project.getBuild().getTestSourceDirectory(), sourceName));

                        tmp = className + '.' + doctestName;
                        endpoint = endpoints.get(requestResult.getPath());
                        if (endpoint == null) {
                            endpoint = new DoctestsContainer();
                            endpoint.setName(requestResult.getPath());
                            endpoints.put(requestResult.getPath(), endpoint);
                        }

                        requestResult.setEntity(escapeToHtml(requestResult.getEntity()));
                        requestResult.setPath(escapeToHtml(requestResult.getPath()));
                        requestResult.setRequestLine(escapeToHtml(requestResult.getRequestLine()));
                        requestResult.setHeader(escapeToHtml(requestResult.getHeader()));
                        requestResult.setParemeters(escapeToHtml(requestResult.getParemeters()));

                        responseResult.setEntity(escapeToHtml(responseResult.getEntity()));
                        responseResult.setStatusLine(escapeToHtml(responseResult.getStatusLine()));
                        responseResult.setHeader(escapeToHtml(responseResult.getHeader()));
                        responseResult.setParemeters(escapeToHtml(responseResult.getParemeters()));

                        doctest = new DoctestData();
                        doctest.setJavaDoc(getJavaDoc(source, doctestName));
                        doctest.setName(tmp);
                        doctest.setRequest(requestResult);
                        doctest.setResponse(responseResult);
                        endpoint.getDoctests().put(tmp, doctest);
                    } catch (IOException exception) {
                        getLog().error("error while reading doctest request", exception);
                    }
                }
            }
        } catch (IOException exception) {
            getLog().error("error while reading doctest request", exception);
        } finally {
            if (zipInputStream != null) {
                try {
                    zipInputStream.close();
                } catch (IOException exception) {
                    getLog().error("error while reading doctest request", exception);
                }
            }
        }
    }
}

From source file:org.exoplatform.faq.service.impl.JCRDataStorage.java

@Override
public boolean importData(String parentId, InputStream inputStream, boolean isZip) throws Exception {
    SessionProvider sProvider = CommonUtils.createSystemProvider();
    List<String> patchNodeImport = new ArrayList<String>();
    Node categoryNode = getFAQServiceHome(sProvider).getNode(parentId);
    Session session = categoryNode.getSession();
    NodeIterator iter = categoryNode.getNodes();
    while (iter.hasNext()) {
        patchNodeImport.add(iter.nextNode().getName());
    }/*from  ww  w.jav a2 s  .  co  m*/
    if (isZip) { // Import from zipfile
        ZipInputStream zipStream = new ZipInputStream(inputStream);
        while (zipStream.getNextEntry() != null) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int available = -1;
            byte[] data = new byte[2048];
            while ((available = zipStream.read(data, 0, 1024)) > -1) {
                out.write(data, 0, available);
            }
            zipStream.closeEntry();
            out.close();
            InputStream input = new ByteArrayInputStream(out.toByteArray());
            session.importXML(categoryNode.getPath(), input, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);
            session.save();
        }
        zipStream.close();
        calculateImportRootCategory(categoryNode);
    } else { // import from xml
        session.importXML(categoryNode.getPath(), inputStream, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);
        session.save();
    }
    categoryNode = (Node) session.getItem(categoryNode.getPath());
    iter = categoryNode.getNodes();
    while (iter.hasNext()) {
        Node node = iter.nextNode();
        if (patchNodeImport.contains(node.getName()))
            patchNodeImport.remove(node.getName());
        else
            patchNodeImport.add(node.getName());
    }
    for (String string : patchNodeImport) {
        Node nodeParentQuestion = categoryNode.getNode(string);
        iter = getQuestionsIterator(nodeParentQuestion, EMPTY_STR, true);
        // Update number answers and regeister question node listener
        while (iter.hasNext()) {
            Node node = iter.nextNode();
            reUpdateNumberOfPublicAnswers(node);
        }
    }
    return true;
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String Unzip(String zipFileName, String dstDirectory) {
    String sRet = "";
    String fixedZipFileName = fixFileName(zipFileName);
    String fixedDstDirectory = fixFileName(dstDirectory);
    String dstFileName = "";
    int nNumExtracted = 0;
    boolean bRet = false;

    try {//from   w w w  .ja  va 2 s  .c  o m
        final int BUFFER = 2048;
        BufferedOutputStream dest = null;
        ZipFile zipFile = new ZipFile(fixedZipFileName);
        int nNumEntries = zipFile.size();
        zipFile.close();

        FileInputStream fis = new FileInputStream(fixedZipFileName);
        CheckedInputStream checksum = new CheckedInputStream(fis, new Adler32());
        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(checksum));
        ZipEntry entry;

        byte[] data = new byte[BUFFER];

        while ((entry = zis.getNextEntry()) != null) {
            System.out.println("Extracting: " + entry);
            int count;
            if (fixedDstDirectory.length() > 0)
                dstFileName = fixedDstDirectory + entry.getName();
            else
                dstFileName = entry.getName();

            String tmpDir = dstFileName.substring(0, dstFileName.lastIndexOf('/'));
            File tmpFile = new File(tmpDir);
            if (!tmpFile.exists()) {
                bRet = tmpFile.mkdirs();
            } else
                bRet = true;

            if (bRet) {
                // if we aren't just creating a directory
                if (dstFileName.lastIndexOf('/') != (dstFileName.length() - 1)) {
                    // write out the file
                    FileOutputStream fos = new FileOutputStream(dstFileName);
                    dest = new BufferedOutputStream(fos, BUFFER);
                    while ((count = zis.read(data, 0, BUFFER)) != -1) {
                        dest.write(data, 0, count);
                    }
                    dest.flush();
                    dest.close();
                    dest = null;
                    fos.close();
                    fos = null;
                }
                nNumExtracted++;
            } else
                sRet += " - failed" + lineSep;
        }

        data = null;
        zis.close();
        System.out.println("Checksum:          " + checksum.getChecksum().getValue());
        sRet += "Checksum:          " + checksum.getChecksum().getValue();
        sRet += lineSep + nNumExtracted + " of " + nNumEntries + " successfully extracted";
    } catch (Exception e) {
        e.printStackTrace();
    }

    return (sRet);
}

From source file:org.crs4.entando.innomanager.aps.system.services.layer.LayerManager.java

@Override
public File unzipShapeFile(String layername, File zipFile, String zipFileName) {
    int page = 0;
    InputStream fis;/*from  w w  w. j  a  v a2s  .c  o  m*/
    ZipInputStream zis;
    FileOutputStream fos;
    byte[] buffer = new byte[1024];
    String type;
    File newFile;
    String path = "";
    WorkLayer layer;
    try {
        layer = this.getWorkLayer(layername);
        path = getShapeFileDiskFolder(layername);
        if (layer == null)
            return null;
    } catch (Throwable t) {
        ApsSystemUtils.logThrowable(t, this, "UnZipShapeFile");
        return null;
    }
    if (!zipFileName.substring(zipFileName.length() - 4).equals(".zip"))
        return null;
    String fileName = null;
    String shapefileName = null;
    //try to unzip 
    boolean reset = false;
    try {
        fis = FileUtils.openInputStream(zipFile);
        zis = new ZipInputStream(fis);
        //get the zipped file list entry
        ZipEntry ze = zis.getNextEntry();

        boolean[] ext = { true, true, true };
        // controllo contenuto zip ( only the first 3 files: .shx, .shp, .dbf with the same name)
        while (ze != null) {
            type = null;
            ApsSystemUtils.getLogger().info("parse file: " + ze.getName());
            if (ze.getName().substring(ze.getName().length() - 4).equals(".shp")
                    && (shapefileName == null
                            || ze.getName().substring(0, ze.getName().length() - 4).equals(shapefileName))
                    && ext[0]) {
                type = ".shp";
                ext[0] = false;
            } else if (ze.getName().substring(ze.getName().length() - 4).equals(".dbf")
                    && (shapefileName == null
                            || ze.getName().substring(0, ze.getName().length() - 4).equals(shapefileName))
                    && ext[1]) {
                type = ".dbf";
                ext[1] = false;
            } else if (ze.getName().substring(ze.getName().length() - 4).equals(".shx")
                    && (shapefileName == null
                            || ze.getName().substring(0, ze.getName().length() - 4).equals(shapefileName))
                    && ext[2]) {
                type = ".shx";
                ext[2] = false;
            }
            // else the shapefiles haven't good ext or name 
            ApsSystemUtils.getLogger().info("type: " + type);

            // set the correct name of the shapefiles  (the first valid)

            if (type != null) {
                if (fileName == null) {
                    shapefileName = ze.getName().substring(0, ze.getName().length() - 4);
                    fileName = zipFileName.substring(0, zipFileName.length() - 4);
                    boolean found = false;
                    /// if exist changename
                    while (!found) {
                        newFile = new File(path + fileName + ".shp");
                        if (newFile.exists())
                            fileName += "0";
                        else
                            found = true;
                    }
                }
                ApsSystemUtils.getLogger().info("file write: " + path + fileName + type);
                newFile = new File(path + fileName + type);
                if (newFile.exists())
                    FileUtils.forceDelete(newFile);
                newFile = new File(path + fileName + type);
                {
                    fos = new FileOutputStream(newFile);
                    int len;
                    while ((len = zis.read(buffer)) > 0) {
                        fos.write(buffer, 0, len);
                    }
                    fos.close();
                    zis.closeEntry();
                }
            }
            ze = zis.getNextEntry();
        }
        zis.close();
    } catch (Throwable t) {
        ApsSystemUtils.logThrowable(t, this, "UnZippingShapeFile");
        reset = true;
    }
    if (fileName != null) {
        if (reset) {
            removeShapeFile(layername, fileName + ".shp");
        } else {
            newFile = new File(path + fileName + ".shp");
            if (newFile.exists())
                return newFile;
        }
    }
    return null;
}

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;//w  ww  . ja  v a 2s .  co  m
    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:es.gob.afirma.signers.ooxml.be.fedict.eid.applet.service.signer.ooxml.AbstractOOXMLSignatureService.java

private ZipOutputStream copyOOXMLContent(final String signatureZipEntryName,
        final OutputStream signedOOXMLOutputStream)
        throws IOException, ParserConfigurationException, SAXException, TransformerException {
    final ZipOutputStream zipOutputStream = new ZipOutputStream(signedOOXMLOutputStream);
    final ZipInputStream zipInputStream = new ZipInputStream(
            new ByteArrayInputStream(this.getOfficeOpenXMLDocument()));
    ZipEntry zipEntry;/*from  ww  w  . j  av a 2s . co m*/
    boolean hasOriginSigsRels = false;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        zipOutputStream.putNextEntry(new ZipEntry(zipEntry.getName()));
        if ("[Content_Types].xml".equals(zipEntry.getName())) { //$NON-NLS-1$
            final Document contentTypesDocument = loadDocumentNoClose(zipInputStream);
            final Element typesElement = contentTypesDocument.getDocumentElement();

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

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

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

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

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

            writeDocumentNoClosing(relsDocument, zipOutputStream, false);
        } else if (zipEntry.getName().startsWith("_xmlsignatures/_rels/") //$NON-NLS-1$
                && zipEntry.getName().endsWith(".rels")) { //$NON-NLS-1$

            hasOriginSigsRels = true;
            final Document originSignRelsDocument = loadDocumentNoClose(zipInputStream);

            final Element relationshipElement = originSignRelsDocument.createElementNS(RELATIONSHIPS_SCHEMA,
                    "Relationship"); //$NON-NLS-1$
            relationshipElement.setAttribute("Id", "rel-" + UUID.randomUUID().toString()); //$NON-NLS-1$ //$NON-NLS-2$
            relationshipElement.setAttribute("Type", //$NON-NLS-1$
                    "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/signature"); //$NON-NLS-1$

            relationshipElement.setAttribute("Target", FilenameUtils.getName(signatureZipEntryName)); //$NON-NLS-1$
            originSignRelsDocument.getDocumentElement().appendChild(relationshipElement);

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

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

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

From source file:com.kunze.androidlocaltodo.TaskListActivity.java

private void LoadAstrid() {
    // Look for a zip file in the proper location
    String loc = Environment.getExternalStorageDirectory() + "/AstridImport/";
    AlertDialog.Builder errorBuilder = new AlertDialog.Builder(this);
    errorBuilder.setTitle("Error reading Astrid Import!");
    ZipInputStream zipStream = null;
    InputStream stream = null;//from  w  ww  .j  a v a2s .c  om
    try {
        // Try to safely open the file
        String errText = "Cannot find Astrid file in " + loc;
        File astridDir = new File(loc);
        if (!astridDir.isDirectory()) {
            throw new Exception(errText);
        }

        File[] files = astridDir.listFiles();
        if (files.length != 1) {
            throw new Exception(errText);
        }

        File astridFile = files[0];
        if (!astridFile.isFile()) {
            throw new Exception(errText);
        }

        // Try to unzip the file and unpack the tasks
        errText = "Could not unzip file " + astridFile.getAbsolutePath();
        stream = new FileInputStream(astridFile);
        zipStream = new ZipInputStream(stream);

        ZipEntry tasksEntry = null;
        while ((tasksEntry = zipStream.getNextEntry()) != null) {
            if (tasksEntry.getName().equals("tasks.csv")) {
                break;
            }
        }
        if (tasksEntry == null) {
            throw new Exception(errText);
        }

        int size = (int) tasksEntry.getSize();
        byte tasksContent[] = new byte[size];
        int offset = 0;
        while (size != 0) {
            int read = zipStream.read(tasksContent, offset, size);
            if (read == 0) {
                throw new Exception(errText);
            }
            offset += read;
            size -= read;
        }

        String tasksString = new String(tasksContent, "UTF-8");

        // Parse the tasks in the task list
        errText = "Could not parse task list";
        List<String> taskLines = new LinkedList<String>(Arrays.asList(tasksString.split("\n")));
        // Remove the header row
        taskLines.remove(0);
        // Some tasks have newlines in quotes, so we have to adjust for that.
        ListIterator<String> it = taskLines.listIterator();
        while (it.hasNext()) {
            String task = it.next();
            while (CountQuotes(task) % 2 == 1) {
                it.remove();
                task += it.next();
            }
            it.set(task);
        }
        for (String taskLine : taskLines) {
            List<String> taskFields = new LinkedList<String>(Arrays.asList(taskLine.split(",", -1)));
            // Some tasks have commas in quotes, so we have to adjust for that.
            it = taskFields.listIterator();
            while (it.hasNext()) {
                String field = it.next();
                while (CountQuotes(field) % 2 == 1) {
                    it.remove();
                    field += it.next();
                }
                it.set(field);
            }

            Task taskElement = new Task();
            taskElement.mName = taskFields.get(0);
            taskElement.mDescription = taskFields.get(8);

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);

            taskElement.mDueDate = Calendar.getInstance();
            taskElement.mDueDate.setTime(dateFormat.parse(taskFields.get(4)));
            String completedString = taskFields.get(9);
            taskElement.mCompletedDate = Calendar.getInstance();
            if (completedString.equals("")) {
                taskElement.mCompletedDate.setTimeInMillis(0);
            } else {
                taskElement.mCompletedDate.setTime(dateFormat.parse(completedString));
            }
            taskElement.mRepeatUnit = Task.RepeatUnit.NONE;
            taskElement.mRepeatTime = 0;
            taskElement.mRepeatFromComplete = false;
            String repeatString = taskFields.get(6);
            String repeatFields[] = repeatString.split(":");
            if (repeatFields[0].equals("RRULE")) {
                repeatFields = repeatFields[1].split(";");
                String freqFields[] = repeatFields[0].split("=");
                if (freqFields[0].equals("FREQ")) {
                    if (freqFields[1].equals("YEARLY")) {
                        taskElement.mRepeatUnit = Task.RepeatUnit.YEARS;
                    } else if (freqFields[1].equals("MONTHLY")) {
                        taskElement.mRepeatUnit = Task.RepeatUnit.MONTHS;
                    } else if (freqFields[1].equals("WEEKLY")) {
                        taskElement.mRepeatUnit = Task.RepeatUnit.WEEKS;
                    } else if (freqFields[1].equals("DAILY")) {
                        taskElement.mRepeatUnit = Task.RepeatUnit.DAYS;
                    }
                }
                freqFields = repeatFields[1].split("=");
                if (freqFields[0].equals("INTERVAL")) {
                    taskElement.mRepeatTime = Integer.valueOf(freqFields[1]);
                }
                if (repeatFields.length > 2 && repeatFields[2] != null) {
                    freqFields = repeatFields[2].split("=");
                    if (freqFields[0].equals("FROM") && freqFields[1].equals("COMPLETION")) {
                        taskElement.mRepeatFromComplete = true;
                    }
                }
            }
            mDB.AddTask(taskElement);
        }

        RefreshView();
    } catch (Exception e) {
        AlertDialog dlg = errorBuilder.setMessage(e.getMessage()).create();
        dlg.show();
    } finally {

        try {
            if (zipStream != null) {
                zipStream.close();
            }
            if (stream != null) {
                stream.close();
            }
        } catch (Exception e) {
            AlertDialog dlg = errorBuilder.setMessage(e.getMessage()).create();
            dlg.show();
        }
    }
}