Showing posts with label gzip. Show all posts
Showing posts with label gzip. Show all posts

Wednesday, 26 July 2023

Compress and decompress a string in Java

In this post, I am going to explain how to compress and decompress a string in Java.

 

Dependency used

<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-compress</artifactId>
	<version>1.21</version>
</dependency>

 

Below utility class use Apache Commons Compress for compression and decompression of strings.

 

StringCompressor.java
package com.sample.app.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

import org.apache.commons.compress.compressors.CompressorStreamFactory;
import org.apache.commons.compress.utils.IOUtils;

public class StringCompessor {

	public static String compress(String inputString) {

		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			try (OutputStream os = new CompressorStreamFactory()
					.createCompressorOutputStream(CompressorStreamFactory.GZIP, baos)) {
				os.write(inputString.getBytes(StandardCharsets.UTF_8));
			}
			return new String(baos.toByteArray(), StandardCharsets.ISO_8859_1);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

	public static String decompress(String compressedString) {

		try {
			byte[] compressedBytes = compressedString.getBytes(StandardCharsets.ISO_8859_1);
			try (InputStream is = new CompressorStreamFactory().createCompressorInputStream(
					CompressorStreamFactory.GZIP, new ByteArrayInputStream(compressedBytes))) {
				byte[] decompressedBytes = IOUtils.toByteArray(is);
				return new String(decompressedBytes, StandardCharsets.UTF_8);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}
}

 

The compress method uses the Apache Commons Compress library to compress the input string using the GZIP compression format and returns the compressed string.

 

The decompress method decompresses the compressed string back to its original form.

 

As you observe the above snippet, Application converts the output stream to a string using the ISO_8859_1 while compressing, it is required to handle any potential encoding issues that might occur when dealing with binary data in certain environments.

 

App.java
package com.sample.app;

import java.io.IOException;

import org.apache.commons.compress.compressors.CompressorException;

import com.sample.app.util.StringCompessor;

public class App {
	
	public static void main(String[] args) throws IOException, CompressorException {
		String str = "Hello world Hello world Hello world Hello world";
		
		String compressedString = StringCompessor.compress(str);
		String decompressedString = StringCompessor.decompress(compressedString);
		
		System.out.println("str : " + str);
		System.out.println("compressedString : " + compressedString);
		System.out.println("decompressedString : " + decompressedString);
	}

}

 


You may like

Miscellaneous

Read pkcs12 certificate information in Java

How to Get Client Certificate from HttpServletRequest

Programmatically import certificate to cacerts file in Java

Command to check CPU temperature in Mac

Quick guide to Java DecimalFormat class

Friday, 27 December 2019

NGINX: Compress response payload


Using gzip directive, you can compress the response payload.

Example
gzip on;
gzip_comp_level 4;
gzip_types text/plain;
gzip_types application/json;

gzip: Enable or disable zipping of responses
Enables or disables gzipping of responses.

Syntax:  gzip on | off;
Default: gzip off;
Context: http, server, location, if in location

gzip_comp_level: Set zipping compression level
Sets a gzip compression level of a response. Acceptable values are in the range from 1 to 9. Higher value means more compression and require more computing resources.

Syntax:  gzip_comp_level level;
Default: gzip_comp_level 1;
Context: http, server, location

gzip_types: Specify MIME types to compress
Syntax: gzip_types mime-type ...;
Default: gzip_types text/html;
Context: http, server, location

Enables gzipping of responses for the specified MIME types. Responses with the “text/html” type are always compressed.

Unless client send 'Accept-Encoding: gzip' header, nginx do not perform zipping of data.
$curl http://localhost:9090/about > temp.txt
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   240  100   240    0     0  37238      0 --:--:-- --:--:-- --:--:-- 40000
$
$
$curl -H 'Accept-Encoding: gzip, deflate' http://localhost:9090/about > temp_compressed.txt
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    63    0    63    0     0   7232      0 --:--:-- --:--:-- --:--:--  7875
$
$ls -lart temp*txt
-rw-r--r--  1 krishna  admin  240 Oct 17 10:38 temp.txt
-rw-r--r--  1 krishna  admin   63 Oct 17 10:38 temp_compressed.txt


As you see the content size of temp.txt and temp_compressed.txt, temp.txt has file size of 240 bytes, whereas temp_compressed.txt has the file size of 63 bytes.


Previous                                                    Next                                                    Home