Example usage for java.util.zip DeflaterOutputStream DeflaterOutputStream

List of usage examples for java.util.zip DeflaterOutputStream DeflaterOutputStream

Introduction

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

Prototype

public DeflaterOutputStream(OutputStream out) 

Source Link

Document

Creates a new output stream with a default compressor and buffer size.

Usage

From source file:com.apporiented.hermesftp.cmd.AbstractFtpCmdRetr.java

private OutputStream createOutputStream(OutputStream dataOut, int mode, String charset)
        throws UnsupportedEncodingException {
    OutputStream result = null;// w w w .j  av  a  2  s  .c o  m
    if (mode == MODE_BLOCK) {
        result = new BlockModeOutputStream(dataOut);
    } else if (mode == MODE_STREAM) {
        result = dataOut;
    } else if (mode == MODE_ZIP) {
        result = new DeflaterOutputStream(dataOut);
    } else {
        log.error("Unsupported file mode: " + mode);
    }
    if (charset != null) {
        result = new TextOutputStream(result, charset);
    }
    return result;
}

From source file:de.tntinteractive.portalsammler.engine.SecureStore.java

private byte[] compress(final byte[] content) throws IOException {
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    final DeflaterOutputStream deflate = new DeflaterOutputStream(buffer);
    deflate.write(content);//from w w  w.ja  v a  2 s .  c o  m
    deflate.close();
    return buffer.toByteArray();
}

From source file:com.cloud.agent.api.SecurityGroupRulesCmd.java

public String compressStringifiedRules() {
    StringBuilder ruleBuilder = new StringBuilder();
    for (SecurityGroupRulesCmd.IpPortAndProto ipPandP : getIngressRuleSet()) {
        ruleBuilder.append("I:").append(ipPandP.getProto()).append(":").append(ipPandP.getStartPort())
                .append(":").append(ipPandP.getEndPort()).append(":");
        for (String cidr : ipPandP.getAllowedCidrs()) {
            ruleBuilder.append(cidr).append(",");
        }//from   w  ww . j a  v  a2 s  .  c  om
        ruleBuilder.append("NEXT");
        ruleBuilder.append(" ");
    }
    for (SecurityGroupRulesCmd.IpPortAndProto ipPandP : getEgressRuleSet()) {
        ruleBuilder.append("E:").append(ipPandP.getProto()).append(":").append(ipPandP.getStartPort())
                .append(":").append(ipPandP.getEndPort()).append(":");
        for (String cidr : ipPandP.getAllowedCidrs()) {
            ruleBuilder.append(cidr).append(",");
        }
        ruleBuilder.append("NEXT");
        ruleBuilder.append(" ");
    }
    String stringified = ruleBuilder.toString();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        //Note : not using GZipOutputStream since that is for files
        //GZipOutputStream gives a different header, although the compression is the same
        DeflaterOutputStream dzip = new DeflaterOutputStream(out);
        dzip.write(stringified.getBytes());
        dzip.close();
    } catch (IOException e) {
        s_logger.warn("Exception while compressing security group rules");
        return null;
    }
    return Base64.encodeBase64String(out.toByteArray());
}

From source file:com.apporiented.hermesftp.cmd.AbstractFtpCmdRetr.java

private RecordWriteSupport createRecOutputStream(OutputStream dataOut, int mode, String charset)
        throws UnsupportedEncodingException {
    RecordWriteSupport result = null;/* w w  w.j a  va  2  s.c om*/
    if (mode == MODE_BLOCK) {
        result = new BlockModeOutputStream(dataOut);
    } else if (mode == MODE_STREAM) {
        result = new RecordOutputStream(dataOut);
    } else if (mode == MODE_ZIP) {
        result = new RecordOutputStream(new DeflaterOutputStream(dataOut));
    } else {
        log.error("Unsupported record mode: " + mode);
    }
    if (charset != null) {
        result = new TextOutputStream((OutputStream) result, charset);
    }
    return result;
}

From source file:org.fejoa.library.database.CSRepositoryBuilder.java

