Example usage for java.util.zip Deflater DEFAULT_COMPRESSION

List of usage examples for java.util.zip Deflater DEFAULT_COMPRESSION

Introduction

In this page you can find the example usage for java.util.zip Deflater DEFAULT_COMPRESSION.

Prototype

int DEFAULT_COMPRESSION

To view the source code for java.util.zip Deflater DEFAULT_COMPRESSION.

Click Source Link

Document

Default compression level.

Usage

From source file:org.adeptnet.auth.saml.SAMLClient.java

private byte[] deflate(final byte[] input) throws IOException {
    // deflate and base-64 encode it
    final Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true);
    deflater.setInput(input);//from w w  w  . j  a v  a 2  s. c o  m
    deflater.finish();

    byte[] tmp = new byte[8192];
    int count;

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    while (!deflater.finished()) {
        count = deflater.deflate(tmp);
        bos.write(tmp, 0, count);
    }
    bos.close();
    deflater.end();

    return bos.toByteArray();
}

From source file:org.atricore.idbus.capabilities.sso.main.binding.SamlR2HttpRedirectBinding.java

public static String deflateForRedirect(String redirStr, boolean encode) {

    int n = redirStr.length();
    byte[] redirIs = null;
    try {//from  w w  w .  java 2  s . c o  m
        redirIs = redirStr.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }

    byte[] deflated = new byte[n];

    Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true);
    deflater.setInput(redirIs);
    deflater.finish();
    int len = deflater.deflate(deflated);
    deflater.end();

    byte[] exact = new byte[len];

    System.arraycopy(deflated, 0, exact, 0, len);

    if (encode) {
        byte[] base64Str = new Base64().encode(exact);
        return new String(base64Str);
    }

    return new String(exact);
}

From source file:org.codehaus.plexus.archiver.zip.ConcurrentJarCreator.java

public static ScatterZipOutputStream createDeferred(
        ScatterGatherBackingStoreSupplier scatterGatherBackingStoreSupplier) throws IOException {
    ScatterGatherBackingStore bs = scatterGatherBackingStoreSupplier.get();
    StreamCompressor sc = StreamCompressor.create(Deflater.DEFAULT_COMPRESSION, bs);
    return new ScatterZipOutputStream(bs, sc);
}

From source file:org.egov.ptis.actions.reports.SearchNoticesAction.java

/**
 * @param inputStream//w w  w. j  a  va  2 s . co m
 * @param noticeNo
 * @param out
 * @return zip output stream file
 */
private ZipOutputStream addFilesToZip(final InputStream inputStream, final String noticeNo,
        final ZipOutputStream out) {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Entered into addFilesToZip method");
    final byte[] buffer = new byte[1024];
    try {
        out.setLevel(Deflater.DEFAULT_COMPRESSION);
        out.putNextEntry(new ZipEntry(noticeNo.replaceAll("/", "_")));
        int len;
        while ((len = inputStream.read(buffer)) > 0)
            out.write(buffer, 0, len);
        inputStream.close();

    } catch (final IllegalArgumentException iae) {
        LOGGER.error(EXCEPTION_IN_ADD_FILES_TO_ZIP, iae);
        throw new ValidationException(Arrays.asList(new ValidationError(ERROR1, iae.getMessage())));
    } catch (final FileNotFoundException fnfe) {
        LOGGER.error(EXCEPTION_IN_ADD_FILES_TO_ZIP, fnfe);
        throw new ValidationException(Arrays.asList(new ValidationError(ERROR1, fnfe.getMessage())));
    } catch (final IOException ioe) {
        LOGGER.error(EXCEPTION_IN_ADD_FILES_TO_ZIP, ioe);
        throw new ValidationException(Arrays.asList(new ValidationError(ERROR1, ioe.getMessage())));
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Exit from addFilesToZip method");
    return out;
}

From source file:org.egov.stms.notice.service.SewerageNoticeService.java

/**
 * @param inputStream/* w  w  w  .  ja  va 2  s. c  o m*/
 * @param noticeNo
 * @param out
 * @return zip output stream file
 */
public ZipOutputStream addFilesToZip(final InputStream inputStream, final String noticeNo,
        final ZipOutputStream out) {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Entered into addFilesToZip method");
    final byte[] buffer = new byte[1024];
    try {
        out.setLevel(Deflater.DEFAULT_COMPRESSION);
        out.putNextEntry(new ZipEntry(noticeNo.replaceAll("/", "_")));
        int len;
        while ((len = inputStream.read(buffer)) > 0)
            out.write(buffer, 0, len);
        inputStream.close();

    } catch (final IllegalArgumentException iae) {
        LOGGER.error(EXCEPTION_IN_ADD_FILES_TO_ZIP, iae);
        throw new ValidationException(Arrays.asList(new ValidationError("error", iae.getMessage())));
    } catch (final FileNotFoundException fnfe) {
        LOGGER.error(EXCEPTION_IN_ADD_FILES_TO_ZIP, fnfe);
        throw new ValidationException(Arrays.asList(new ValidationError("error", fnfe.getMessage())));
    } catch (final IOException ioe) {
        LOGGER.error(EXCEPTION_IN_ADD_FILES_TO_ZIP, ioe);
        throw new ValidationException(Arrays.asList(new ValidationError("error", ioe.getMessage())));
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Exit from addFilesToZip method");
    return out;
}

From source file:org.egov.wtms.web.controller.reports.GenerateConnectionBillController.java

private ZipOutputStream addFilesToZip(final InputStream inputStream, final String noticeNo,
        final ZipOutputStream out) {
    final byte[] buffer = new byte[1024];
    try {//w w w .  j a v a2s  .c  o m
        out.setLevel(Deflater.DEFAULT_COMPRESSION);
        out.putNextEntry(new ZipEntry(noticeNo.replaceAll("/", "_")));
        int len;
        while ((len = inputStream.read(buffer)) > 0)
            out.write(buffer, 0, len);
        inputStream.close();

    } catch (final IllegalArgumentException iae) {
        LOGGER.error("Exception in addFilesToZip : ", iae);
    } catch (final FileNotFoundException fnfe) {
        LOGGER.error("Exception in addFilesToZip : ", fnfe);
    } catch (final IOException ioe) {
        LOGGER.error("Exception in addFilesToZip : ", ioe);
    }
    return out;
}

From source file:org.egov.wtms.web.controller.reports.SearchNoticeController.java

private ZipOutputStream addFilesToZip(final InputStream inputStream, final String noticeNo,
        final ZipOutputStream out) {
    final byte[] buffer = new byte[1024];
    try {//w  ww.  j a va 2 s. c om
        out.setLevel(Deflater.DEFAULT_COMPRESSION);
        out.putNextEntry(new ZipEntry(noticeNo.replaceAll("/", "_")));
        int len;
        while ((len = inputStream.read(buffer)) > 0)
            out.write(buffer, 0, len);
        inputStream.close();

    } catch (final IllegalArgumentException iae) {
        LOGGER.error(EXCEPTION_IN_ADDFILESTOZIP, iae);
    } catch (final FileNotFoundException fnfe) {
        LOGGER.error(EXCEPTION_IN_ADDFILESTOZIP, fnfe);
    } catch (final IOException ioe) {
        LOGGER.error(EXCEPTION_IN_ADDFILESTOZIP, ioe);
    }
    return out;
}

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 {// w w w  . j  av  a2s .  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:org.jlibrary.core.jcr.modules.JCRImportExportModule.java

public void exportRepository(Ticket ticket, OutputStream stream)
        throws RepositoryNotFoundException, RepositoryException, SecurityException {

    try {// www  . j  av a 2s  .co  m
        javax.jcr.Session session = SessionManager.getInstance().getSession(ticket);
        if (session == null) {
            throw new RepositoryException("Session has expired. Please log in again.");
        }
        javax.jcr.Node root = JCRUtils.getRootNode(session);
        if (!JCRSecurityService.canRead(root, ticket.getUser().getId())) {
            throw new SecurityException(SecurityException.NOT_ENOUGH_PERMISSIONS);
        }

        // Create a temporary file with content
        File tempRoot = File.createTempFile("tmp", "jlib");
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(tempRoot);
            session.exportSystemView(JCRUtils.getRootNode(session).getPath(), fos, false, false);
        } finally {
            if (fos != null) {
                fos.close();
            }
        }

        // Will wrap compression around the given stream         
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(stream);
            zos.setComment("jLibrary ZIP archive");
            zos.setMethod(ZipOutputStream.DEFLATED);
            zos.setEncoding("UTF-8");
            zos.setLevel(Deflater.DEFAULT_COMPRESSION);

            // create and initialize a zipentry for it
            ZipEntry entry = new ZipEntry("jlibrary");
            entry.setTime(System.currentTimeMillis());
            zos.putNextEntry(entry);
            // write header
            String tag = String.valueOf(tempRoot.length()) + "*";
            byte[] header = tag.getBytes();
            zos.write(header);

            // write root
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(tempRoot);
                IOUtils.copy(fis, zos);
            } finally {
                if (fis != null) {
                    fis.close();
                }
            }
            // Delete root file
            tempRoot.delete();

            session.exportSystemView(JCRUtils.getSystemNode(session).getPath(), zos, false, false);
        } finally {
            if (zos != null) {
                zos.closeEntry();
                zos.close();
            }
        }

    } catch (PathNotFoundException e) {
        logger.error(e.getMessage(), e);
        throw new RepositoryException(e);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new RepositoryException(e);
    } catch (javax.jcr.RepositoryException e) {
        logger.error(e.getMessage(), e);
        throw new RepositoryException(e);
    }
}

From source file:org.jlibrary.core.jcr.modules.JCRImportExportModule.java

/**
 * Zips a given file or directory//from   w ww  .jav  a 2  s  .  c o m
 * 
 * @param byte[] content to zip
 * 
 * @return byte[] zipped content
 * 
 * @throws IOException If the zip content can't be created
 */
private byte[] zipContent(byte[] content) throws IOException {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);

    zos.setComment("jLibrary ZIP archive");
    zos.setMethod(ZipOutputStream.DEFLATED);
    zos.setEncoding("UTF-8");
    zos.setLevel(Deflater.DEFAULT_COMPRESSION);

    // create and initialize a zipentry for it
    ZipEntry entry = new ZipEntry("jlibrary");
    entry.setTime(System.currentTimeMillis());
    zos.putNextEntry(entry);
    zos.write(content);
    zos.closeEntry();

    zos.close();
    baos.close();

    return baos.toByteArray();
}