/**
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 *
 * Copyright (C)
 * <a href="http://www.inab.org">Spanish National Institute of Bioinformatics (INB)</a>
 * <a href="http://www.bsc.es">Barcelona Supercomputing Center (BSC)</a>
 * <a href="http://inb.bsc.es">Computational Node 6</a>
 */

package org.inb.util;

import java.util.Iterator;
import java.util.ServiceLoader;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

/**
 * Applets works with a Java Runtime and thus have no Java compiler accessible.
 * To fix this an external Java Compiler must provided along with an applet.
 * This helper class gets such a compiler either through a standard API or directly creating an object.
 * 
 * @author Dmitry Repchevsky
 */

public final class CompilerProvider
{
    private CompilerProvider() {}

    public static JavaCompiler getJavaCompiler ()
    {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

        if (compiler == null)
        {
            ServiceLoader<JavaCompiler> loader = java.util.ServiceLoader.load(JavaCompiler.class, CompilerProvider.class.getClassLoader());
            Iterator<JavaCompiler> iterator = loader.iterator();

            if (iterator.hasNext())
            {
                compiler = iterator.next();
            }
            else
            {
                try
                {
                    Class clazz = Class.forName("com.sun.tools.javac.api.JavacTool");
                    compiler = (JavaCompiler)clazz.newInstance();
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();

                    compiler = null;
                }
            }
        }

        return compiler;
    }
}
