001/*
002 * Copyright (C) 2012 eXo Platform SAS.
003 *
004 * This is free software; you can redistribute it and/or modify it
005 * under the terms of the GNU Lesser General Public License as
006 * published by the Free Software Foundation; either version 2.1 of
007 * the License, or (at your option) any later version.
008 *
009 * This software is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * You should have received a copy of the GNU Lesser General Public
015 * License along with this software; if not, write to the Free
016 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
017 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
018 */
019package org.crsh.lang.impl.java;
020
021import java.security.SecureClassLoader;
022import java.util.HashMap;
023import java.util.Map;
024
025/** @author Julien Viet */
026class LoadingClassLoader extends SecureClassLoader {
027
028  /** . */
029  private final Map<String, byte[]> definitions;
030
031  /** . */
032  private final HashMap<String, Class<?>> classes;
033
034  LoadingClassLoader(ClassLoader parent, Iterable<JavaClassFileObject> files) {
035    super(parent);
036
037    //
038    HashMap<String, byte[]> definitions = new HashMap<String,byte[]>();
039    for (JavaClassFileObject definition : files) {
040      definitions.put(definition.getClassName(), definition.getBytes());
041    }
042
043    //
044    this.definitions = definitions;
045    this.classes = new HashMap<String, Class<?>>();
046  }
047
048  LoadingClassLoader(Map<String, byte[]> definitions) {
049    this.definitions = definitions;
050    this.classes = new HashMap<String, Class<?>>();
051  }
052
053  @Override
054  protected Class<?> findClass(String name) throws ClassNotFoundException {
055    Class<?> clazz = classes.get(name);
056    if (clazz == null) {
057      byte[] definition = definitions.get(name);
058      if (definition == null) {
059        return super.findClass(name);
060      } else {
061        classes.put(name, clazz = super.defineClass(name, definition, 0, definition.length));
062      }
063    }
064    return clazz;
065  }
066}