<commit_before>/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2009 - 2013 Board of Regents of the University of
 * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
 * Institute of Molecular Cell Biology and Genetics.
 * %%
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * The views and conclusions contained in the software and documentation are
 * those of the authors and should not be interpreted as representing official
 * policies, either expressed or implied, of any organization.
 * #L%
 */

package imagej.script.java;

import imagej.build.minimaven.BuildEnvironment;
import imagej.build.minimaven.Coordinate;
import imagej.build.minimaven.MavenProject;
import imagej.command.Command;
import imagej.command.CommandInfo;
import imagej.command.CommandService;
import imagej.script.AbstractScriptEngine;
import imagej.script.ScriptService;
import imagej.util.LineOutputStream;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.script.ScriptException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.scijava.Context;
import org.scijava.plugin.Plugin;
import org.scijava.plugin.PluginService;
import org.scijava.util.FileUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

/**
 * TODO
 * 
 * @author <NAME>
 */
public class JavaEngine extends AbstractScriptEngine {

	private final static String DEFAULT_GROUP_ID = "net.imagej";
	private final static String DEFAULT_VERSION = "1.0.0-SNAPSHOT";

	private final static String XALAN_INDENT_AMOUNT = "{http://xml.apache.org/xslt}indent-amount";
	{
		engineScopeBindings = new JavaEngineBindings();
	}

	@Override
	public Object eval(String script) throws ScriptException {
		return eval(new StringReader(script));
	}

	@SuppressWarnings({ "unchecked" })
	@Override
	public Object eval(Reader reader) throws ScriptException {
		final Writer writer = getContext().getErrorWriter();
		final PrintStream err;
		if (writer == null) {
			err = null;
		} else {
			err = new PrintStream(new LineOutputStream() {

				@Override
				public void println(final String line) throws IOException {
					writer.append(line).append('\n');
				}

			});
		}

		try {
			boolean verbose = "true".equals(get("verbose"));
			boolean debug = "true".equals(get("debug"));
			BuildEnvironment env = new BuildEnvironment(err, true, verbose, debug);
			final MavenProject project;
			String mainClass = null;

			final String path = (String)get(FILENAME);
			File file = path == null ? null : new File(path);
			if (file == null || !file.exists()) try {
				project = writeTemporaryProject(env, reader);
				mainClass = project.getMainClass();
			} catch (Exception e) {
				throw new ScriptException(e);
			} else {
				if (file.getName().equals("pom.xml")) {
					project = env.parse(file, null);
				} else {
					mainClass = getFullClassName(file);
					project = getMavenProject(env, file, mainClass);
				}
			}

			project.build(true);
			if (mainClass == null) {
				mainClass = project.getMainClass();
				if (mainClass == null) {
					throw new ScriptException("No main class found for file " + file);
				}
			}

			// make class loader
			String[] paths = project.getClassPath(false).split(File.pathSeparator);
			URL[] urls = new URL[paths.length];
			for (int i = 0; i < urls.length; i++)
				urls[i] = new URL("file:" + paths[i] + (paths[i].endsWith(".jar") ? "" : "/"));
			URLClassLoader classLoader = new URLClassLoader(urls, getClass().getClassLoader());

			// needed for sezpoz
			Thread.currentThread().setContextClassLoader(classLoader);

			// launch main class
			final Class<?> clazz = classLoader.loadClass(mainClass);
			if (Command.class.isAssignableFrom(clazz)) {
				final Context context = (Context)get(ScriptService.CONTEXT);
				final Plugin annotation = clazz.getAnnotation(Plugin.class);
				final CommandInfo info = new CommandInfo(mainClass, annotation) {

					@Override
					public Class<? extends Command> loadClass() {
						return (Class<? extends Command>) clazz;
					}
				};

				final PluginService pluginService = context.getService(PluginService.class);
				pluginService.addPlugin(info);

				final CommandService commandService = context.getService(CommandService.class);
				commandService.run(info);
			} else {
				Method main = clazz.getMethod("main", new Class[] { String[].class });
				main.invoke(null, new Object[] { new String[0] });
			}
		} catch (Exception e) {
			if (err != null) err.close();
			if (e instanceof ScriptException) throw (ScriptException)e;
			throw new ScriptException(e);
		} finally {
			if (err != null) err.close();
		}
		return null;
	}

