001package org.apache.commons.jcs3.utils.serialization; 002 003/* 004 * Licensed to the Apache Software Foundation (ASF) under one 005 * or more contributor license agreements. See the NOTICE file 006 * distributed with this work for additional information 007 * regarding copyright ownership. The ASF licenses this file 008 * to you under the Apache License, Version 2.0 (the 009 * "License"); you may not use this file except in compliance 010 * with the License. You may obtain a copy of the License at 011 * 012 * http://www.apache.org/licenses/LICENSE-2.0 013 * 014 * Unless required by applicable law or agreed to in writing, 015 * software distributed under the License is distributed on an 016 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 017 * KIND, either express or implied. See the License for the 018 * specific language governing permissions and limitations 019 * under the License. 020 */ 021 022import java.io.ByteArrayInputStream; 023import java.io.ByteArrayOutputStream; 024import java.io.IOException; 025import java.io.ObjectInputStream; 026import java.io.ObjectOutputStream; 027 028import org.apache.commons.jcs3.engine.behavior.IElementSerializer; 029import org.apache.commons.jcs3.io.ObjectInputStreamClassLoaderAware; 030 031/** 032 * Performs default serialization and de-serialization. 033 */ 034public class StandardSerializer 035 implements IElementSerializer 036{ 037 /** 038 * Serializes an object using default serialization. 039 * <p> 040 * @param obj 041 * @return byte[] 042 * @throws IOException 043 */ 044 @Override 045 public <T> byte[] serialize(final T obj) 046 throws IOException 047 { 048 final ByteArrayOutputStream baos = new ByteArrayOutputStream(); 049 050 try (ObjectOutputStream oos = new ObjectOutputStream(baos)) 051 { 052 oos.writeUnshared(obj); 053 } 054 055 return baos.toByteArray(); 056 } 057 058 /** 059 * Uses default de-serialization to turn a byte array into an object. All exceptions are 060 * converted into IOExceptions. 061 * <p> 062 * @param data data bytes 063 * @param loader class loader to use 064 * @return Object 065 * @throws IOException 066 * @throws ClassNotFoundException 067 */ 068 @Override 069 public <T> T deSerialize(final byte[] data, final ClassLoader loader) 070 throws IOException, ClassNotFoundException 071 { 072 try (ByteArrayInputStream bais = new ByteArrayInputStream(data); 073 ObjectInputStream ois = new ObjectInputStreamClassLoaderAware(bais, loader)) 074 { 075 @SuppressWarnings("unchecked") // Need to cast from Object 076 final 077 T readObject = (T) ois.readObject(); 078 return readObject; 079 } 080 } 081}