001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019package org.apache.isis.core.commons.base64; 020 021import java.io.ByteArrayInputStream; 022import java.io.ByteArrayOutputStream; 023import java.io.IOException; 024import java.io.ObjectInputStream; 025import java.io.ObjectOutputStream; 026import java.io.Serializable; 027 028import org.apache.commons.codec.binary.Base64; 029 030public class Base64Serializer { 031 032 public static class Exception extends RuntimeException { 033 034 private static final long serialVersionUID = 1L; 035 036 public Exception(java.lang.Exception e) { 037 super(e); 038 } 039 } 040 041 public static Object fromString( String s ) { 042 final byte [] data = Base64.decodeBase64( s ); 043 ObjectInputStream ois = null; 044 try { 045 ois = new ObjectInputStream(new ByteArrayInputStream( data ) ); 046 return ois.readObject(); 047 } catch (IOException e) { 048 throw new Base64Serializer.Exception(e); 049 } catch (ClassNotFoundException e) { 050 throw new Base64Serializer.Exception(e); 051 } finally { 052 try { 053 if(ois != null) { 054 ois.close(); 055 } 056 } catch (IOException e) { 057 throw new Base64Serializer.Exception(e); 058 } 059 } 060 } 061 062 public static String toString( Serializable serializable ) { 063 final ByteArrayOutputStream baos = new ByteArrayOutputStream(); 064 ObjectOutputStream oos = null; 065 try { 066 oos = new ObjectOutputStream( baos ); 067 oos.writeObject( serializable ); 068 return new String( Base64.encodeBase64( baos.toByteArray() ) ); 069 } catch (IOException e) { 070 throw new Base64Serializer.Exception(e); 071 } finally { 072 try { 073 if(oos != null) { 074 oos.close(); 075 } 076 } catch (IOException e) { 077 throw new Base64Serializer.Exception(e); 078 } 079 } 080 } 081}