Example usage for java.util.zip Deflater BEST_COMPRESSION

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

Introduction

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

Prototype

int BEST_COMPRESSION

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

Click Source Link

Document

Compression level for best compression.

Usage

From source file:org.sigmah.server.file.impl.BackupArchiveJob.java

/**
 * {@inheritDoc}/*from ww w  . j  a v a2s .c  o  m*/
 */
@Override
public void run() {

    final Path tempArchiveFile = arguments.tempArchiveFile;
    final Path finalArchiveFile = arguments.finalArchiveFile;

    try (final ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(
            Files.newOutputStream(tempArchiveFile))) {

        zipOutputStream.setMethod(ZipOutputStream.DEFLATED);
        zipOutputStream.setLevel(Deflater.BEST_COMPRESSION);

        final RepositoryElement repository = buildOrgUnitRepository(arguments.backup, arguments.userId);
        repository.setName("");

        zipRepository(repository, zipOutputStream, "");

        // TODO Delete existing previous organization file(s).

        // Renames temporary '.tmp' file to complete '.zip' file.
        Files.move(tempArchiveFile, finalArchiveFile, StandardCopyOption.REPLACE_EXISTING);

    } catch (final Throwable t) {

        if (LOG.isErrorEnabled()) {
            LOG.error("An error occurred during backup archive generation process.", t);
        }

        try {

            Files.deleteIfExists(tempArchiveFile);
            Files.deleteIfExists(finalArchiveFile);

        } catch (final IOException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("An error occurred while deleting archive error file.", e);
            }
        }
    }
}

From source file:fr.smile.alfresco.module.panier.scripts.SmilePanierExportZipWebScript.java

@Override
public void execute(WebScriptRequest request, WebScriptResponse res) throws IOException {

    String userName = AuthenticationUtil.getFullyAuthenticatedUser();

    PersonService personService = services.getPersonService();

    NodeRef userNodeRef = personService.getPerson(userName);

    MimetypeService mimetypeService = services.getMimetypeService();
    FileFolderService fileFolderService = services.getFileFolderService();

    Charset archiveEncoding = Charset.forName("ISO-8859-1");

    String encoding = request.getParameter("encoding");

    if (StringUtils.isNotEmpty(encoding)) {
        archiveEncoding = Charset.forName(encoding);
    }/*from ww  w .  ja  v a2 s  .  com*/

    ZipOutputStream fileZip = new ZipOutputStream(res.getOutputStream(), archiveEncoding);
    String folderName = "mon_panier";
    try {

        String zipFileExtension = "." + mimetypeService.getExtension(MimetypeMap.MIMETYPE_ZIP);

        res.setContentType(MimetypeMap.MIMETYPE_ZIP);

        res.setHeader("Content-Transfer-Encoding", "binary");
        res.addHeader("Content-Disposition",
                "attachment;filename=\"" + normalizeZipFileName(folderName) + zipFileExtension + "\"");

        res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        res.setHeader("Pragma", "public");
        res.setHeader("Expires", "0");

        fileZip.setMethod(ZipOutputStream.DEFLATED);
        fileZip.setLevel(Deflater.BEST_COMPRESSION);

        String archiveRootPath = folderName + "/";

        List<NodeRef> list = smilePanierService.getSelection(userNodeRef);
        List<FileInfo> filesInfos = new ArrayList<FileInfo>();
        for (int i = 0; i < list.size(); i++) {
            FileInfo fileInfo = fileFolderService.getFileInfo(list.get(i));
            filesInfos.add(fileInfo);
        }

        for (FileInfo file : filesInfos) {
            addEntry(file, fileZip, archiveRootPath);
        }
        fileZip.closeEntry();

    } catch (Exception e) {
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Erreur exportation Zip", e);
    } finally {
        fileZip.close();
    }

}

From source file:fr.gael.dhus.service.job.SendLogsJob.java

@Override
protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
    if (!configurationManager.getSendLogsCronConfiguration().isActive())
        return;//w  ww. jav  a  2 s.  c  o m
    long start = System.currentTimeMillis();
    logger.info("SCHEDULER : Send Administrative logs.");
    if (!DHuS.isStarted()) {
        logger.warn("SCHEDULER : Not run while system not fully initialized.");
        return;
    }

    String[] addresses = configurationManager.getSendLogsCronConfiguration().getAddresses().split(",");
    // Case of no addresses available: use system support
    if ((addresses == null) || (addresses.length == 0) || "".equals(addresses[0].trim())) {
        String email = configurationManager.getSupportConfiguration().getMail();
        if ((email == null) || "".equals(email)) {
            throw new MailException("Support e-mail not configured, " + "system logs will not be send");
        }
        addresses = new String[] { email };
    }

    RollingFileAppender rollingFileAppender = (RollingFileAppender) ((org.apache.logging.log4j.core.Logger) LogManager
            .getRootLogger()).getAppenders().get("RollingFile");
    if (rollingFileAppender == null) {
        throw new MailException("No rolling log file defined");
    }

    String logPath = rollingFileAppender.getFileName();

    if ((logPath == null) || logPath.trim().equals("")) {
        throw new MailException("Log file not defined");
    }

    File logs = new File(logPath);
    if (!logs.exists()) {
        throw new MailException("Log file not present : " + logs.getPath());
    }

    Date now = new Date();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'@'HH:mm:ss");
    df.setTimeZone(TimeZone.getTimeZone("GMT"));
    String docFilename = configurationManager.getNameConfiguration().getShortName().toLowerCase() + "-"
            + df.format(now);

    File zipLogs;
    try {
        zipLogs = File.createTempFile(docFilename, ".zip");
    } catch (IOException e) {
        throw new MailException("Cannot create temporary zip log file.", e);
    }

    // compress logs file to zip format
    FileOutputStream fos;
    ZipOutputStream zos = null;
    FileInputStream fis = null;
    try {
        int length;
        byte[] buffer = new byte[1024];
        ZipEntry entry = new ZipEntry(docFilename + ".txt");

        fos = new FileOutputStream(zipLogs);
        zos = new ZipOutputStream(fos);
        fis = new FileInputStream(logs);

        zos.setLevel(Deflater.BEST_COMPRESSION);
        zos.putNextEntry(entry);
        while ((length = fis.read(buffer)) > 0) {
            zos.write(buffer, 0, length);
        }
    } catch (IOException e) {
        throw new MailException("An error occurred during compression " + "logs file, cannot send logs !", e);
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            if (zos != null) {
                zos.closeEntry();
                zos.close();
            }
        } catch (IOException e) {
            throw new MailException("An error occurred during compression " + "logs file, cannot send logs !",
                    e);
        }
    }

    EmailAttachment attachment = new EmailAttachment();
    attachment.setDescription(
            configurationManager.getNameConfiguration().getShortName() + " Logs " + now.toString());
    attachment.setPath(zipLogs.getPath());
    attachment.setName(zipLogs.getName());

    // Prepare the addresses
    List<String> ads = new ArrayList<String>();
    for (String email : addresses) {
        StringTokenizer tk = new StringTokenizer(email, ", ");
        while (tk.hasMoreTokens()) {
            String token = tk.nextToken().trim();
            if (!token.isEmpty())
                ads.add(token);
        }
    }
    for (String email : ads) {
        try {
            String server = configurationManager.getServerConfiguration().getExternalHostname();
            String url = configurationManager.getServerConfiguration().getExternalUrl();

            mailServer.send(email, null, null,
                    "[" + configurationManager.getNameConfiguration().getShortName().toLowerCase() + "@"
                            + server + "] logs of " + df.format(now),
                    "Here is attached " + configurationManager.getNameConfiguration().getShortName()
                            + " logs of \"" + url + "\" host.\n\n" + "Kind Regards.\nThe "
                            + configurationManager.getNameConfiguration().getShortName() + " Team.",
                    attachment);
            logger.info("Logs Sent to " + email);
        } catch (EmailException e) {
            throw new MailException("Cannot send logs to " + email, e);
        }
    }

    if (!zipLogs.delete()) {
        logger.warn("Cannot remove mail attachment: " + zipLogs.getAbsolutePath());
    }

    logger.info("SCHEDULER : Send Administrative logs done - " + (System.currentTimeMillis() - start) + "ms");
}

From source file:org.asimba.wa.integrationtest.saml2.model.AuthnRequest.java

/**
 * Get String with the SAML2 AuthnRequest message
 * @param format -1=plain, 1=base64//from w w w  .j  a  v a2 s.  c  om
 * @return
 * @throws XMLStreamException
 * @throws IOException
 */
public String getRequest(int format) throws XMLStreamException, IOException {
    _logger.info("For ID: " + this._id);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Deflater compresser = new Deflater(Deflater.BEST_COMPRESSION, true);
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(baos, compresser);
    StringWriter sw = new StringWriter();

    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    XMLStreamWriter writer = null;

    // ugly but effective:
    if (format == base64) {
        writer = factory.createXMLStreamWriter(deflaterOutputStream);
    } else {
        writer = factory.createXMLStreamWriter(sw);
    }

    writer.writeStartElement("samlp", "AuthnRequest", "urn:oasis:names:tc:SAML:2.0:protocol");
    writer.writeNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol");

    writer.writeAttribute("ID", _id);
    writer.writeAttribute("Version", "2.0");
    writer.writeAttribute("IssueInstant", this._issueInstant);
    writer.writeAttribute("ProtocolBinding", "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
    writer.writeAttribute("AssertionConsumerServiceURL", _acsUrl);

    writeIssuer(writer);

    writeNameIDPolicy(writer);

    writeRequestedAuthnContext(writer);

    writer.writeEndElement();
    writer.flush();

    if (format == base64) {
        deflaterOutputStream.close();
        byte[] bain = baos.toByteArray();
        byte[] encoded = Base64.encodeBase64(bain, false);
        String result = new String(encoded, Charset.forName("UTF-8"));

        return result;
    } else {
        return sw.toString();
    }

}

From source file:de.tudarmstadt.lt.n2n.annotators.JoBimPrinter.java

private void openPrintToFileStream() throws IOException {
    OutputStream os = new FileOutputStream(_printstream_as_string, true);
    if (_printstream_as_string.endsWith(".gz"))
        os = new GZIPOutputStream(os) {
            {// w  ww  . jav a2  s  .  c  o m
                def.setLevel(Deflater.BEST_COMPRESSION);
            }
        };
    _printstream = new PrintStream(os);
    _printstream.flush();
    _prints_to_sys = false;
}

From source file:com.threerings.cast.bundle.tools.MetadataBundlerTask.java

/**
 * Creates the base output stream to which to write our bundle's files.
 *///  w ww  .  ja  v  a2s  .com
protected OutputStream createOutputStream(File target) throws IOException {
    JarOutputStream jout = new JarOutputStream(new FileOutputStream(target));
    jout.setLevel(Deflater.BEST_COMPRESSION);
    return jout;
}

From source file:ch.randelshofer.cubetwister.HTMLExporter.java

public void exportToDirectory(String documentName, DocumentModel model, File dir, ProgressObserver p)
        throws IOException {
    this.documentName = documentName;
    this.model = model;
    this.dir = dir;
    this.zipFile = null;
    this.p = p;//www  .ja v  a 2  s .c  o  m
    init();
    processHTMLTemplates(p);
    new File(dir, "applets").mkdir();
    ZipOutputStream zout = new ZipOutputStream(
            new BufferedOutputStream(new FileOutputStream(new File(dir, "applets/resources.xml.zip"))));
    zout.setLevel(Deflater.BEST_COMPRESSION);
    try {
        //model.writeXML(new PrintWriter(new File(dir, "applets/resources.xml")));
        zout.putNextEntry(new ZipEntry("resources.xml"));
        PrintWriter pw = new PrintWriter(zout);
        model.writeXML(pw);
        pw.flush();
        zout.closeEntry();
    } finally {
        zout.close();
    }
    p.setProgress(p.getProgress() + 1);
}

From source file:fr.eo.util.dumper.Dumper.java

private static String getCompressedString(String value) {

    byte[] output = new byte[8096];

    try {//from w w  w.  j av a2s .  c  om
        byte[] input = value.getBytes("UTF-8");
        Deflater compresser = new Deflater(Deflater.BEST_COMPRESSION, true);
        compresser.setInput(input);
        compresser.finish();
        int compressedDataLength = compresser.deflate(output);
        return "X'" + Hex.encodeHexString(Arrays.copyOf(output, compressedDataLength)) + "'";
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.tremolosecurity.proxy.auth.saml2.Saml2SingleLogout.java

@Override
public void handleLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    if (request == null || response == null) {
        //do nothing
        return;// w  w w .j  a  va  2  s  .  com
    }

    String xmlAlg = SAML2Auth.xmlDigSigAlgs.get(digSigAlg);

    if (xmlAlg == null) {
        throw new ServletException("Unknown Signiture algorithm : '" + digSigAlg + "'");
    }

    String javaAlg = SAML2Auth.javaDigSigAlgs.get(digSigAlg);

    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);

    ConfigManager cfgMgr = holder.getConfig();

    LogoutRequestBuilder lrb = new LogoutRequestBuilder();
    LogoutRequest lr = lrb.buildObject();

    DateTime dt = new DateTime();
    lr.setIssueInstant(dt);

    lr.setDestination(logoutURL);

    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);

    String id = "f" + Hex.encodeHexString(idBytes);
    lr.setID(id);

    IssuerBuilder ib = new IssuerBuilder();
    Issuer issuer = ib.buildObject();
    issuer.setValue(assertionConsumerServiceURL);
    lr.setIssuer(issuer);

    NameIDBuilder nidbpb = new NameIDBuilder();
    NameID nid = nidbpb.buildObject();
    //nidp.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified");
    nid.setFormat(nameIDFormat);

    //nid.setSPNameQualifier(assertionConsumerServiceURL);
    nid.setValue(nameID);
    lr.setNameID(nid);

    SessionIndexBuilder sib = new SessionIndexBuilder();
    SessionIndex si = sib.buildObject();
    si.setSessionIndex(sessionIndex);
    lr.getSessionIndexes().add(si);

    try {
        // Get the Subject marshaller
        Marshaller marshaller = new LogoutRequestMarshaller();

        // Marshall the Subject
        //Element assertionElement = marshaller.marshall(lr);

        String xml = OpenSAMLUtils.xml2str(lr);
        xml = xml.substring(xml.indexOf("?>") + 2);

        if (logger.isDebugEnabled()) {
            logger.debug("=======AuthnRequest============");
            logger.debug(xml);
            logger.debug("=======AuthnRequest============");
        }

        byte[] bxml = xml.getBytes("UTF-8");

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        DeflaterOutputStream compressor = new DeflaterOutputStream(baos,
                new Deflater(Deflater.BEST_COMPRESSION, true));

        compressor.write(bxml);
        compressor.flush();
        compressor.close();

        String b64 = new String(Base64.encodeBase64(baos.toByteArray()));
        StringBuffer redirURL = new StringBuffer();
        StringBuffer query = new StringBuffer();

        idBytes = new byte[20];
        random.nextBytes(idBytes);

        query.append("SAMLRequest=").append(URLEncoder.encode(b64, "UTF-8")).append("&RelayState=")
                .append(URLEncoder.encode(Hex.encodeHexString(idBytes), "UTF-8"));

        query.append("&SigAlg=").append(URLEncoder.encode(xmlAlg, "UTF-8"));
        //http://www.w3.org/2000/09/xmldsig#rsa-sha1

        java.security.Signature signer = java.security.Signature.getInstance(javaAlg);

        PrivateKey sigKey = cfgMgr.getPrivateKey(signingKeyAlias);

        if (sigKey == null) {
            throw new ServletException("Signing Key : '" + signingKeyAlias + "' not found");
        }

        signer.initSign(sigKey);
        signer.update(query.toString().getBytes("UTF-8"));
        String base64Sig = new String(Base64.encodeBase64(signer.sign()));
        query.append("&Signature=").append(URLEncoder.encode(base64Sig, "UTF-8"));

        redirURL.append(logoutURL).append("?").append(query.toString());

        if (logger.isDebugEnabled()) {
            logger.debug("Logout URL : '" + redirURL.toString() + "'");
        }

        //((ProxyResponse) response).removeHeader("Location");
        response.sendRedirect(redirURL.toString());

    } catch (Exception e) {
        throw new ServletException("Could not generate logout request", e);
    }

}

