View Javadoc

1   /**********************************************************************
2    * ClassHandler.java
3    * created on 14.08.2004 by netseeker
4    * $Source: /cvsroot/ejoe/EJOE/src/de/netseeker/ejoe/handler/ClassHandler.java,v $
5    * $Date: 2006/02/04 14:16:03 $
6    * $Revision: 1.8 $
7    *********************************************************************/
8   
9   package de.netseeker.ejoe.handler;
10  
11  import java.io.ByteArrayOutputStream;
12  import java.io.IOException;
13  import java.io.InputStream;
14  import java.util.logging.Level;
15  import java.util.logging.Logger;
16  
17  import de.netseeker.ejoe.EJConstants;
18  import de.netseeker.ejoe.cache.SoftKeyedObjectCache;
19  import de.netseeker.ejoe.io.IOUtils;
20  
21  /***
22   * A ServerHandler which handles class loader requests. It reads the .class file
23   * of the requested class and returns the content as an ByteArray. A cache is
24   * used to store the last thousand returned classes.
25   * 
26   * @author netseeker aka Michael Manske
27   */
28  public class ClassHandler implements ServerHandler
29  {
30  	private static final Logger					log			= Logger.getLogger(ClassHandler.class.getName());
31  
32  	private static final SoftKeyedObjectCache	_classCache	= new SoftKeyedObjectCache(1000);
33  
34  	/*
35  	 * (non-Javadoc)
36  	 * 
37  	 * @see de.netseeker.ejoe.ServerHandler#handle(java.lang.Object)
38  	 */
39  	public Object handle(Object obj)
40  	{
41  		byte[] buf = (byte[]) _classCache.get(obj);
42  
43  		if (buf == null)
44  		{
45  			InputStream input = null;
46  
47  			try
48  			{
49  				String name = (String) obj;
50  				name = name.replaceAll("//.", "/");
51  				input = ClassHandler.class.getResourceAsStream("/" + name + ".class");
52  				if (input != null)
53  				{
54  					ByteArrayOutputStream bos = new ByteArrayOutputStream(EJConstants.BUFFERED_STREAM_SIZE);
55  					byte[] buffer = new byte[EJConstants.BUFFERED_STREAM_SIZE];
56  					int count = 0;
57  					int n = 0;
58  					while (-1 != (n = input.read(buffer)))
59  					{
60  						bos.write(buffer, 0, n);
61  						count += n;
62  					}
63  
64  					buf = bos.toByteArray();
65  					_classCache.put(obj, buf);
66  				}
67  				else
68  				{
69  					throw new RuntimeException("Class " + obj + "not found.");
70  				}
71  			}
72  			catch (IOException e)
73  			{
74  				log.log(Level.SEVERE, "IOException occured while serializing class " + obj + ".", e);
75  				throw new RuntimeException(e);
76  			}
77  			finally
78  			{
79  				IOUtils.closeQuite(input);
80  			}
81  		}
82  
83  		return buf;
84  	}
85  }