Example usage for java.util.zip ZipOutputStream DEFLATED

List of usage examples for java.util.zip ZipOutputStream DEFLATED

Introduction

In this page you can find the example usage for java.util.zip ZipOutputStream DEFLATED.

Prototype

int DEFLATED

To view the source code for java.util.zip ZipOutputStream DEFLATED.

Click Source Link

Document

Compression method for compressed (DEFLATED) entries.

Usage

From source file:org.gluu.oxtrust.action.UpdateTrustRelationshipAction.java

@Restrict("#{s:hasPermission('trust', 'access')}")
public String downloadConfiguration() {
    Shibboleth2ConfService shibboleth2ConfService = Shibboleth2ConfService.instance();

    ByteArrayOutputStream bos = new ByteArrayOutputStream(16384);
    ZipOutputStream zos = ResponseHelper.createZipStream(bos, "Shibboleth2 configuration files");
    try {//from   www  . j  a v  a  2  s  . c om
        zos.setMethod(ZipOutputStream.DEFLATED);
        zos.setLevel(Deflater.DEFAULT_COMPRESSION);

        // Add files
        String idpMetadataFilePath = shibboleth2ConfService.getIdpMetadataFilePath();
        if (!ResponseHelper.addFileToZip(idpMetadataFilePath, zos,
                Shibboleth2ConfService.SHIB2_IDP_IDP_METADATA_FILE)) {
            log.error("Failed to add " + idpMetadataFilePath + " to zip");
            return OxTrustConstants.RESULT_FAILURE;
        }

        if (this.trustRelationship.getSpMetaDataFN() == null) {
            log.error("SpMetaDataFN is not set.");
            return OxTrustConstants.RESULT_FAILURE;
        }
        String spMetadataFilePath = shibboleth2ConfService
                .getSpMetadataFilePath(this.trustRelationship.getSpMetaDataFN());
        if (!ResponseHelper.addFileToZip(spMetadataFilePath, zos,
                Shibboleth2ConfService.SHIB2_IDP_SP_METADATA_FILE)) {
            log.error("Failed to add " + spMetadataFilePath + " to zip");
            return OxTrustConstants.RESULT_FAILURE;
        }
        String sslDirFN = applicationConfiguration.getShibboleth2IdpRootDir() + File.separator
                + TrustService.GENERATED_SSL_ARTIFACTS_DIR + File.separator;
        String spKeyFilePath = sslDirFN + shibboleth2ConfService
                .getSpNewMetadataFileName(this.trustRelationship).replaceFirst("\\.xml$", ".key");
        if (!ResponseHelper.addFileToZip(spKeyFilePath, zos, Shibboleth2ConfService.SHIB2_IDP_SP_KEY_FILE)) {
            log.error("Failed to add " + spKeyFilePath + " to zip");
            //            return OxTrustConstants.RESULT_FAILURE;
        }
        String spCertFilePath = sslDirFN + shibboleth2ConfService
                .getSpNewMetadataFileName(this.trustRelationship).replaceFirst("\\.xml$", ".crt");
        if (!ResponseHelper.addFileToZip(spCertFilePath, zos, Shibboleth2ConfService.SHIB2_IDP_SP_CERT_FILE)) {
            log.error("Failed to add " + spCertFilePath + " to zip");
            //            return OxTrustConstants.RESULT_FAILURE;
        }

        String spAttributeMap = shibboleth2ConfService.generateSpAttributeMapFile(this.trustRelationship);
        if (spAttributeMap == null) {
            log.error("spAttributeMap is not set.");
            return OxTrustConstants.RESULT_FAILURE;
        }
        if (!ResponseHelper.addFileContentToZip(spAttributeMap, zos,
                Shibboleth2ConfService.SHIB2_SP_ATTRIBUTE_MAP)) {
            log.error("Failed to add " + spAttributeMap + " to zip");
            return OxTrustConstants.RESULT_FAILURE;
        }

        String spShibboleth2FilePath = shibboleth2ConfService.getSpShibboleth2FilePath();
        VelocityContext context = new VelocityContext();
        context.put("spUrl", trustRelationship.getUrl());
        String gluuSPEntityId = trustRelationship.getEntityId();
        context.put("gluuSPEntityId", gluuSPEntityId);
        String spHost = trustRelationship.getUrl().replaceAll(":[0-9]*$", "").replaceAll("^.*?//", "");
        context.put("spHost", spHost);
        String idpUrl = applicationConfiguration.getIdpUrl();
        context.put("idpUrl", idpUrl);
        String idpHost = idpUrl.replaceAll(":[0-9]*$", "").replaceAll("^.*?//", "");
        context.put("idpHost", idpHost);
        context.put("orgInum",
                StringHelper.removePunctuation(OrganizationService.instance().getOrganizationInum()));
        context.put("orgSupportEmail", applicationConfiguration.getOrgSupportEmail());
        String shibConfig = templateService.generateConfFile(Shibboleth2ConfService.SHIB2_SP_SHIBBOLETH2,
                context);
        if (!ResponseHelper.addFileContentToZip(shibConfig, zos, Shibboleth2ConfService.SHIB2_SP_SHIBBOLETH2)) {
            log.error("Failed to add " + spShibboleth2FilePath + " to zip");
            return OxTrustConstants.RESULT_FAILURE;
        }

        String spReadMeResourceName = shibboleth2ConfService.getSpReadMeResourceName();
        String fileName = (new File(spReadMeResourceName)).getName();
        InputStream is = resourceLoader.getResourceAsStream(spReadMeResourceName);
        //InputStream is = this.getClass().getClassLoader().getResourceAsStream(spReadMeResourceName);
        if (!ResponseHelper.addResourceToZip(is, fileName, zos)) {
            log.error("Failed to add " + spReadMeResourceName + " to zip");
            return OxTrustConstants.RESULT_FAILURE;
        }
        String spReadMeWindowsResourceName = shibboleth2ConfService.getSpReadMeWindowsResourceName();
        fileName = (new File(spReadMeWindowsResourceName)).getName();
        is = resourceLoader.getResourceAsStream(spReadMeWindowsResourceName);
        if (!ResponseHelper.addResourceToZip(is, fileName, zos)) {
            log.error("Failed to add " + spReadMeWindowsResourceName + " to zip");
            return OxTrustConstants.RESULT_FAILURE;
        }
    } finally {
        IOUtils.closeQuietly(zos);
        IOUtils.closeQuietly(bos);
    }

    boolean result = ResponseHelper.downloadFile("shibboleth2-configuration.zip",
            OxTrustConstants.CONTENT_TYPE_APPLICATION_ZIP, bos.toByteArray(), facesContext);

    return result ? OxTrustConstants.RESULT_SUCCESS : OxTrustConstants.RESULT_FAILURE;
}

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

