All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.e6tech.elements.common.util.CompressionSerializer Maven / Gradle / Ivy

There is a newer version: 2.7.9
Show newest version
/*
 * Copyright 2015-2019 Futeh Kao
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.e6tech.elements.common.util;

import java.io.*;
import java.util.zip.Deflater;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class CompressionSerializer {

    int compressionLevel = Deflater.BEST_SPEED;

    public CompressionSerializer() {
    }

    public CompressionSerializer(int level) {
        this.compressionLevel = level;
    }

    @SuppressWarnings({"squid:S1171", "squid:S3599"})
    public byte[] toBytes(Object obj) throws IOException {
        if (obj != null) {
            try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
                  GZIPOutputStream zos = new GZIPOutputStream(bos) {
                      { this.def.setLevel(compressionLevel); }
                 };
                 ObjectOutputStream oos = new ObjectOutputStream(zos)
            ) {
                oos.writeObject(obj);
                oos.flush();
                zos.finish();
                return bos.toByteArray();
            }
        } else {
            return new byte[0];
        }
    }

    @SuppressWarnings("unchecked")
    public static  T fromBytes(byte[] obj) throws IOException, ClassNotFoundException {
        if (obj != null && obj.length > 0) {
            try (ObjectInputStream ois =
                         new ObjectInputStream(
                                 new GZIPInputStream(
                                         new ByteArrayInputStream(obj)))) {
                return (T) ois.readObject();
            }
        } else {
            return null;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy