1/*
2 * Copyright (C) 2015 The Android Open Source Project
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
17package com.android.layoutlib.bridge.intensive.setup;
18
19import java.io.ByteArrayOutputStream;
20import java.io.IOException;
21import java.io.InputStream;
22import java.util.Map;
23
24import com.google.android.collect.Maps;
25
26/**
27 * The ClassLoader to load the project's classes.
28 */
29public class ModuleClassLoader extends ClassLoader {
30
31    private final Map<String, Class<?>> mClasses = Maps.newHashMap();
32    private final String mClassLocation;
33
34    public ModuleClassLoader(String classLocation) {
35        mClassLocation = classLocation;
36    }
37
38    @Override
39    protected Class<?> findClass(String name) throws ClassNotFoundException {
40        Class<?> aClass = mClasses.get(name);
41        if (aClass != null) {
42            return aClass;
43        }
44        String pathName = mClassLocation.concat(name.replace('.', '/')).concat(".class");
45        InputStream classInputStream = getClass().getResourceAsStream(pathName);
46        if (classInputStream == null) {
47            throw new ClassNotFoundException("Unable to find class " + name + " at " + pathName);
48        }
49        byte[] data;
50        try {
51            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
52            int nRead;
53            data = new byte[16384];  // 16k
54            while ((nRead = classInputStream.read(data, 0, data.length)) != -1) {
55                buffer.write(data, 0, nRead);
56            }
57            buffer.flush();
58            data = buffer.toByteArray();
59        } catch (IOException e) {
60            // Wrap the exception with ClassNotFoundException so that caller can deal with it.
61            throw new ClassNotFoundException("Unable to load class " + name, e);
62        }
63        aClass = defineClass(name, data, 0, data.length);
64        mClasses.put(name, aClass);
65        return aClass;
66    }
67}
68