001package org.cache2k.storage; 002 003/* 004 * #%L 005 * cache2k core package 006 * %% 007 * Copyright (C) 2000 - 2015 headissue GmbH, Munich 008 * %% 009 * This program is free software: you can redistribute it and/or modify 010 * it under the terms of the GNU General Public License as 011 * published by the Free Software Foundation, either version 3 of the 012 * License, or (at your option) any later version. 013 * 014 * This program is distributed in the hope that it will be useful, 015 * but WITHOUT ANY WARRANTY; without even the implied warranty of 016 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 017 * GNU General Public License for more details. 018 * 019 * You should have received a copy of the GNU General Public 020 * License along with this program. If not, see 021 * <http://www.gnu.org/licenses/gpl-3.0.html>. 022 * #L% 023 */ 024 025import java.io.ByteArrayInputStream; 026import java.io.ByteArrayOutputStream; 027import java.io.IOException; 028import java.io.InputStream; 029import java.io.ObjectInput; 030import java.io.ObjectInputStream; 031import java.io.ObjectOutput; 032import java.io.ObjectOutputStream; 033import java.io.OutputStream; 034import java.nio.ByteBuffer; 035 036/** 037 * A standard marshaller implementation, based on serialization. 038 * 039 * @author Jens Wilke; created: 2014-03-31 040 */ 041public class StandardMarshaller implements Marshaller { 042 043 @Override 044 public byte[] marshall(Object o) throws IOException { 045 ByteArrayOutputStream bos = new ByteArrayOutputStream(); 046 ObjectOutputStream oos = new ObjectOutputStream(bos); 047 oos.writeObject(o); 048 oos.close(); 049 return bos.toByteArray(); 050 } 051 052 @Override 053 public Object unmarshall(byte[] ba) throws IOException, ClassNotFoundException { 054 ByteArrayInputStream bis = new ByteArrayInputStream(ba); 055 return returnObject(bis); 056 } 057 058 @Override 059 public Object unmarshall(ByteBuffer b) throws IOException, ClassNotFoundException { 060 ByteBufferInputStream bis = new ByteBufferInputStream(b); 061 return returnObject(bis); 062 } 063 064 private Object returnObject(InputStream bis) throws IOException, ClassNotFoundException { 065 ObjectInputStream ois = new ObjectInputStream(bis); 066 try { 067 return ois.readObject(); 068 } finally { 069 ois.close(); 070 } 071 } 072 073 @Override 074 public boolean supports(Object o) { 075 return true; 076 } 077 078 @Override 079 public ObjectOutput startOutput(OutputStream out) throws IOException { 080 return new ObjectOutputStream(out); 081 } 082 083 @Override 084 public ObjectInput startInput(InputStream in) throws IOException { 085 return new ObjectInputStream(in); 086 } 087 088 @Override 089 public MarshallerFactory.Parameters getFactoryParameters() { 090 return new MarshallerFactory.Parameters(this.getClass()); 091 } 092 093}