From source file:net.yacy.crawler.data.CacheTest.java

/**
 * Run a stress test on the Cache//  www  . j  av a2s  .  c om
 * 
 * @param args
 *            main arguments
 * @throws IOException
 *             when a error occurred
 */
public static void main(final String args[]) throws IOException {
    System.out.println("Stress test on Cache");

    /*
     * Set the root log level to WARNING to prevent filling the console with
     * too many information log messages
     */
    LogManager.getLogManager().readConfiguration(
            new ByteArrayInputStream(".level=WARNING".getBytes(StandardCharsets.ISO_8859_1)));

    /* Main control parameters. Modify values for different scenarios. */

    /* Number of concurrent test tasks */
    final int threads = 50;
    /* Number of steps in each task */
    final int steps = 10;
    /* Number of test URLs in each task */
    final int urlsPerThread = 5;
    /* Size of the generated test content */
    final int contentSize = Math.max(Cache.DEFAULT_COMPRESSOR_BUFFER_SIZE + 1,
            Cache.DEFAULT_BACKEND_BUFFER_SIZE + 1) / urlsPerThread;
    /* Cache maximum size */
    final long cacheMaxSize = Math.min(1024 * 1024 * 1024, ((long) contentSize) * 10 * urlsPerThread);
    /* Sleep time between each cache operation */
    final long sleepTime = 0;
    /* Maximum waiting time (in ms) for acquiring a synchronization lock */
    final long lockTimeout = 2000;
    /* The backend compression level */
    final int compressionLevel = Deflater.BEST_COMPRESSION;

    Cache.init(new File(System.getProperty("java.io.tmpdir") + File.separator + "yacyTestCache"), "peerSalt",
            cacheMaxSize, lockTimeout, compressionLevel);
    Cache.clear();
    System.out.println("Cache initialized with a maximum size of " + cacheMaxSize + " bytes.");

    try {
        System.out.println("Starting " + threads + " threads ...");
        long time = System.nanoTime();
        List<CacheAccessTask> tasks = new ArrayList<>();
        for (int count = 0; count < threads; count++) {
            List<DigestURL> urls = new ArrayList<>();
            for (int i = 0; i < urlsPerThread; i++) {
                urls.add(new DigestURL("http://yacy.net/" + i + "/" + count));
            }
            CacheAccessTask thread = new CacheAccessTask(urls, steps, contentSize, sleepTime);
            thread.start();
            tasks.add(thread);
        }
        /* Wait for tasks termination */
        for (CacheAccessTask task : tasks) {
            try {
                task.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        /*
         * Check consistency : cache should be empty when all tasks have
         * terminated without error
         */
        Cache.commit();
        long docCount = Cache.getActualCacheDocCount();
        if (docCount > 0) {
            System.out.println("Cache is not empty!!! Actual documents count : " + docCount);
        }

        System.out.println("All threads terminated in "
                + TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - time) + "s. Computing statistics...");
        long storeTime = 0;
        long maxStoreTime = 0;
        long getContentTime = 0;
        long maxGetContentTime = 0;
        int storeFailures = 0;
        long deleteTime = 0;
        long maxDeleteTime = 0;
        long totalSteps = 0;
        for (CacheAccessTask task : tasks) {
            storeTime += task.getStoreTime();
            maxStoreTime = Math.max(task.getMaxStoreTime(), maxStoreTime);
            getContentTime += task.getGetContentTime();
            maxGetContentTime = Math.max(task.getMaxGetContentTime(), maxGetContentTime);
            storeFailures += task.getStoreFailures();
            deleteTime += task.getDeleteTime();
            maxDeleteTime = Math.max(task.getMaxDeleteTime(), maxDeleteTime);
            totalSteps += task.getSteps();
        }
        System.out.println("Cache.store() total time (ms) : " + TimeUnit.NANOSECONDS.toMillis(storeTime));
        System.out.println("Cache.store() maximum time (ms) : " + TimeUnit.NANOSECONDS.toMillis(maxStoreTime));
        System.out.println(
                "Cache.store() mean time (ms) : " + TimeUnit.NANOSECONDS.toMillis(storeTime / totalSteps));
        System.out.println("Cache.store() failures : " + storeFailures);
        System.out.println("");
        System.out.println(
                "Cache.getContent() total time (ms) : " + TimeUnit.NANOSECONDS.toMillis(getContentTime));
        System.out.println(
                "Cache.getContent() maximum time (ms) : " + TimeUnit.NANOSECONDS.toMillis(maxGetContentTime));
        System.out.println("Cache.getContent() mean time (ms) : "
                + TimeUnit.NANOSECONDS.toMillis(getContentTime / totalSteps));
        System.out.println("Cache hits : " + Cache.getHits() + " total requests : " + Cache.getTotalRequests()
                + " ( hit rate : " + NumberFormat.getPercentInstance().format(Cache.getHitRate()) + " )");
        System.out.println("");
        System.out.println("Cache.delete() total time (ms) : " + TimeUnit.NANOSECONDS.toMillis(deleteTime));
        System.out
                .println("Cache.delete() maximum time (ms) : " + TimeUnit.NANOSECONDS.toMillis(maxDeleteTime));
        System.out.println(
                "Cache.delete() mean time (ms) : " + TimeUnit.NANOSECONDS.toMillis(deleteTime / totalSteps));
    } finally {
        try {
            Cache.close();
        } finally {
            /* Shutdown running threads */
            ArrayStack.shutdownDeleteService();
            try {
                Domains.close();
            } finally {
                ConcurrentLog.shutdown();
            }
        }
    }

}