View Javadoc
1   /*
2    *  Copyright 2012 Chris Pheby
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   */
16  package org.jadira.scanner.core.helper;
17  
18  import java.io.BufferedInputStream;
19  import java.io.DataInputStream;
20  import java.io.IOException;
21  import java.io.InputStream;
22  import java.util.WeakHashMap;
23  
24  import javassist.bytecode.ClassFile;
25  
26  public final class JavassistClassFileHelper {
27  
28  	private static final WeakHashMap<String, ClassFile> CLASSFILES_BY_NAME = new WeakHashMap<String, ClassFile>(1024, 0.6f);
29  	private static final WeakHashMap<String, ClassFile> CLASSFILES_BY_FILE = new WeakHashMap<String, ClassFile>(1024, 0.6f);
30  	
31  	private static final int MAXIMUM_SIZE = 2048;
32  	
33  	private JavassistClassFileHelper() {
34  	}
35  	
36      public static ClassFile constructClassFile(String className, InputStream bits) throws IOException {
37  
38  		ClassFile cachedClassFile = CLASSFILES_BY_NAME.get(className);
39  		if (cachedClassFile != null) {
40  			return cachedClassFile;
41  		}
42      	
43      	DataInputStream dstream = new DataInputStream(new BufferedInputStream(bits));
44          ClassFile cf = null;
45          try {
46              cf = new ClassFile(dstream);
47          } finally {
48              dstream.close();
49              bits.close();
50          }
51          
52          if (cf != null) {
53          	CLASSFILES_BY_NAME.put(className, cf);
54          }
55          return cf;
56      }
57      
58      public static ClassFile constructClassFileForPath(String path, InputStream bits) throws IOException {
59  
60  		ClassFile cachedClassFile = CLASSFILES_BY_FILE.get(path);
61  		if (cachedClassFile != null) {
62  			return cachedClassFile;
63  		}
64      	
65      	DataInputStream dstream = new DataInputStream(new BufferedInputStream(bits));
66          ClassFile cf = null;
67          try {
68              cf = new ClassFile(dstream);
69          } finally {
70              dstream.close();
71              bits.close();
72          }
73          
74          if (cf != null) {
75          	if (CLASSFILES_BY_NAME.size() < MAXIMUM_SIZE) {
76          		CLASSFILES_BY_NAME.put(cf.getName(), cf);
77          	}
78          	if (CLASSFILES_BY_FILE.size() < MAXIMUM_SIZE) {
79          		CLASSFILES_BY_FILE.put(path, cf);
80          	}
81          }
82          return cf;
83      }}