01: /* Copyright (C) 2004 - 2007 db4objects Inc. http://www.db4o.com
02:
03: This file is part of the db4o open source object database.
04:
05: db4o is free software; you can redistribute it and/or modify it under
06: the terms of version 2 of the GNU General Public License as published
07: by the Free Software Foundation and as clarified by db4objects' GPL
08: interpretation policy, available at
09: http://www.db4o.com/about/company/legalpolicies/gplinterpretation/
10: Alternatively you can write to db4objects, Inc., 1900 S Norfolk Street,
11: Suite 350, San Mateo, CA 94403, USA.
12:
13: db4o is distributed in the hope that it will be useful, but WITHOUT ANY
14: WARRANTY; without even the implied warranty of MERCHANTABILITY or
15: FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16: for more details.
17:
18: You should have received a copy of the GNU General Public License along
19: with this program; if not, write to the Free Software Foundation, Inc.,
20: 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
21: package com.db4o.db4ounit.util;
22:
23: import java.io.*;
24: import java.net.*;
25: import java.util.*;
26:
27: /**
28: * @sharpen.ignore
29: */
30: public class VersionClassLoader extends URLClassLoader {
31:
32: private Map cache = new HashMap();
33:
34: private String[] prefixes;
35:
36: public VersionClassLoader(URL[] urls, String[] prefixes) {
37: super (urls);
38: this .prefixes = prefixes;
39: }
40:
41: protected synchronized Class loadClass(String name, boolean resolve)
42: throws ClassNotFoundException {
43:
44: if (cache.containsKey(name)) {
45: return (Class) cache.get(name);
46: }
47:
48: if (!knownPrefix(name)) {
49: return super .loadClass(name, resolve);
50: }
51:
52: String resourceName = name.replace('.', '/') + ".class";
53: URL resourceURL = findResource(resourceName);
54: if (resourceURL == null) {
55: System.out.println("Warning: Cannot find resource "
56: + resourceName);
57: return super .loadClass(name, resolve);
58: }
59:
60: byte[] byteCode = null;
61: try {
62: byteCode = readBytes(resourceURL);
63: } catch (IOException e) {
64: e.printStackTrace();
65: super .loadClass(name, resolve);
66: }
67:
68: Class clazz = defineClass(name, byteCode, 0, byteCode.length);
69: if (resolve) {
70: resolveClass(clazz);
71: }
72: cache.put(name, clazz);
73: return clazz;
74: }
75:
76: private byte[] readBytes(URL resURL) throws IOException {
77: InputStream in = resURL.openStream();
78: ByteArrayOutputStream out = new ByteArrayOutputStream();
79: byte[] buf = new byte[1024];
80: int bytesRead = 0;
81: while ((bytesRead = in.read(buf)) >= 0) {
82: out.write(buf, 0, bytesRead);
83: }
84: in.close();
85: out.close();
86: byte[] full = out.toByteArray();
87: return full;
88: }
89:
90: private boolean knownPrefix(String className) {
91: for (int idx = 0; idx < prefixes.length; idx++) {
92: if (className.startsWith(prefixes[idx])) {
93: return true;
94: }
95: }
96: return false;
97: }
98:
99: }
|