Package Framework.compression

Source Code of Framework.compression.CompressionHelper

/*
Copyright (c) 2003-2008 ITerative Consulting Pty Ltd. All Rights Reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:

o Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
 
o Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the distribution.
   
o This jcTOOL Helper Class software, whether in binary or source form may not be used within,
or to derive, any other product without the specific prior written permission of the copyright holder

 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


*/
package Framework.compression;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

import org.apache.log4j.Logger;

import Framework.ErrorMgr;

/**
* This class contains helper methods that compress and uncompress data via ObjectInput
* and ObjectOutput streams. The compression is performed using a Deflator once the size
* of the data exceeds a particular threshold.
* @author tfaulkes
*
*/
public class CompressionHelper {
    public static final int cUncompressedDataLimit = 500;
    private static Logger _log = Logger.getLogger(CompressionHelper.class);
    private static ByteArrayInputStream readUncompressed(ObjectInput in) throws IOException {
        int len = in.readInt();
        byte[] bytes = new byte[len];
        in.readFully(bytes);
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        bytes = null;
        return bais;
    }

    private static ByteArrayInputStream readCompressed(ObjectInput in) throws IOException {
        ByteArrayInputStream bais;
        int compressedDataLength = in.readInt();
        int uncompressedDataLength = in.readInt();

        byte[] compressedData = new byte[compressedDataLength];
        byte[] uncompressedData = new byte[uncompressedDataLength];

        // Read the data into the full array
        in.readFully(compressedData);

        Inflater inflater = new Inflater();
        inflater.setInput(compressedData);
        int uncompressedLen;
        try {
            uncompressedLen = inflater.inflate(uncompressedData);
        }
        catch (DataFormatException e) {
            _log.error("Problem decompressing byte stream", e);
            IOException errorVar = new IOException(e.getMessage());
            ErrorMgr.addError(errorVar);
            throw errorVar;
        }
        inflater.end();
        bais = new ByteArrayInputStream(uncompressedData);
        compressedData = null;
        uncompressedData = null;
        if (_log.isInfoEnabled()) {
            _log.info("Inflated input stream from " + compressedDataLength + " bytes to " + uncompressedLen + " bytes.");
            if (uncompressedDataLength != uncompressedLen) {
                _log.info("*** Warning: Expected " + uncompressedDataLength + " bytes when uncompressed, received " + uncompressedLen);
            }
        }
        return bais;
    }

    public static ObjectInputStream getObjectInputStream(ObjectInput in) throws IOException {
        boolean isCompressed = in.readBoolean();
        if (isCompressed) {
            return new ObjectInputStream(CompressionHelper.readCompressed(in));
        }
        else {
            return new ObjectInputStream(CompressionHelper.readUncompressed(in));
        }
    }

    public static void writeToObjectOutputStream(ObjectOutput pOut, byte[] pByteArray) throws IOException {
        if (pByteArray.length <= cUncompressedDataLimit) {
            CompressionHelper.writeUncompressed(pOut, pByteArray);
        }
        else {
            CompressionHelper.writeCompressed(pOut, pByteArray);
        }
        // TF:17/2/08: Flush the output buffer, so that the output ObjectOutput is ready to go with no
        // issues. If we fail to do this and the buffer is read immediately, the read stream will not
        // be the full output and hence will fail to de-compress. (Note however that this is the normal
        // behaviour of streams...)
        pOut.flush();
    }

    /**
     * Write the passed array of bytes to the passed output stream, uncompressed.
     * @param pOut the stream to receive the bytes
     * @param pByteArray the the bytes to pass to the stream
     * @throws IOException
     */
    private static void writeUncompressed(ObjectOutput pOut, byte []pByteArray) throws IOException {
        // First write a flag to indicate whether the stream is compressed or not
        pOut.writeBoolean(false);

        // Now the length of the data
        pOut.writeInt(pByteArray.length);

        // Now the data
        pOut.write(pByteArray, 0, pByteArray.length);
    }

    /**
     * Write the passed array of bytes to the passed output stream, compressed using a Deflater
     * @param pOut the stream to receive the bytes
     * @param pByteArray the the bytes to pass to the stream
     * @throws IOException
     */
    private static void writeCompressed(ObjectOutput pOut, byte[] pByteArray) throws IOException {
        byte[] compressedBytes = new byte[pByteArray.length];
        Deflater deflator = new Deflater(Deflater.BEST_COMPRESSION);
        deflator.setInput(pByteArray);
        deflator.finish();

        int compressedSize = deflator.deflate(compressedBytes);
        deflator.end();

        // First write a flag to indicate whether the stream is compressed or not
        pOut.writeBoolean(true);

        // Now the length of the compressed data
        pOut.writeInt(compressedSize);

        // Now the length of the uncompressed data
        pOut.writeInt(pByteArray.length);

        // Now the data
        pOut.write(compressedBytes, 0, compressedSize);
        if (_log.isInfoEnabled()) {
            _log.info("Compressed output stream from " + pByteArray.length + " bytes to " + compressedSize + " bytes.");
        }
    }
}
TOP

Related Classes of Framework.compression.CompressionHelper

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.