static private IChunkAccessor getEncryptionChunkAccessor(final FejoaContext context,
        final ChunkStore.Transaction transaction, final SymmetricKeyData keyData, final ChunkContainerRef ref) {
    return new IChunkAccessor() {
        final ICryptoInterface cryptoInterface = context.getCrypto();

        private byte[] getIv(byte[] hashValue) {
            final int ivSizeBytes = keyData.settings.ivSize / 8;
            byte[] iv = Arrays.copyOfRange(hashValue, 0, ivSizeBytes);
            // xor with the base IV
            for (int i = 0; i < ivSizeBytes; i++)
                iv[i] = (byte) (keyData.iv[i] ^ iv[i]);
            return iv;
        }/*  w  w  w.ja  v a2s .  com*/

        @Override
        public DataInputStream getChunk(ChunkPointer hash) throws IOException, CryptoException {
            byte[] iv = getIv(hash.getIV());
            byte[] chunkData = transaction.getChunk(hash.getBoxHash());
            if (chunkData == null)
                throw new IOException("Chunk not found: " + hash.getBoxHash());
            InputStream inputStream = new ByteArrayInputStream(chunkData);
            inputStream = cryptoInterface.decryptSymmetric(inputStream, keyData.key, iv, keyData.settings);
            if (ref.getBoxHeader().getCompressionType() == BoxHeader.CompressionType.ZLIB_COMPRESSION)
                inputStream = new InflaterInputStream(inputStream);
            return new DataInputStream(inputStream);
        }

        @Override
        public PutResult<HashValue> putChunk(byte[] data, HashValue ivHash)
                throws IOException, CryptoException {
            ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
            OutputStream outputStream = byteOutputStream;
            outputStream = cryptoInterface.encryptSymmetric(outputStream, keyData.key, getIv(ivHash.getBytes()),
                    keyData.settings);
            if (ref.getBoxHeader().getCompressionType() == BoxHeader.CompressionType.ZLIB_COMPRESSION)
                outputStream = new DeflaterOutputStream(outputStream);
            outputStream.write(data);
            outputStream.close();
            return transaction.put(byteOutputStream.toByteArray());
        }

        @Override
        public void releaseChunk(HashValue data) {

        }
    };
}

From source file:org.ozsoft.xantippe.Document.java

/**
 * Sets the document's content based on a file.
 * /*from w w  w . jav  a 2  s  .c  o m*/
 * In case of an XML document and depending on the validation mode of the
 * collection, the document may be validated against its schema before it
 * is stored.
 * 
 * In case of a schema it is parsed and registered by its target namespace.
 * 
 * Depending on the compression mode of the collection, the document may be
 * stored in compressed form.
 *  
 * @param   file  the file with the document's content
 * 
 * @throws  IllegalArgumentException  if the file is null 
 * 
 * @throws  XmldbException
 *              if the file does not exist, could not be read or parsed, or
 *              the document could not be compressed or stored
 */