public String Zip(String zipFileName, String srcName) {
    String fixedZipFileName = fixFileName(zipFileName);
    String fixedSrcName = fixFileName(srcName);
    String sRet = "";

    try {//from  ww w.j a  va2  s. com
        FileOutputStream dest = new FileOutputStream(fixedZipFileName);
        CheckedOutputStream checksum = new CheckedOutputStream(dest, new Adler32());
        ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(checksum));
        out.setMethod(ZipOutputStream.DEFLATED);

        sRet += AddFilesToZip(out, fixedSrcName, "");

        out.close();
        System.out.println("checksum:                   " + checksum.getChecksum().getValue());
        sRet += "checksum:                   " + checksum.getChecksum().getValue();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return (sRet);
}

From source file:com.portfolio.data.provider.MysqlAdminProvider.java

@Override
public Object getPortfolio(MimeType outMimeType, String portfolioUuid, int userId, int groupId, String label,
        String resource, String files) throws Exception {
    String rootNodeUuid = getPortfolioRootNode(portfolioUuid);
    String header = "";
    String footer = "";
    NodeRight nodeRight = credential.getPortfolioRight(userId, groupId, portfolioUuid, Credential.READ);
    if (!nodeRight.read)
        return "faux";

    if (outMimeType.getSubType().equals("xml")) {
        //         header = "<portfolio xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' schemaVersion='1.0'>";
        //         footer = "</portfolio>";

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder;
        Document document = null;
        try {/*from   w w w .j a v  a 2  s.  c om*/
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            document = documentBuilder.newDocument();
            document.setXmlStandalone(true);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Element root = document.createElement("portfolio");
        root.setAttribute("id", portfolioUuid);
        root.setAttribute("code", "0");

        //// Noeuds supplmentaire pour WAD
        // Version
        Element verNode = document.createElement("version");
        Text version = document.createTextNode("3");
        verNode.appendChild(version);
        root.appendChild(verNode);
        // metadata-wad
        Element metawad = document.createElement("metadata-wad");
        metawad.setAttribute("prog", "main.jsp");
        metawad.setAttribute("owner", "N");
        root.appendChild(metawad);

        //          root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        //          root.setAttribute("schemaVersion", "1.0");
        document.appendChild(root);

        getLinearXml(portfolioUuid, rootNodeUuid, root, true, null, userId, groupId);

        StringWriter stw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.transform(new DOMSource(document), new StreamResult(stw));

        if (resource != null && files != null) {

            if (resource.equals("true") && files.equals("true")) {
                String adressedufichier = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".xml";
                String adresseduzip = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".zip";

                File file = null;
                PrintWriter ecrire;
                PrintWriter ecri;
                try {
                    file = new File(adressedufichier);
                    ecrire = new PrintWriter(new FileOutputStream(adressedufichier));
                    ecrire.println(stw.toString());
                    ecrire.flush();
                    ecrire.close();
                    System.out.print("fichier cree ");
                } catch (IOException ioe) {
                    System.out.print("Erreur : ");
                    ioe.printStackTrace();
                }

                try {
                    String fileName = portfolioUuid + ".zip";

                    ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(adresseduzip));
                    zip.setMethod(ZipOutputStream.DEFLATED);
                    zip.setLevel(Deflater.BEST_COMPRESSION);
                    File dataDirectories = new File(file.getName());
                    FileInputStream fis = new FileInputStream(dataDirectories);
                    byte[] bytes = new byte[fis.available()];
                    fis.read(bytes);

                    ZipEntry entry = new ZipEntry(file.getName());
                    entry.setTime(dataDirectories.lastModified());
                    zip.putNextEntry(entry);
                    zip.write(bytes);
                    zip.closeEntry();
                    fis.close();
                    //zipDirectory(dataDirectories, zip);
                    zip.close();

                    file.delete();

                    return adresseduzip;

                } catch (FileNotFoundException fileNotFound) {
                    fileNotFound.printStackTrace();

                } catch (IOException io) {

                    io.printStackTrace();
                }
            }
        }

        return stw.toString();

    } else if (outMimeType.getSubType().equals("json")) {
        header = "{\"portfolio\": { \"-xmlns:xsi\": \"http://www.w3.org/2001/XMLSchema-instance\",\"-schemaVersion\": \"1.0\",";
        footer = "}}";
    }

    return header + getNode(outMimeType, rootNodeUuid, true, userId, groupId, label).toString() + footer;
}

