View Javadoc

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