/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2005/07/15, 16:04
!  AUTHOR(S): KOGA, Junichiro
!  File : PluginLoader.java
!  
!  Contact address :  Phase System Consortium
!                     E-mail: phase_system@nims.go.jp URL https://azuma.nims.go.jp
!
!
!   Since 2002, this program set had been intensively developed as a part of the following 
!  national projects supported by the Ministry of Education, Culture, Sports, Science and
!  Technology (MEXT) of Japan; "Frontier Simulation Software for Industrial Science
!  (FSIS)" from 2002 to 2005, "Revolutionary Simulation Software (RSS21)" from 2006 to
!  2008. "Research and Development of Innovative Simulation Software (RISS)" from 2008
!  to 2013. These projects is lead by the Center for Research on Innovative Simulation 
!  Software (CISS), the Institute of Industrial Science (IIS), the University of Tokyo.
!   Since 2013, this program set has been further developed centering on PHASE System
!  Consortium. 
!   The activity of development of this program set has been supervised by Takahisa Ohno.
!
!=======================================================================
 */
package ciss.phase_viewer.main;

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.log4j.Logger;

/**
 * 
 * @author KOGA, Junichiro
 */
public class PluginLoader extends ClassLoader {
    private static Logger logger = Logger.getLogger(PluginLoader.class
            .getName());

    public static String plugindir = System.getProperty("pviewer.home")
            + System.getProperty("file.separator") + "plugins";

    /** Creates a new instance of PluginLoader */
    public PluginLoader() {
    }

    protected Class findClass(String name) {
        String className = name.replace('.', File.separatorChar);
        logger.debug("loading: " + className);
        byte[] classData = getClassDataFrom(plugindir
                + System.getProperty("file.separator") + className + ".class");
        return defineClass(name, classData, 0, classData.length);
    }

    protected URL findResource(String name) {
        String resourcePath = name.replace('/', File.separatorChar);
        resourcePath = plugindir + System.getProperty("file.separator")
                + resourcePath;
        URL url = null;
        try {
            url = new URL("file://localhost/" + resourcePath);
        } catch (MalformedURLException ex) {
            logger.error("failed to get resource: " + resourcePath);
        }
        return url;
    }

    /**
     * 指定のクラスを, 指定の引数でインスタンス化.
     * 
     * @param path
     *            クラスのパス
     * @param args
     *            コンストラクターの引数
     */
    public static Object instantiate(String path, Object[] args) {
        logger.debug("trying " + path);
        PluginLoader pl = new PluginLoader();
        Object obj = null;
        try {
            Class cla = pl.loadClass(path);
            Constructor[] constructor = cla.getDeclaredConstructors();
            obj = constructor[0].newInstance(args);
        } catch (Exception ex) {
            logger.error("failed to load class: " + path);
            ex.printStackTrace();
        }
        return obj;
    }

    /**
     * plugins dirからリソース名を解決する. findResourceと同じだけどstaticな点のみ異なる.
     * 
     * @param name
     *            リソースのパス
     * @return リソースへのURL.
     */
    public static URL getPluginResource(String name) {
        String resourcePath = name.replace('/', File.separatorChar);
        resourcePath = plugindir + System.getProperty("file.separator")
                + resourcePath;
        URL url = null;
        try {
            url = new URL("file://localhost/" + resourcePath);
        } catch (MalformedURLException ex) {
            logger.error("failed to get resource: " + resourcePath);
        }
        return url;
    }

    private byte[] getClassDataFrom(String className) {
        byte result[];
        try {
            FileInputStream fi = new FileInputStream(className);
            result = new byte[fi.available()];
            fi.read(result);
            return result;
        } catch (Exception e) {
            return null;
        }
    }

}
