View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.transport.tcp.protocols;
8   
9   import java.io.IOException;
10  import java.io.InputStream;
11  
12  import org.apache.commons.io.input.ClassLoaderObjectInputStream;
13  import org.apache.log4j.Logger;
14  
15  /**
16   * A length protocol that uses a specific class loader to load objects from streams
17   * 
18   * @since 2.2.6
19   */
20  public class CustomClassLoadingLengthProtocol extends LengthProtocol
21  {
22      private final Logger logger = Logger.getLogger(this.getClass());
23  
24      private ClassLoader classLoader;
25  
26      @Override
27      public Object read(InputStream is) throws IOException
28      {
29          byte[] bytes = (byte[]) super.read(is);
30  
31          if (bytes == null)
32          {
33              return null;
34          }
35          else
36          {
37              ClassLoaderObjectInputStream classLoaderIS = new ClassLoaderObjectInputStream(this.getClassLoader(),
38                  is);
39              try
40              {
41                  return classLoaderIS.readObject();
42              }
43              catch (ClassNotFoundException e)
44              {
45                  logger.warn(e.getMessage());
46                  IOException iox = new IOException();
47                  iox.initCause(e);
48                  throw iox;
49              }
50              finally
51              {
52                  classLoaderIS.close();
53              }
54          }
55      }
56  
57      public ClassLoader getClassLoader()
58      {
59          if (this.classLoader == null)
60          {
61              this.classLoader = this.getClass().getClassLoader();
62          }
63          return classLoader;
64      }
65  
66      public void setClassLoader(ClassLoader classLoader)
67      {
68          this.classLoader = classLoader;
69      }
70  }