public void setContent(File file) throws XmldbException {
    if (file == null) {
        throw new IllegalArgumentException("Null file");
    }

    if (!file.isFile()) {
        String msg = "File not found: " + file;
        LOG.error(msg);
        throw new XmldbException(msg);
    }

    if (!file.canRead()) {
        String msg = "No read permission on file: " + file;
        LOG.error(msg);
        throw new XmldbException(msg);
    }

    Collection parentCol = getParent();

    if (mediaType == MediaType.XML) {
        String uri = getUri();
        ValidationMode vm = parentCol.getValidationMode(true);
        switch (vm) {
        case ON:
            // Validate document against mandatory schema. 
            database.getValidator().validate(file, uri, true);
            break;
        case AUTO:
            // Validate document if possible (namespace and schema).
            database.getValidator().validate(file, uri, false);
            break;
        case OFF:
            // No validation.
            break;
        default:
            // Should never happen.
            LOG.error("Invalid validation mode: " + vm);
        }
    } else if (mediaType == MediaType.SCHEMA) {
        try {
            database.getValidator().addSchema(file, id);
        } catch (Exception e) {
            String msg = String.format("Invalid schema file: '%s': %s", file, e.getMessage());
            LOG.error(msg);
            throw new XmldbException(msg);
        }
    }

    // Use compression mode as configured for collection.
    compressionMode = parentCol.getCompressionMode(true);

    File storedFile = null;

    try {
        if (compressionMode != CompressionMode.NONE) {
            // Compress document to a temporary file.
            storedFile = File.createTempFile("xantippe-", null);
            OutputStream os;
            if (compressionMode == CompressionMode.DEFLATE) {
                os = new DeflaterOutputStream(new FileOutputStream(storedFile));
            } else {
                // Should never happen.
                String msg = "Invalid compression mode: " + compressionMode;
                LOG.error(msg);
                throw new XmldbException(msg);
            }
            InputStream is = new FileInputStream(file);
            byte[] buffer = new byte[BUFFER_SIZE];
            int read;
            while ((read = is.read(buffer)) > 0) {
                os.write(buffer, 0, read);
            }
            os.close();
            is.close();
        } else {
            // No compression; store document as-is.
            storedFile = file;
        }

        database.getLockManager().lockWrite(this);

        database.getFileStore().store(id, storedFile);

        if (mediaType == MediaType.XML) {
            parentCol.indexDocument(this, file);
        }

        length = (int) file.length();

        updateModified();

    } catch (IOException e) {
        String msg = String.format("Error while compressing document '%s': %s", this, e.getMessage());
        LOG.error(msg, e);
        throw new XmldbException(msg, e);

    } catch (FileStoreException e) {
        String msg = String.format("Error while storing document '%s': %s", this, e.getMessage());
        LOG.error(msg, e);
        throw new XmldbException(msg, e);

    } finally {
        database.getLockManager().unlockWrite(this);

        if (compressionMode != CompressionMode.NONE && storedFile != null) {
            // Always clean up temporary (compressed) file.
            storedFile.delete();
        }
    }
}

From source file:org.diorite.nbt.NbtOutputStream.java

/**
 * Create new deflated nbt output stream for given file, and write nbt tag to it.
 *
 * @param tag    nbt tag to write.//from   w  w w . j av a  2  s . c  o m
 * @param file   data file to be used.
 * @param append if new data should be appended to existing one.
 *
 * @return created NbtOutputStream.
 *
 * @throws IOException if any write operation failed.
 */
public static NbtOutputStream writeDeflated(final NbtTag tag, final File file, final boolean append)
        throws IOException {
    createFile(file);
    final NbtOutputStream out = new NbtOutputStream(
            new DeflaterOutputStream(new FileOutputStream(file, append)));
    out.write(tag);
    return out;
}

From source file:de.tntinteractive.portalsammler.engine.SecureStore.java

private MapWriter createMapWriterAndWriteSalt(final OutputStream out, final int salt) throws IOException {
    final OutputStream cipher = CryptoHelper.createAesEncryptStream(out, this.key, this.srand);
    writeInt(cipher, salt);//from   w w  w .  j  av a2s.  c o  m

    final DeflaterOutputStream deflate = new DeflaterOutputStream(cipher);
    final MapWriter w = MapWriter.createFor(deflate);
    return w;
}

From source file:org.apache.pdfbox.filter.FlateFilter.java

/**
 * {@inheritDoc}//from w w  w. ja  v a2s  . c om
 */
public void encode(InputStream rawData, OutputStream result, COSDictionary options, int filterIndex)
        throws IOException {
    DeflaterOutputStream out = new DeflaterOutputStream(result);
    int amountRead = 0;
    int mayRead = rawData.available();
    if (mayRead > 0) {
        byte[] buffer = new byte[Math.min(mayRead, BUFFER_SIZE)];
        while ((amountRead = rawData.read(buffer, 0, Math.min(mayRead, BUFFER_SIZE))) != -1) {
            out.write(buffer, 0, amountRead);
        }
    }
    out.close();
    result.flush();
}

From source file:org.candlepin.pinsetter.tasks.HypervisorUpdateJob.java

public static byte[] compress(String text) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {// w  w w.j a va  2s  .c  o  m
        OutputStream out = new DeflaterOutputStream(baos);
        out.write(text.getBytes("UTF-8"));
        out.close();
    } catch (IOException e) {
        throw new AssertionError(e);
    }
    return baos.toByteArray();
}