View Javadoc
1   package org.sentrysoftware.jawk.util;
2   
3   /*-
4    * ╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲
5    * Jawk
6    * ჻჻჻჻჻჻
7    * Copyright (C) 2006 - 2023 Sentry Software
8    * ჻჻჻჻჻჻
9    * This program is free software: you can redistribute it and/or modify
10   * it under the terms of the GNU Lesser General Public License as
11   * published by the Free Software Foundation, either version 3 of the
12   * License, or (at your option) any later version.
13   *
14   * This program is distributed in the hope that it will be useful,
15   * but WITHOUT ANY WARRANTY; without even the implied warranty of
16   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   * GNU General Lesser Public License for more details.
18   *
19   * You should have received a copy of the GNU General Lesser Public
20   * License along with this program.  If not, see
21   * <http://www.gnu.org/licenses/lgpl-3.0.html>.
22   * ╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱
23   */
24  
25  import java.io.ByteArrayOutputStream;
26  import java.io.File;
27  import java.io.FileInputStream;
28  import java.io.IOException;
29  
30  /**
31   * Load classes from a particular directory, disregarding the
32   * environmental class-path setting.
33   * This is useful when a directory is specified for class files,
34   * and it would not make sense to deviate from that directory.
35   * So this ClassLoader does practically the same
36   * like a <code>URLClassLoader</code> with a "file://.../" URL,
37   * except that it does not forward calls to its parent,
38   * if it can not find the class its self.
39   * <p>
40   * For Jawk, this is used when the -d argument is present.
41   *
42   * @author Danny Daglas
43   */
44  public final class DestDirClassLoader extends ClassLoader {
45  
46  	private String dirname;
47  
48  	/**
49  	 * <p>Constructor for DestDirClassLoader.</p>
50  	 *
51  	 * @param dirname a {@link java.lang.String} object
52  	 */
53  	public DestDirClassLoader(String dirname) {
54  		this.dirname = dirname;
55  	}
56  
57  	/** {@inheritDoc} */
58  	@Override
59  	protected Class<?> findClass(String name)
60  			throws ClassNotFoundException
61  	{
62  		byte[] b = loadClassData(name);
63  		return defineClass(name, b, 0, b.length);
64  	}
65  
66  	private byte[] loadClassData(String name)
67  			throws ClassNotFoundException
68  	{
69  		String fileName = dirname + File.separator + name + ".class";
70  		try {
71  			FileInputStream f = new FileInputStream(fileName);
72  			ByteArrayOutputStream baos = new ByteArrayOutputStream();
73  			byte[] b = new byte[4096];
74  			int len;
75  			while ((len = f.read(b, 0, b.length)) >= 0) {
76  				baos.write(b, 0, len);
77  			}
78  			f.close();
79  			baos.close();
80  			return baos.toByteArray();
81  		} catch (IOException ioe) {
82  			throw new ClassNotFoundException(
83  					"Could not load class " + name
84  					+ " from file \"" + fileName + "\"", ioe);
85  		}
86  	}
87  }