From source file:com.portfolio.data.provider.MysqlDataProvider.java

@Override
public Object getPortfolio(MimeType outMimeType, String portfolioUuid, int userId, int groupId, String label,
        String resource, String files, int substid) throws Exception {
    String rootNodeUuid = getPortfolioRootNode(portfolioUuid);
    String header = "";
    String footer = "";
    NodeRight nodeRight = credential.getPortfolioRight(userId, groupId, portfolioUuid, Credential.READ);
    if (!nodeRight.read) {
        userId = credential.getPublicUid();
        //         NodeRight nodeRight = new NodeRight(false,false,false,false,false,false);
        /// Vrifie les droits avec le compte publique (dernire chance)
        nodeRight = credential.getPublicRight(userId, 123, rootNodeUuid, "dummy");
        if (!nodeRight.read)
            return "faux";
    }/* ww w.  j  ava  2 s  . c om*/

    if (outMimeType.getSubType().equals("xml")) {
        //         header = "<portfolio xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' schemaVersion='1.0'>";
        //         footer = "</portfolio>";

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder;
        Document document = null;
        try {
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            document = documentBuilder.newDocument();
            document.setXmlStandalone(true);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }

        Element root = document.createElement("portfolio");
        root.setAttribute("id", portfolioUuid);
        root.setAttribute("code", "0");

        //// Noeuds supplmentaire pour WAD
        // Version
        Element verNode = document.createElement("version");
        Text version = document.createTextNode("4");
        verNode.appendChild(version);
        root.appendChild(verNode);
        // metadata-wad
        //         Element metawad = document.createElement("metadata-wad");
        //         metawad.setAttribute("prog", "main.jsp");
        //         metawad.setAttribute("owner", "N");
        //         root.appendChild(metawad);
        int owner = credential.getOwner(userId, portfolioUuid);
        String isOwner = "N";
        if (owner == userId)
            isOwner = "Y";
        root.setAttribute("owner", isOwner);

        //          root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        //          root.setAttribute("schemaVersion", "1.0");
        document.appendChild(root);

        getLinearXml(portfolioUuid, rootNodeUuid, root, true, null, userId, nodeRight.groupId,
                nodeRight.groupLabel);

        StringWriter stw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.transform(new DOMSource(document), new StreamResult(stw));

        if (resource != null && files != null) {
            if (resource.equals("true") && files.equals("true")) {
                String adressedufichier = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".xml";
                String adresseduzip = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".zip";

                File file = null;
                PrintWriter ecrire;
                try {
                    file = new File(adressedufichier);
                    ecrire = new PrintWriter(new FileOutputStream(adressedufichier));
                    ecrire.println(stw.toString());
                    ecrire.flush();
                    ecrire.close();
                    System.out.print("fichier cree ");
                } catch (IOException ioe) {
                    System.out.print("Erreur : ");
                    ioe.printStackTrace();
                }

                try {
                    ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(adresseduzip));
                    zip.setMethod(ZipOutputStream.DEFLATED);
                    zip.setLevel(Deflater.BEST_COMPRESSION);
                    File dataDirectories = new File(file.getName());
                    FileInputStream fis = new FileInputStream(dataDirectories);
                    byte[] bytes = new byte[fis.available()];
                    fis.read(bytes);

                    ZipEntry entry = new ZipEntry(file.getName());
                    entry.setTime(dataDirectories.lastModified());
                    zip.putNextEntry(entry);
                    zip.write(bytes);
                    zip.closeEntry();
                    fis.close();
                    //zipDirectory(dataDirectories, zip);
                    zip.close();

                    file.delete();

                    return adresseduzip;
                } catch (FileNotFoundException fileNotFound) {
                    fileNotFound.printStackTrace();
                } catch (IOException io) {
                    io.printStackTrace();
                }
            }
        }

        return stw.toString();
    } else if (outMimeType.getSubType().equals("json")) {
        header = "{\"portfolio\": { \"-xmlns:xsi\": \"http://www.w3.org/2001/XMLSchema-instance\",\"-schemaVersion\": \"1.0\",";
        footer = "}}";
    }

    return header + getNode(outMimeType, rootNodeUuid, true, userId, groupId, label).toString() + footer;
}