001/**
002 * Launcher.java
003 * jCOLIBRI2 framework. 
004 * @author Juan A. Recio-Garc�a.
005 * GAIA - Group for Artificial Intelligence Applications
006 * http://gaia.fdi.ucm.es
007 * 10/01/2007
008 */
009package es.ucm.fdi.gaia.jcolibri.util;
010
011import java.io.File;
012import java.io.IOException;
013import java.lang.reflect.Method;
014import java.net.URL;
015import java.net.URLClassLoader;
016
017import javax.xml.parsers.DocumentBuilder;
018import javax.xml.parsers.DocumentBuilderFactory;
019
020import org.apache.logging.log4j.LogManager;
021import org.w3c.dom.Document;
022import org.w3c.dom.NamedNodeMap;
023import org.w3c.dom.Node;
024import org.w3c.dom.NodeList;
025
026
027/**
028 * This class launches a jCOLIBRI application loading dinamically its libraries. 
029 * It has a method that parses the ".classpath" file of the eclipse project to find the libraries that a project needs.
030 * Then it loads the libraries and executes an application.
031 * This eases the process of invoking a jCOLIBRI application.
032 * 
033 * @author Juan A. Recio Garcia
034 * @version 2.0
035 */
036public class Launcher
037{
038
039    /**
040     * Main method used to launch any application loading the libraries from a eclipse classpath file.
041     * The first argument must be the class to launch and the second (optional) is the name of the eclipse classpath file.
042     * If this second argument is not specified it tries with ".classpath". 
043     */
044    public static void main(String[] args)
045    {
046        if(args.length == 0)
047        {
048                System.out.println("Usage: jcolibri.util.Launcher MainClass [eclipse_classpath_file]");
049                System.exit(0);
050        }
051
052        try {
053                String classpathfile = ".classpath";
054                if(args.length==2)
055                        classpathfile = args[1];
056                
057                System.out.println("Loading class path from file: "+classpathfile);
058                                
059                URL[] libraries = getClassPath(classpathfile);
060                for(int i=0; i<libraries.length; i++)
061                {
062                        addURLtoClassLoader(libraries[i]);
063                        System.out.println("Adding library: "+libraries[i]);
064                }
065                
066                Class<?> mainClass = Class.forName(args[0]);
067                LogManager.getLogger(Launcher.class).info("Executing class: "+args[0]);
068                Method mainMethod = mainClass.getMethod("main", args.getClass());
069                
070                String[] newargs = new String[args.length-1];
071                for(int i=1; i<args.length; i++)
072                        newargs[i-1] = args[1];
073                
074                Object[] methodparams = new Object[1];
075                methodparams[0] = newargs;
076                mainMethod.invoke(null, methodparams);  
077        } catch (Exception e) {
078                LogManager.getLogger(Launcher.class).error("Launching class "+ e.getMessage());
079                e.printStackTrace();
080                }
081        LogManager.getLogger(Launcher.class).info("Launch finished");
082        //System.exit(0);
083    }
084
085    /**
086     * Loads a resource pointed by a URL into the Class Loader.
087     */
088    public static void addURLtoClassLoader(URL u) throws IOException {  
089        URLClassLoader sysloader = (URLClassLoader)ClassLoader.getSystemClassLoader();
090        Class<URLClassLoader> sysclass = URLClassLoader.class;
091     
092        try {
093                //Please don't read this code. It is a dark way to invoke a private method using reflection.
094                //The clear way consists on creating your own subclass of URLClassLoader.
095                Class<?>[] parameters = new Class<?>[]{URL.class};
096                Method method = sysclass.getDeclaredMethod("addURL",parameters);
097                method.setAccessible(true);
098                method.invoke(sysloader,new Object[]{ u });
099        } catch (Throwable t) {
100                t.printStackTrace();
101                throw new IOException("Error, could not add URL to system classloader");
102        }//end try catch        
103    }//end method
104    
105    /**
106     * Parses a eclipse classpath file returning a list of URLs to the libraries in that file.
107     */
108    protected static URL[] getClassPath(String classpathfile) throws Exception
109    {
110        
111        java.util.ArrayList<URL> CLASSPATH = new java.util.ArrayList<URL>();
112        try
113        {
114            DocumentBuilder db = DocumentBuilderFactory.newInstance()
115            .newDocumentBuilder();
116            Document doc = db.parse(classpathfile);
117                  
118            NodeList nl = doc.getElementsByTagName("classpathentry");
119            for(int i=0; i<nl.getLength(); i++)
120            {
121                Node n = nl.item(i);
122                NamedNodeMap nnm = n.getAttributes();
123                if(nnm.getNamedItem("kind").getNodeValue().equals("lib"))
124                {
125                    String lib = nnm.getNamedItem("path").getNodeValue();
126                    File f = new File(lib);
127                    CLASSPATH.add(f.toURI().toURL());
128                }
129            }
130        } catch (Exception e)
131        {
132                LogManager.getLogger(Launcher.class).error("Error obtaining classpath. Revise your classpath file \n"+e.getMessage());
133                throw e;
134        }
135
136        return (URL[])CLASSPATH.toArray(new URL[]{});
137    }
138
139}