Java tutorial
/** * @author Tadanori TERUYA <tadanori.teruya@gmail.com> (2012) */ /* * Copyright (c) 2012 Tadanori TERUYA (tell) <tadanori.teruya@gmail.com> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * @license: The MIT license <http://opensource.org/licenses/MIT> */ package com.github.tell.codec; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64OutputStream; import java.io.*; public class Base64Serializer implements SerializationEncoder { public String getFormat() { return "Base64/" + JavaSerialization.formatName; } public byte[] encode(final Serializable o) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final Base64OutputStream b64os = new Base64OutputStream(baos, true); final ObjectOutputStream oos = new ObjectOutputStream(b64os); oos.writeObject(o); oos.close(); return baos.toByteArray(); } public Serializable decode(final byte[] encoded) throws IOException, ClassNotFoundException { final byte[] decoded = Base64.decodeBase64(encoded); final ByteArrayInputStream bais = new ByteArrayInputStream(decoded); final ObjectInputStream ois = new ObjectInputStream(bais); return (Serializable) ois.readObject(); } public String encodeToString(final Serializable o) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(o); oos.close(); final byte[] encoded = baos.toByteArray(); final Base64 encoder = new Base64(); return encoder.encodeToString(encoded); } public Serializable decodeFromString(final String encoded) throws IOException, ClassNotFoundException { final byte[] decoded = Base64.decodeBase64(encoded); final ByteArrayInputStream bais = new ByteArrayInputStream(decoded); final ObjectInputStream ois = new ObjectInputStream(bais); return (Serializable) ois.readObject(); } }