Skip to contentPackage: GZIPUtils
GZIPUtils
Coverage
1: /*******************************************************************************
2: * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others
3: *
4: * This program and the accompanying materials are made
5: * available under the terms of the Eclipse Public License 2.0
6: * which is available at https://www.eclipse.org/legal/epl-2.0/
7: *
8: * SPDX-License-Identifier: EPL-2.0
9: *
10: * Contributors:
11: * Eurotech - initial API and implementation
12: * Red Hat Inc
13: *******************************************************************************/
14: package org.eclipse.kapua.service.device.call.message.kura.utils;
15:
16: import com.google.common.io.ByteSource;
17: import com.google.common.io.ByteStreams;
18:
19: import java.io.ByteArrayInputStream;
20: import java.io.ByteArrayOutputStream;
21: import java.io.IOException;
22: import java.io.OutputStream;
23: import java.util.zip.GZIPInputStream;
24: import java.util.zip.GZIPOutputStream;
25:
26: /**
27: * Gzip utilities.
28: *
29: * @since 1.0.0
30: */
31: public class GZIPUtils {
32:
33: private GZIPUtils() {
34: }
35:
36: /**
37: * Check if the byte array represents compressed data.
38: *
39: * @param bytes The input data to check.
40: * @return {@code true} if the data is compressed, {@code false} otherwise.
41: * @since 1.0.0
42: */
43: public static boolean isCompressed(byte[] bytes) {
44:• if (bytes == null || bytes.length < 2) {
45: return false;
46: } else {
47:• return bytes[0] == (byte) GZIPInputStream.GZIP_MAGIC && bytes[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8);
48: }
49: }
50:
51: /**
52: * Compress provided data with GZIP.
53: *
54: * @param source the input data to compress.
55: * @return the compressed output data, returns {@code null} if the input was {@code null}.
56: * @throws IOException in case of an I/O error.
57: * @since 1.0.0
58: */
59: public static byte[] compress(byte[] source) throws IOException {
60:• if (source == null) {
61: return new byte[0];
62: }
63:
64: try (
65: ByteArrayOutputStream result = new ByteArrayOutputStream();
66: OutputStream out = new GZIPOutputStream(result)
67: ) {
68: ByteSource.wrap(source).copyTo(out);
69: return result.toByteArray();
70: }
71: }
72:
73: /**
74: * Uncompress GZIP compressed data.
75: *
76: * @param source the data to uncompress.
77: * @return the uncompressed data, returns {@code null} if the input was {@code null}.
78: * @throws IOException in case of an I/O error.
79: * @since 1.0.0
80: */
81: public static byte[] decompress(byte[] source) throws IOException {
82:• if (source == null) {
83: return new byte[0];
84: }
85:
86: try (
87: ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(source);
88: GZIPInputStream inputStream = new GZIPInputStream(byteArrayInputStream)
89: ) {
90: return ByteStreams.toByteArray(inputStream);
91: }
92: }
93: }