Line data Source code
1 : // Copyright (C) 2016 The Android Open Source Project 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.server.plugins; 16 : 17 : import com.google.common.io.ByteStreams; 18 : import java.io.IOException; 19 : import java.io.InputStream; 20 : import java.net.URL; 21 : import java.util.Enumeration; 22 : 23 : public class DelegatingClassLoader extends ClassLoader { 24 : private final ClassLoader target; 25 : 26 : public DelegatingClassLoader(ClassLoader parent, ClassLoader target) { 27 0 : super(parent); 28 0 : this.target = target; 29 0 : } 30 : 31 : @Override 32 : public Class<?> findClass(String name) throws ClassNotFoundException { 33 0 : String path = name.replace('.', '/') + ".class"; 34 0 : try (InputStream resource = target.getResourceAsStream(path)) { 35 0 : if (resource != null) { 36 : try { 37 0 : byte[] bytes = ByteStreams.toByteArray(resource); 38 0 : return defineClass(name, bytes, 0, bytes.length); 39 0 : } catch (IOException e) { 40 : // throws ClassNotFoundException later 41 : } 42 : } 43 0 : } catch (IOException e) { 44 : // throws ClassNotFoundException later 45 0 : } 46 0 : throw new ClassNotFoundException(name); 47 : } 48 : 49 : @Override 50 : public URL getResource(String name) { 51 0 : URL rtn = getParent().getResource(name); 52 0 : if (rtn == null) { 53 0 : rtn = target.getResource(name); 54 : } 55 0 : return rtn; 56 : } 57 : 58 : @Override 59 : public Enumeration<URL> getResources(String name) throws IOException { 60 0 : Enumeration<URL> rtn = getParent().getResources(name); 61 0 : if (rtn == null) { 62 0 : rtn = target.getResources(name); 63 : } 64 0 : return rtn; 65 : } 66 : 67 : @Override 68 : public InputStream getResourceAsStream(String name) { 69 0 : InputStream rtn = getParent().getResourceAsStream(name); 70 0 : if (rtn == null) { 71 0 : rtn = target.getResourceAsStream(name); 72 : } 73 0 : return rtn; 74 : } 75 : }