All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ats.executor.java.JavaCodeEval Maven / Gradle / Ivy

The newest version!
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
 */

package com.ats.executor.java;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.tools.DiagnosticCollector;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

import com.ats.generator.variables.transform.EvalTransformer;

public class JavaCodeEval {

	private static final String ATS_EXECUTOR_CLASS = "AtsJavaExecutor";
	private String contentCode;

	public JavaCodeEval(String code) {
		if(code.endsWith(";")) {
			code = code.substring(0, code.length()-1);
		}
		contentCode = "public class " + ATS_EXECUTOR_CLASS + " implements com.ats.executor.java.IJavaCodeExecuter {@Override\npublic String execute(){return String.valueOf(" + code + ");}}";
	}

	@SuppressWarnings("unchecked")
	public String eval() throws Exception {

		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

		DiagnosticCollector diagnostics = new DiagnosticCollector<>();

		final JavaByteObject byteObject = new JavaByteObject(ATS_EXECUTOR_CLASS);

		StandardJavaFileManager standardFileManager = compiler.getStandardFileManager(diagnostics, null, null);

		JavaFileManager fileManager = createFileManager(standardFileManager, byteObject);

		List javaObjs = Arrays.asList(new JavaStringObject(ATS_EXECUTOR_CLASS, contentCode));
		JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, null, null, javaObjs);

		if (!task.call()) {
			final StringBuilder sj = new StringBuilder(" [");
			diagnostics.getDiagnostics().forEach(d -> sj.append(" ").append(d.getMessage(null)));
			return EvalTransformer.CODE_ERROR + sj.append(" ]").toString();
		}
		fileManager.close();

		final ClassLoader inMemoryClassLoader = createClassLoader(byteObject);

		Class exec = (Class) inMemoryClassLoader.loadClass(ATS_EXECUTOR_CLASS);

		return exec.getDeclaredConstructor().newInstance().execute();
	}

	private static JavaFileManager createFileManager(StandardJavaFileManager fileManager, JavaByteObject byteObject) {
		return new ForwardingJavaFileManager<>(fileManager) {
			@Override
			public JavaFileObject getJavaFileForOutput(Location location,
					String className, JavaFileObject.Kind kind,
					FileObject sibling) throws IOException {
				return byteObject;
			}
		};
	}

    private static ClassLoader createClassLoader(final JavaByteObject byteObject) {
        return new ClassLoader() {
            @Override
            public Class findClass(String name) throws ClassNotFoundException {
                //no need to search class path, we already have byte code.
                byte[] bytes = byteObject.getBytes();
                return defineClass(name, bytes, 0, bytes.length);
            }
        };
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy