Thursday, June 2, 2016

Simple and useful Zip and unZip text

Simple and usefull textual zip and unzip.
First we use binary zip . but if we want to send it as a text message (e.g some message bus supports only text messages) we need to convert it to text by encoding to base 64 and vice versa to unzip it.
import java.io.ByteArrayInputStream
import java.nio.charset.StandardCharsets
import java.util.zip.{GZIPOutputStream, GZIPInputStream}
import org.apache.commons.codec.binary.Base64
import org.apache.commons.io.output.ByteArrayOutputStream

import scala.util.Try
  val zipToBinary: String => Array[Byte] = {txt =>
    val arrOutputStream = new ByteArrayOutputStream()
    val zipOutputStream = new GZIPOutputStream(arrOutputStream)
    zipOutputStream.write(txt.getBytes(StandardCharsets.UTF_8))
    zipOutputStream.close()
    arrOutputStream.toByteArray
  }


  val byteArrayToTxt : Array[Byte] => String = bytes => Base64.encodeBase64String(bytes)

  val txtToBinary : String => Array[Byte]= txt => Base64.decodeBase64(txt.getBytes(StandardCharsets.UTF_8))

  val binaryToTxt : Array[Byte] => String = bytes =>
    scala.io.Source.fromInputStream(new GZIPInputStream(new ByteArrayInputStream(bytes)))(StandardCharsets.UTF_8).mkString

  val zip:String => String = zipToBinary andThen byteArrayToTxt

  val unzip :String => String = txtToBinary andThen binaryToTxt


Usage :
val someLongTxt = "One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches into stiff sections. The bedding was hardly able to cover it and seemed ready to slide off any moment. His many legs, pitifully thin compared with the size of the rest of him, waved about helplessly as he looked. \"What's happened to me?\" he thought. It wasn't a dream. His room, a proper human room although a little too small, lay peacefully between its four familiar walls. A collection of textile samples lay spread out on the table - Samsa was a travelling salesman - and above it there hung a picture that he had recently cut out of an illustrated magazine and housed in a nice, gilded frame. It showed a lady fitted out with a fur hat and fur boa who sat upright, raising a heavy fur muff that covered the whole of her lower arm towards the viewer. Gregor then turned to look out the window at the dull weather. Drops"
assert (unzip(zip(someLongTxt)) == someLongTxt)

No comments:

Post a Comment