|
| 1 | +/* |
| 2 | + * Copyright 1999-2019 Seata.io Group. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package io.seata.compressor.deflater; |
| 17 | + |
| 18 | +import java.io.ByteArrayOutputStream; |
| 19 | +import java.io.IOException; |
| 20 | +import java.util.zip.Deflater; |
| 21 | +import java.util.zip.Inflater; |
| 22 | + |
| 23 | +/** |
| 24 | + * @author dongzl |
| 25 | + */ |
| 26 | +public class DeflaterUtil { |
| 27 | + |
| 28 | + private DeflaterUtil() { |
| 29 | + |
| 30 | + } |
| 31 | + |
| 32 | + private static final int BUFFER_SIZE = 8192; |
| 33 | + |
| 34 | + public static byte[] compress(byte[] bytes) { |
| 35 | + if (bytes == null) { |
| 36 | + throw new NullPointerException("bytes is null"); |
| 37 | + } |
| 38 | + int lenght = 0; |
| 39 | + Deflater deflater = new Deflater(); |
| 40 | + deflater.setInput(bytes); |
| 41 | + deflater.finish(); |
| 42 | + byte[] outputBytes = new byte[BUFFER_SIZE]; |
| 43 | + try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { |
| 44 | + while (!deflater.finished()) { |
| 45 | + lenght = deflater.deflate(outputBytes); |
| 46 | + bos.write(outputBytes, 0, lenght); |
| 47 | + } |
| 48 | + deflater.end(); |
| 49 | + return bos.toByteArray(); |
| 50 | + } catch (IOException e) { |
| 51 | + throw new RuntimeException("Deflater compress error", e); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + public static byte[] decompress(byte[] bytes) { |
| 56 | + if (bytes == null) { |
| 57 | + throw new NullPointerException("bytes is null"); |
| 58 | + } |
| 59 | + int length = 0; |
| 60 | + Inflater inflater = new Inflater(); |
| 61 | + inflater.setInput(bytes); |
| 62 | + byte[] outputBytes = new byte[BUFFER_SIZE]; |
| 63 | + try (ByteArrayOutputStream bos = new ByteArrayOutputStream();) { |
| 64 | + while (!inflater.finished()) { |
| 65 | + length = inflater.inflate(outputBytes); |
| 66 | + if (length == 0) { |
| 67 | + break; |
| 68 | + } |
| 69 | + bos.write(outputBytes, 0, length); |
| 70 | + } |
| 71 | + inflater.end(); |
| 72 | + return bos.toByteArray(); |
| 73 | + } catch (Exception e) { |
| 74 | + throw new RuntimeException("Deflater decompress error", e); |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | +} |
0 commit comments