/* * [Wrap.java] * * Summary: Prepares an object for shipping via HTTP CGI-POST. * * Copyright: (c) 2004-2017 Roedy Green, Canadian Mind Products, http://mindprod.com * * Licence: This software may be copied and used freely for any purpose but military. * http://mindprod.com/contact/nonmil.html * * Requires: JDK 1.8+ * * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/ * * Version History: * 1.4 2006-03-05 reformat with IntelliJ and add Javadoc. */ package com.mindprod.transporter; import com.mindprod.base64.Base64u; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.zip.GZIPOutputStream; /** * Prepares an object for shipping via HTTP CGI-POST. *

* Serialised, compressed, and Base64u armoured. * No encryption or signing. See Transporter.java for example of use. * * @author Roedy Green, Canadian Mind Products * @version 1.4 2006-03-05 reformat with IntelliJ and add Javadoc. * @since 2004-06-06 */ public class Wrap { /** * used to add armouring */ final Base64u armourer; /** * constructor */ public Wrap() { armourer = new Base64u(); armourer.setLineLength( Integer.MAX_VALUE ); armourer.setLineSeparator( "\n" ); } /** * add ASCII base64u armouring to a message of bytes to prepare it for transport. * * @param raw raw bytes. * * @return Printable ASCII armoured message. */ protected String armour( byte[] raw ) { return armourer.encode( raw ); } /** * Compress message with GZIP compression. * * @param message uncompressed message. * * @return compressed message. * @throws IOException */ protected byte[] compress( byte[] message ) throws IOException { // O P E N // will grow if needed. ByteArrayOutputStream baos = new ByteArrayOutputStream( message.length ); GZIPOutputStream gzos = new GZIPOutputStream( baos, 4 * 1024 ); // W R I T E gzos .write( message, 0 /* offset */, message.length /* bytes to write */ ); gzos.finish(); gzos.flush(); byte[] compressedMessage = baos.toByteArray(); // C L O S E gzos.close(); return compressedMessage; } /** * Serialise an object for sending * * @param o Object to serialize * * @return Pickled object as a byte array. * @throws IOException if cannot serialise the object */ protected byte[] serialize( Object o ) throws IOException { // O P E N // will grow if needed. ByteArrayOutputStream baos = new ByteArrayOutputStream( Tools.TYPICAL_MESSAGE_SIZE ); ObjectOutputStream oos = new ObjectOutputStream( baos ); // W R I T E oos.writeObject( o ); oos.flush(); byte[] pickled = baos.toByteArray(); // C L O S E oos.close(); return pickled; } /** * Wraps object for sending via CGI Post, serialised, compressed, and base64u encoded. Does not build parm=value. * * @param o Object to wrap for sending. * * @return base64u-encoded string to send. * @throws IOException if cannot wrate the serialisable object. */ public String wrap( Serializable o ) throws IOException { return armour( compress( serialize( o ) ) ); } }