001 /* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 018 package org.apache.commons.proxy.interceptor; 019 020 import org.apache.commons.proxy.Interceptor; 021 import org.apache.commons.proxy.Invocation; 022 023 import java.io.ByteArrayInputStream; 024 import java.io.ByteArrayOutputStream; 025 import java.io.IOException; 026 import java.io.ObjectInputStream; 027 import java.io.ObjectOutputStream; 028 029 /** 030 * An interceptor which makes a serialized copy of all parameters and return values. This 031 * is useful when testing remote services to ensure that all parameter/return types 032 * are in fact serializable/deserializable. 033 * @since 1.0 034 */ 035 public class SerializingInterceptor implements Interceptor 036 { 037 public Object intercept(Invocation invocation) throws Throwable 038 { 039 Object[] arguments = invocation.getArguments(); 040 for (int i = 0; i < arguments.length; i++) 041 { 042 arguments[i] = serializedCopy(arguments[i]); 043 } 044 return serializedCopy(invocation.proceed()); 045 } 046 047 private Object serializedCopy(Object original) 048 { 049 try 050 { 051 final ByteArrayOutputStream bout = new ByteArrayOutputStream(); 052 final ObjectOutputStream oout = new ObjectOutputStream(bout); 053 oout.writeObject(original); 054 oout.close(); 055 bout.close(); 056 final ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray()); 057 final ObjectInputStream oin = new ObjectInputStream(bin); 058 final Object copy = oin.readObject(); 059 oin.close(); 060 bin.close(); 061 return copy; 062 } 063 catch (IOException e) 064 { 065 throw new RuntimeException( "Unable to make serialized copy of " + 066 original.getClass().getName() + " object.", e ); 067 } 068 catch (ClassNotFoundException e) 069 { 070 throw new RuntimeException( "Unable to make serialized copy of " + 071 original.getClass().getName() + " object.", e ); 072 } 073 } 074 }