	private MavenProject getMavenProject(final BuildEnvironment env,
			final File file, final String mainClass) throws IOException,
			ParserConfigurationException, SAXException, ScriptException,
			TransformerConfigurationException, TransformerException,
			TransformerFactoryConfigurationError {
		String path = file.getAbsolutePath();
		if (!path.replace(File.separatorChar, '.').endsWith("." + mainClass + ".java")) {
			throw new ScriptException("Class " + mainClass + " in invalid directory: " + path);
		}
		path = path.substring(0, path.length() - mainClass.length() - 5);
		if (path.replace(File.separatorChar, '/').endsWith("/src/main/java/")) {<commit_msg>JavaEngine: remove temporary directory after use<commit_after>/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2009 - 2013 Board of Regents of the University of
 * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
 * Institute of Molecular Cell Biology and Genetics.
 * %%
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * The views and conclusions contained in the software and documentation are
 * those of the authors and should not be interpreted as representing official
 * policies, either expressed or implied, of any organization.
 * #L%
 */

package imagej.script.java;

import imagej.build.minimaven.BuildEnvironment;
import imagej.build.minimaven.Coordinate;
import imagej.build.minimaven.MavenProject;
import imagej.command.Command;
import imagej.command.CommandInfo;
import imagej.command.CommandService;
import imagej.script.AbstractScriptEngine;
import imagej.script.ScriptService;
import imagej.util.LineOutputStream;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.script.ScriptException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.scijava.Context;
import org.scijava.plugin.Plugin;
import org.scijava.plugin.PluginService;
import org.scijava.util.FileUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

/**
 * TODO
 * 
 * @author <NAME>
 */
public class JavaEngine extends AbstractScriptEngine {

	private final static String DEFAULT_GROUP_ID = "net.imagej";
	private final static String DEFAULT_VERSION = "1.0.0-SNAPSHOT";

	private final static String XALAN_INDENT_AMOUNT = "{http://xml.apache.org/xslt}indent-amount";
	{
		engineScopeBindings = new JavaEngineBindings();
	}

	@Override
	public Object eval(String script) throws ScriptException {
		return eval(new StringReader(script));
	}

	@SuppressWarnings({ "unchecked" })
	@Override
	public Object eval(Reader reader) throws ScriptException {
		File temporaryDirectory = null;
		final Writer writer = getContext().getErrorWriter();
		final PrintStream err;
		if (writer == null) {
			err = null;
		} else {
			err = new PrintStream(new LineOutputStream() {

				@Override
				public void println(final String line) throws IOException {
					writer.append(line).append('\n');
				}

			});
		}

		try {
			boolean verbose = "true".equals(get("verbose"));
			boolean debug = "true".equals(get("debug"));
			BuildEnvironment env = new BuildEnvironment(err, true, verbose, debug);
			final MavenProject project;
			String mainClass = null;

			final String path = (String)get(FILENAME);
			File file = path == null ? null : new File(path);
			if (file == null || !file.exists()) try {
				project = writeTemporaryProject(env, reader);
				temporaryDirectory = project.getDirectory();
				mainClass = project.getMainClass();
			} catch (Exception e) {
				throw new ScriptException(e);
			} else {
				if (file.getName().equals("pom.xml")) {
					project = env.parse(file, null);
				} else {
					mainClass = getFullClassName(file);
					project = getMavenProject(env, file, mainClass);
				}
			}

			project.build(true);
			if (mainClass == null) {
				mainClass = project.getMainClass();
				if (mainClass == null) {
					throw new ScriptException("No main class found for file " + file);
				}
			}

			// make class loader
			String[] paths = project.getClassPath(false).split(File.pathSeparator);
			URL[] urls = new URL[paths.length];
			for (int i = 0; i < urls.length; i++)
				urls[i] = new URL("file:" + paths[i] + (paths[i].endsWith(".jar") ? "" : "/"));
			URLClassLoader classLoader = new URLClassLoader(urls, getClass().getClassLoader());

			// needed for sezpoz
			Thread.currentThread().setContextClassLoader(classLoader);

			// launch main class
			final Class<?> clazz = classLoader.loadClass(mainClass);
			if (Command.class.isAssignableFrom(clazz)) {
				final Context context = (Context)get(ScriptService.CONTEXT);
				final Plugin annotation = clazz.getAnnotation(Plugin.class);
				final CommandInfo info = new CommandInfo(mainClass, annotation) {

					@Override
					public Class<? extends Command> loadClass() {
						return (Class<? extends Command>) clazz;
					}
				};

				final PluginService pluginService = context.getService(PluginService.class);
				pluginService.addPlugin(info);

				final CommandService commandService = context.getService(CommandService.class);
				commandService.run(info);
			} else {
				Method main = clazz.getMethod("main", new Class[] { String[].class });
				main.invoke(null, new Object[] { new String[0] });
			}
		} catch (Exception e) {
			if (err != null) err.close();
			if (e instanceof ScriptException) throw (ScriptException)e;
			throw new ScriptException(e);
		} finally {
			if (err != null) err.close();
			if (temporaryDirectory != null && !FileUtils.deleteRecursively(temporaryDirectory)) {
				temporaryDirectory.deleteOnExit();
			}
		}
		return null;
	}

	private MavenProject getMavenProject(final BuildEnvironment env,
			final File file, final String mainClass) throws IOException,
			ParserConfigurationException, SAXException, ScriptException,
			TransformerConfigurationException, TransformerException,
			TransformerFactoryConfigurationError {
		String path = file.getAbsolutePath();
		if (!path.replace(File.separatorChar, '.').endsWith("." + mainClass + ".java")) {
			throw new ScriptException("Class " + mainClass + " in invalid directory: " + path);
		}
		path = path.substring(0, path.length() - mainClass.length() - 5);
		if (path.replace(File.separatorChar, '/').endsWith("/src/main/java/")) {
{'fraction_non_alphanumeric': 0.10500228265831867, 'fraction_numerical': 0.0024783147459727386, 'mean_word_length': 4.435661113080468, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 26}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4671533', 'n_tokens_mistral': 4815, 'n_tokens_neox': 4223, 'n_words': 1319}