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 package org.apache.servicemix.camel.util;
018
019 import java.io.ByteArrayOutputStream;
020 import java.io.IOException;
021 import java.io.ObjectOutputStream;
022 import java.io.Serializable;
023
024 import org.apache.camel.spi.HeaderFilterStrategy;
025 import org.apache.commons.logging.Log;
026 import org.apache.commons.logging.LogFactory;
027
028 /**
029 * {@link org.apache.camel.spi.HeaderFilterStrategy} that filters out non-serializable values.
030 *
031 * It will try to write the object to a stream to make sure that an object that implements the
032 * {@link Serializable} interface can actually be serialized
033 */
034 public class StrictSerializationHeaderFilterStrategy implements HeaderFilterStrategy {
035
036 private static final Log LOG = LogFactory.getLog(StrictSerializationHeaderFilterStrategy.class);
037
038 public boolean applyFilterToCamelHeaders(String s, Object o) {
039 return doApplyFilter(s, o);
040 }
041
042 public boolean applyFilterToExternalHeaders(String s, Object o) {
043 return doApplyFilter(s, o);
044 }
045
046 private boolean doApplyFilter(String s, Object o) {
047 if (o instanceof Serializable) {
048 ObjectOutputStream oos = null;
049 try {
050 oos = new ObjectOutputStream(new ByteArrayOutputStream());
051 oos.writeObject(o);
052 } catch (IOException e) {
053 LOG.debug(String.format("%s implements Serializable, but serialization throws IOException: filtering key %s",
054 o, s));
055 return true;
056 } finally {
057 if (oos != null) {
058 try {
059 oos.close();
060 } catch (IOException e) {
061 // ignoring exception on stream close
062 }
063 }
064 }
065 return false;
066 }
067 return true;
068 }
069 }