Record test coverage per test case using eclEmma tool - java

I want to record test coverage per test case using eclEmma tool. The coverage should contain the % covered by that test case of the target class and also want to access the statements executed by that test case. Follwowing is the code which runs a test class and generates the coverage on test class itself.
package expJaCoCo;
public class Calculadora
{
public Calculadora() { }
public int add(int x, final int y) {
return x + y;
}
}
CalculadoraTest.java
package expJaCoCo;
import junit.framework.TestCase;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
public class CalculadoraTest extends TestCase
{
private Calculadora c1;
#BeforeClass
public void setUp() { c1 = new Calculadora(); }
#AfterClass
public void tearDown() { c1 = null; }
#Test
public void testAdd() { assertTrue(c1.add(1, 0) == 1); }
}
CoreTutorial.java
package expJaCoCo;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.jacoco.core.analysis.Analyzer;
import org.jacoco.core.analysis.CoverageBuilder;
import org.jacoco.core.analysis.IClassCoverage;
import org.jacoco.core.analysis.ICounter;
import org.jacoco.core.data.ExecutionDataStore;
import org.jacoco.core.instr.Instrumenter;
import org.jacoco.core.runtime.IRuntime;
import org.jacoco.core.runtime.LoggerRuntime;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
public class CoreTutorial
{
/**
* A class loader that loads classes from in-memory data.
*/
public static class MemoryClassLoader extends ClassLoader
{
private final Map<String, byte[]> definitions = new HashMap<String, byte[]>();
/**
* Add a in-memory representation of a class.
*
* #param name name of the class
* #param bytes class definition
*/
public void addDefinition(final String name, final byte[] bytes) {
definitions.put(name, bytes);
}
#Override
protected Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException
{
final byte[] bytes = definitions.get(name);
if (bytes != null)
return defineClass(name, bytes, 0, bytes.length);
return super.loadClass(name, resolve);
}
}
private InputStream getTargetClass(final String name)
{
final String resource = '/' + name.replace('.', '/') + ".class";
return getClass().getResourceAsStream(resource);
}
private void printCounter(final String unit, final ICounter counter)
{
final Integer missed = Integer.valueOf(counter.getMissedCount());
final Integer total = Integer.valueOf(counter.getTotalCount());
System.out.printf("%s of %s %s missed%n", missed, total, unit);
}
private String getColor(final int status)
{
switch (status) {
case ICounter.NOT_COVERED:
return "red";
case ICounter.PARTLY_COVERED:
return "yellow";
case ICounter.FULLY_COVERED:
return "green";
}
return "";
}
private void runTutorial() throws Exception
{
final String targetName = CalculadoraTest.class.getName();
// For instrumentation and runtime we need a IRuntime instance to collect execution data:
final IRuntime runtime = new LoggerRuntime();
// The Instrumenter creates a modified version of our test target class that contains additional probes for execution data recording:
final Instrumenter instr = new Instrumenter(runtime);
final byte[] instrumented = instr.instrument(getTargetClass(targetName));
// Now we're ready to run our instrumented class and need to startup the runtime first:
runtime.startup();
// In this tutorial we use a special class loader to directly load the instrumented class definition from a byte[] instances.
final MemoryClassLoader memoryClassLoader = new MemoryClassLoader();
memoryClassLoader.addDefinition(targetName, instrumented);
final Class<?> targetClass = memoryClassLoader.loadClass(targetName);
// Here we execute our test target class through its Runnable interface:
/*final Runnable targetInstance = (Runnable) targetClass.newInstance();
targetInstance.run();*/
JUnitCore junit = new JUnitCore();
Result result = junit.run(targetClass);
System.out.println(result.getRunTime());
// At the end of test execution we collect execution data and shutdown the runtime:
final ExecutionDataStore executionData = new ExecutionDataStore();
runtime.collect(executionData, null, false);
runtime.shutdown();
// Together with the original class definition we can calculate coverage information:
final CoverageBuilder coverageBuilder = new CoverageBuilder();
final Analyzer analyzer = new Analyzer(executionData, coverageBuilder);
analyzer.analyzeClass(getTargetClass(targetName));
// Let's dump some metrics and line coverage information:
for (final IClassCoverage cc : coverageBuilder.getClasses())
{
System.out.printf("Coverage of class %s%n", cc.getName());
printCounter("instructions", cc.getInstructionCounter());
printCounter("branches", cc.getBranchCounter());
printCounter("lines", cc.getLineCounter());
printCounter("methods", cc.getMethodCounter());
printCounter("complexity", cc.getComplexityCounter());
for (int i = cc.getFirstLine(); i <= cc.getLastLine(); i++) {
System.out.printf("Line %s: %s%n", Integer.valueOf(i), getColor(cc.getLine(i).getStatus()));
}
}
}
public static void main(final String[] args) throws Exception {
new CoreTutorial().runTutorial();
}
}
This example executes and instrument CalculadoraTest and provide the coverage of CalculadoraTest.java, but I want the coverage of Calculadora.java
How can I change the code to get the desired result.

This example executes and instrument CalculadoraTest and provide the coverage of CalculadoraTest.java, but I want the coverage of Calculadora.java How can I change the code to get the desired result.
targetName that is CalculadoraTest.class.getName() is used for both coverage instrumentation/analysis by JaCoCo and execution by JUnit, however in the first case should be Calculadora.class.getName().
Using JaCoCo 0.7.7 APIs:
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.jacoco.core.analysis.Analyzer;
import org.jacoco.core.analysis.CoverageBuilder;
import org.jacoco.core.analysis.IClassCoverage;
import org.jacoco.core.analysis.ICounter;
import org.jacoco.core.data.ExecutionDataStore;
import org.jacoco.core.instr.Instrumenter;
import org.jacoco.core.runtime.IRuntime;
import org.jacoco.core.runtime.LoggerRuntime;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.jacoco.core.runtime.RuntimeData;
import org.jacoco.core.data.SessionInfoStore;
public class CoreTutorialTest
{
/**
* A class loader that loads classes from in-memory data.
*/
public static class MemoryClassLoader extends ClassLoader
{
private final Map<String, byte[]> definitions = new HashMap<String, byte[]>();
/**
* Add a in-memory representation of a class.
*
* #param name name of the class
* #param bytes class definition
*/
public void addDefinition(final String name, final byte[] bytes) {
definitions.put(name, bytes);
}
#Override
protected Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException
{
final byte[] bytes = definitions.get(name);
if (bytes != null)
return defineClass(name, bytes, 0, bytes.length);
return super.loadClass(name, resolve);
}
}
private InputStream getTargetClass(final String name)
{
final String resource = '/' + name.replace('.', '/') + ".class";
return getClass().getResourceAsStream(resource);
}
private void printCounter(final String unit, final ICounter counter)
{
final Integer missed = Integer.valueOf(counter.getMissedCount());
final Integer total = Integer.valueOf(counter.getTotalCount());
System.out.printf("%s of %s %s missed%n", missed, total, unit);
}
private String getColor(final int status)
{
switch (status) {
case ICounter.NOT_COVERED:
return "red";
case ICounter.PARTLY_COVERED:
return "yellow";
case ICounter.FULLY_COVERED:
return "green";
}
return "";
}
private void runTutorial() throws Exception
{
final String targetName = Calculadora.class.getName();
// For instrumentation and runtime we need a IRuntime instance to collect execution data:
final IRuntime runtime = new LoggerRuntime();
// The Instrumenter creates a modified version of our test target class that contains additional probes for execution data recording:
final Instrumenter instr = new Instrumenter(runtime);
final byte[] instrumented = instr.instrument(getTargetClass(targetName), "");
// Now we're ready to run our instrumented class and need to startup the runtime first:
final RuntimeData data = new RuntimeData();
runtime.startup(data);
// In this tutorial we use a special class loader to directly load the instrumented class definition from a byte[] instances.
final MemoryClassLoader memoryClassLoader = new MemoryClassLoader();
memoryClassLoader.addDefinition(targetName, instrumented);
final Class<?> targetClass = memoryClassLoader.loadClass(targetName);
// Here we execute our test target class through its Runnable interface:
/*final Runnable targetInstance = (Runnable) targetClass.newInstance();
targetInstance.run();*/
String junitName = CalculadoraTest.class.getName();
memoryClassLoader.addDefinition(junitName, instr.instrument(getTargetClass(junitName), ""));
final Class<?> junitClass = memoryClassLoader.loadClass(junitName);
JUnitCore junit = new JUnitCore();
Result result = junit.run(junitClass);
System.out.println("Failure count: " + result.getFailureCount());
// At the end of test execution we collect execution data and shutdown the runtime:
final ExecutionDataStore executionData = new ExecutionDataStore();
data.collect(executionData, new SessionInfoStore(), false);
runtime.shutdown();
// Together with the original class definition we can calculate coverage information:
final CoverageBuilder coverageBuilder = new CoverageBuilder();
final Analyzer analyzer = new Analyzer(executionData, coverageBuilder);
analyzer.analyzeClass(getTargetClass(targetName), targetName);
// Let's dump some metrics and line coverage information:
for (final IClassCoverage cc : coverageBuilder.getClasses())
{
System.out.printf("Coverage of class %s%n", cc.getName());
printCounter("instructions", cc.getInstructionCounter());
printCounter("branches", cc.getBranchCounter());
printCounter("lines", cc.getLineCounter());
printCounter("methods", cc.getMethodCounter());
printCounter("complexity", cc.getComplexityCounter());
for (int i = cc.getFirstLine(); i <= cc.getLastLine(); i++) {
System.out.printf("Line %s: %s%n", Integer.valueOf(i), getColor(cc.getLine(i).getStatus()));
}
}
}
public static void main(final String[] args) throws Exception {
new CoreTutorial().runTutorial();
}
}

Related

Tensorflow lite model(.tflite) in android is always giving the same result for text classification

I am trying to classify the messages that i receive into 5 categories(sports, politics, business, tech, entertainment), but for every message I send the tflite model classify it as sports ONLY.
this is my model:
i am using Average Word Vector model to train and test my data. and it gives me correct predictions when testing it. However, when I integrate the model into android studio, the model always predict the message as sports with high accuracy(around 95%)
!pip install -q tflite-model-maker
import numpy as np
import os
from tflite_model_maker import configs
from tflite_model_maker import ExportFormat
from tflite_model_maker import model_spec
from tflite_model_maker import text_classifier
from tflite_model_maker import TextClassifierDataLoader
import pandas as pd
import tensorflow as tf
assert tf.__version__.startswith('2')
data = pd.read_csv("bbc-text.csv")
print(data)
awv_spec = model_spec.get('average_word_vec')
awv_train_data = TextClassifierDataLoader.from_csv(
filename='bbc-text.csv',
text_column='text',
label_column='category',
model_spec=awv_spec,
is_training=True)
awv_test_data = TextClassifierDataLoader.from_csv(
filename='bbc-text1.csv',
text_column='text',
label_column='category',
model_spec=awv_spec,
is_training=False)
awv_model = text_classifier.create(awv_train_data, model_spec=awv_spec, epochs=20)
awv_model.evaluate(awv_test_data)
awv_model.export(export_dir='average_word_vec/')
and this is how i retrive info in android:
package com.example.letstalk.lib_interpreter;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.util.Log;
import com.example.letstalk.lib_interpreter.Result;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import org.tensorflow.lite.Interpreter;
import org.tensorflow.lite.support.metadata.MetadataExtractor;
public class TextClassificationClient {
private static final String TAG = "Interpreter";
private static final int SENTENCE_LEN = 256; // The maximum length of an input sentence.
// Simple delimiter to split words.
private static final String SIMPLE_SPACE_OR_PUNCTUATION = " |\\,|\\.|\\!|\\?|\n";
private static final String MODEL_PATH = "sentiment_analysis.tflite";
/*
* Reserved values in ImdbDataSet dic:
* dic["<PAD>"] = 0 used for padding
* dic["<START>"] = 1 mark for the start of a sentence
* dic["<UNKNOWN>"] = 2 mark for unknown words (OOV)
*/
private static final String START = "<START>";
private static final String PAD = "<PAD>";
private static final String UNKNOWN = "<UNKNOWN>";
/** Number of results to show in the UI. */
private static final int MAX_RESULTS = 3;
private final Context context;
private final Map<String, Integer> dic = new HashMap<>();
private final List<String> labels = new ArrayList<>();
private Interpreter tflite;
public TextClassificationClient(Context context) {
this.context = context;
}
/** Load the TF Lite model and dictionary so that the client can start classifying text. */
public void load() {
loadModel();
}
/** Load TF Lite model. */
private synchronized void loadModel() {
try {
// Load the TF Lite model
ByteBuffer buffer = loadModelFile(this.context.getAssets(), MODEL_PATH);
tflite = new Interpreter(buffer);
Log.v(TAG, "TFLite model loaded.");
// Use metadata extractor to extract the dictionary and label files.
MetadataExtractor metadataExtractor = new MetadataExtractor(buffer);
// Extract and load the dictionary file.
InputStream dictionaryFile = metadataExtractor.getAssociatedFile("vocab.txt");
loadDictionaryFile(dictionaryFile);
Log.v(TAG, "Dictionary loaded.");
// Extract and load the label file.
InputStream labelFile = metadataExtractor.getAssociatedFile("labels.txt");
loadLabelFile(labelFile);
Log.v(TAG, "Labels loaded.");
} catch (IOException ex) {
Log.e(TAG, "Error loading TF Lite model.\n", ex);
}
}
/** Free up resources as the client is no longer needed. */
public synchronized void unload() {
tflite.close();
dic.clear();
labels.clear();
}
/** Classify an input string and returns the classification results. */
public synchronized List<Result> classify(String text) {
// Pre-prosessing.
int[][] input = tokenizeInputText(text);
// Run inference.
Log.v(TAG, "Classifying text with TF Lite...");
float[][] output = new float[1][labels.size()];
tflite.run(input, output);
// Find the best classifications.
PriorityQueue<Result> pq =
new PriorityQueue<>(
MAX_RESULTS, (lhs, rhs) -> Float.compare(rhs.getConfidence(), lhs.getConfidence()));
for (int i = 0; i < labels.size(); i++) {
pq.add(new Result("" + i, labels.get(i), output[0][i]));
}
final ArrayList<Result> results = new ArrayList<>();
while (!pq.isEmpty()) {
results.add(pq.poll());
}
Collections.sort(results);
// Return the probability of each class.
return results;
}
/** Load TF Lite model from assets. */
private static MappedByteBuffer loadModelFile(AssetManager assetManager, String modelPath)
throws IOException {
try (AssetFileDescriptor fileDescriptor = assetManager.openFd(modelPath);
FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor())) {
FileChannel fileChannel = inputStream.getChannel();
long startOffset = fileDescriptor.getStartOffset();
long declaredLength = fileDescriptor.getDeclaredLength();
return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength);
}
}
/** Load dictionary from model file. */
private void loadLabelFile(InputStream ins) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
// Each line in the label file is a label.
while (reader.ready()) {
labels.add(reader.readLine());
}
}
/** Load labels from model file. */
private void loadDictionaryFile(InputStream ins) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
// Each line in the dictionary has two columns.
// First column is a word, and the second is the index of this word.
while (reader.ready()) {
List<String> line = Arrays.asList(reader.readLine().split(" "));
if (line.size() < 2) {
continue;
}
dic.put(line.get(0), Integer.parseInt(line.get(1)));
}
}
/** Pre-prosessing: tokenize and map the input words into a float array. */
int[][] tokenizeInputText(String text) {
Log.d("hello", "tokenize: "+ text);
int[] tmp = new int[SENTENCE_LEN];
List<String> array = Arrays.asList(text.split(SIMPLE_SPACE_OR_PUNCTUATION));
int index = 0;
// Prepend <START> if it is in vocabulary file.
if (dic.containsKey(START)) {
tmp[index++] = dic.get(START);
}
for (String word : array) {
if (index >= SENTENCE_LEN) {
break;
}
tmp[index++] = dic.containsKey(word) ? dic.get(word) : (int) dic.get(UNKNOWN);
}
// Padding and wrapping.
Arrays.fill(tmp, index, SENTENCE_LEN - 1, (int) dic.get(PAD));
int[][] ans = {tmp};
return ans;
}
Map<String, Integer> getDic() {
return this.dic;
}
Interpreter getTflite() {
return this.tflite;
}
List<String> getLabels() {
return this.labels;
}
}

javax.tools.JavaCompiler compile into byte[] [duplicate]

This question already has answers here:
How do you dynamically compile and load external java classes? [duplicate]
(2 answers)
Closed 5 years ago.
I'm using the JavaCompiler from the javax.tools package (JDK 1.7) to compile some stuff on the fly, like this:
compiler.run(null, null, "-cp", paths, "path/to/my/file.java");
It works but I would like to do it all in memory (e.g. pass a string with the code, not the source file, and get the byte code back not a .class file). I found that extending the InputStream and OutputStream parameters is no use since it's probably just the same as in the console. Do you know a way to make the run method work like this? Or do you know a confirmed way to do this with the getTask() method? (extending the FileManager looks easy but isn't that easy :)
I've run the above code in Mac OS Java 7. None of them works. So i wrote one
https://github.com/trung/InMemoryJavaCompiler
StringBuilder source = new StringBuilder()
.append("package org.mdkt;\n")
.append("public class HelloClass {\n")
.append(" public String hello() { return \"hello\"; }")
.append("}");
Class<?> helloClass = InMemoryJavaCompiler.compile("org.mdkt.HelloClass", source.toString());
I think this here might be of help it basically shows how to compile Java source from memory (the string is located in the class).
It uses the PrinterWriter and StringWriter to write the source to a String/in memory and then uses the JavaCompiler class (since JDK 6) to compile and run the program:
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
public class CompileSourceInMemory {
public static void main(String args[]) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
StringWriter writer = new StringWriter();
PrintWriter out = new PrintWriter(writer);
out.println("public class HelloWorld {");
out.println(" public static void main(String args[]) {");
out.println(" System.out.println(\"This is in another java file\");");
out.println(" }");
out.println("}");
out.close();
JavaFileObject file = new JavaSourceFromString("HelloWorld", writer.toString());
Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);
boolean success = task.call();
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
System.out.println(diagnostic.getCode());
System.out.println(diagnostic.getKind());
System.out.println(diagnostic.getPosition());
System.out.println(diagnostic.getStartPosition());
System.out.println(diagnostic.getEndPosition());
System.out.println(diagnostic.getSource());
System.out.println(diagnostic.getMessage(null));
}
System.out.println("Success: " + success);
if (success) {
try {
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { new File("").toURI().toURL() });
Class.forName("HelloWorld", true, classLoader).getDeclaredMethod("main", new Class[] { String[].class }).invoke(null, new Object[] { null });
} catch (ClassNotFoundException e) {
System.err.println("Class not found: " + e);
} catch (NoSuchMethodException e) {
System.err.println("No such method: " + e);
} catch (IllegalAccessException e) {
System.err.println("Illegal access: " + e);
} catch (InvocationTargetException e) {
System.err.println("Invocation target: " + e);
}
}
}
}
class JavaSourceFromString extends SimpleJavaFileObject {
final String code;
JavaSourceFromString(String name, String code) {
super(URI.create("string:///" + name.replace('.','/') + Kind.SOURCE.extension),Kind.SOURCE);
this.code = code;
}
#Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return code;
}
}
If you have a look at the reference link you will find a few more other examples too
Reference:
Compiling from Memory
This is a class that compiles entirely in memory.
I've taken (almost) the entirety of this from http://javapracs.blogspot.de/2011/06/dynamic-in-memory-compilation-using.html by Rekha Kumari (June 2011). Though this version is more than 100 lines shorter and has considerably more features (but no docs:P).
It can compile multiple classes at once, which is the only way to compile classes that depend on each other. If you wonder about the class "CompilerFeedback": I was working on a tiny Java IDE for coding-games where I needed that. I'm including it here because I assume that you want to do something with this compiler, and the predigestion might help with that. (I realize that some of the code in the CompilerFeedback class is complete crap. It was recycled from a years old attempt.
There's also a utility method, not needed for compilation, that derives the full class name from a class' source code (incl. package name, if it's provided). Very useful for calling the compiler, which does need this information.
DEMO CLASS:
import java.util.ArrayList;
import java.util.List;
public class Demo {
public static void main(final String[] args) {
final InMemoryCompiler.IMCSourceCode cls1source;
final InMemoryCompiler.IMCSourceCode cls2source;
final StringBuilder sb = new StringBuilder();
sb.append("package toast;\n");
sb.append("public class DynaClass {\n");
sb.append(" public static void main(final String[] args) {");
sb.append(" System.out.println(\"Based massively on the work of Rekha Kumari, http://javapracs.blogspot.de/2011/06/dynamic-in-memory-compilation-using.html\");\n");
sb.append(" System.out.println(\"This is the main method speaking.\");\n");
sb.append(" System.out.println(\"Args: \" + java.util.Arrays.toString(args));\n");
sb.append(" final Test test = new Test();\n");
sb.append(" }\n");
sb.append(" public String toString() {\n");
sb.append(" return \"Hello, I am \" + ");
sb.append("this.getClass().getSimpleName();\n");
sb.append(" }\n");
sb.append("}\n");
cls1source = new InMemoryCompiler.IMCSourceCode("toast.DynaClass", sb.toString());
sb.setLength(0);
sb.append("package toast;\n");
sb.append("public class Test {\n");
sb.append(" public Test() {\n");
sb.append(" System.out.println(\"class Test constructor reporting in.\");\n");
sb.append(" System.out.println(new DynaClass());\n");
sb.append(" }\n");
sb.append("}\n");
cls2source = new InMemoryCompiler.IMCSourceCode("toast.Test", sb.toString());
final List<InMemoryCompiler.IMCSourceCode> classSources = new ArrayList<>();
classSources.add(cls1source);
classSources.add(cls2source);
final InMemoryCompiler uCompiler = new InMemoryCompiler(classSources);
final CompilerFeedback compilerFeedback = uCompiler.compile();
System.out.println("\n\nCOMPILER FEEDBACK: " + compilerFeedback);
if (compilerFeedback != null && compilerFeedback.success) {
try {
System.out.println("\nTOSTRING DEMO:");
uCompiler.runToString(cls1source.fullClassName);
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println("\nMAIN DEMO:");
uCompiler.runMain(cls1source.fullClassName, new String[] { "test1", "test2" });
} catch (Exception e) {
e.printStackTrace();
}
}
System.exit(0);
}
}
COMPILER CLASS:
import javax.tools.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
import java.security.SecureClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* MASSIVELY based on http://javapracs.blogspot.de/2011/06/dynamic-in-memory-compilation-using.html by Rekha Kumari
* (June 2011)
*/
final public class InMemoryCompiler {
final public static class IMCSourceCode {
final public String fullClassName;
final public String sourceCode;
/**
* #param fullClassName Full name of the class that will be compiled. If the class should be in some package,
* fullName should contain it too, for example: "testpackage.DynaClass"
* #param sourceCode the source code
*/
public IMCSourceCode(final String fullClassName, final String sourceCode) {
this.fullClassName = fullClassName;
this.sourceCode = sourceCode;
}
}
final public boolean valid;
final private List<IMCSourceCode> classSourceCodes;
final private JavaFileManager fileManager;
public InMemoryCompiler(final List<IMCSourceCode> classSourceCodes) {
this.classSourceCodes = classSourceCodes;
final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null) {
fileManager = null;
valid = false;
System.err.println("ToolProvider.getSystemJavaCompiler() returned null! This program needs to be run on a system with an installed JDK.");
return;
}
valid = true;
fileManager = new ForwardingJavaFileManager<JavaFileManager>(compiler.getStandardFileManager(null, null, null)) {
final private Map<String, ByteArrayOutputStream> byteStreams = new HashMap<>();
#Override
public ClassLoader getClassLoader(final Location location) {
return new SecureClassLoader() {
#Override
protected Class<?> findClass(final String className) throws ClassNotFoundException {
final ByteArrayOutputStream bos = byteStreams.get(className);
if (bos == null) {
return null;
}
final byte[] b = bos.toByteArray();
return super.defineClass(className, b, 0, b.length);
}
};
}
#Override
public JavaFileObject getJavaFileForOutput(final Location location, final String className, final JavaFileObject.Kind kind, final FileObject sibling) throws IOException {
return new SimpleJavaFileObject(URI.create("string:///" + className.replace('.', '/') + kind.extension), kind) {
#Override
public OutputStream openOutputStream() throws IOException {
ByteArrayOutputStream bos = byteStreams.get(className);
if (bos == null) {
bos = new ByteArrayOutputStream();
byteStreams.put(className, bos);
}
return bos;
}
};
}
};
}
public CompilerFeedback compile() {
if (!valid) {
return null;
}
final List<JavaFileObject> files = new ArrayList<>();
for (IMCSourceCode classSourceCode : classSourceCodes) {
URI uri = null;
try {
uri = URI.create("string:///" + classSourceCode.fullClassName.replace('.', '/') + JavaFileObject.Kind.SOURCE.extension);
} catch (Exception e) {
// e.printStackTrace();
}
if (uri != null) {
final SimpleJavaFileObject sjfo = new SimpleJavaFileObject(uri, JavaFileObject.Kind.SOURCE) {
#Override
public CharSequence getCharContent(final boolean ignoreEncodingErrors) {
return classSourceCode.sourceCode;
}
};
files.add(sjfo);
}
}
final DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (files.size() > 0) {
final JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, null, null, files);
return new CompilerFeedback(task.call(), diagnostics);
} else {
return null;
}
}
public void runToString(final String className) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
if (!valid) {
return;
}
final Class<?> theClass = getCompiledClass(className);
final Object instance = theClass.newInstance();
System.out.println(instance);
}
public void runMain(final String className, final String[] args) throws IllegalAccessException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
if (!valid) {
return;
}
final Class<?> theClass = getCompiledClass(className);
final Method mainMethod = theClass.getDeclaredMethod("main", String[].class);
mainMethod.invoke(null, new Object[] { args });
}
public Class<?> getCompiledClass(final String className) throws ClassNotFoundException {
if (!valid) {
throw new IllegalStateException("InMemoryCompiler instance not usable because ToolProvider.getSystemJavaCompiler() returned null: No JDK installed.");
}
final ClassLoader classLoader = fileManager.getClassLoader(null);
final Class<?> ret = classLoader.loadClass(className);
if (ret == null) {
throw new ClassNotFoundException("Class returned by ClassLoader was null!");
}
return ret;
}
}
COMPILERFEEDBACK CLASS:
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
final public class CompilerFeedback {
final public boolean success;
final public List<CompilerMessage> messages = new ArrayList<>();
public CompilerFeedback(final Boolean success, final DiagnosticCollector<JavaFileObject> diagnostics) {
this.success = success != null && success;
for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
messages.add(new CompilerMessage(diagnostic));
}
}
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("SUCCESS: ").append(success).append('\n');
final int iTop = messages.size();
for (int i = 0; i < iTop; i++) {
sb.append("\n[MESSAGE ").append(i + 1).append(" OF ").append(iTop).append("]\n\n");
// sb.append(messages.get(i).toString()).append("\n");
// sb.append(messages.get(i).toStringForList()).append("\n");
sb.append(messages.get(i).toStringForDebugging()).append("\n");
}
return sb.toString();
}
final public static class CompilerMessage {
final public Diagnostic<? extends JavaFileObject> compilerInfo;
final public String typeOfProblem;
final public String typeOfProblem_forDebugging;
final public String multiLineMessage;
final public int lineNumber;
final public int columnNumber;
final public int textHighlightPos_lineStart;
final public int textHighlightPos_problemStart;
final public int textHighlightPos_problemEnd;
final public String sourceCode;
final public String codeOfConcern;
final public String codeOfConcernLong;
CompilerMessage(final Diagnostic<? extends JavaFileObject> diagnostic) {
final JavaFileObject sourceFileObject = diagnostic.getSource();
String sourceCodePreliminary = null;
if (sourceFileObject instanceof SimpleJavaFileObject) {
final SimpleJavaFileObject simpleSourceFileObject = (SimpleJavaFileObject) sourceFileObject;
try {
final CharSequence charSequence = simpleSourceFileObject.getCharContent(false);
sourceCodePreliminary = charSequence.toString();
} catch (IOException e) {
e.printStackTrace();
}
}
if (sourceCodePreliminary == null) {
sourceCode = "[SOURCE CODE UNAVAILABLE]";
} else {
sourceCode = sourceCodePreliminary;
}
compilerInfo = diagnostic;
typeOfProblem = diagnostic.getKind().name();
typeOfProblem_forDebugging = "toString() = " + diagnostic.getKind().toString() + "; name() = " + typeOfProblem;
lineNumber = (int) compilerInfo.getLineNumber();
columnNumber = (int) compilerInfo.getColumnNumber();
final int sourceLen = sourceCode.length();
textHighlightPos_lineStart = (int) Math.min(Math.max(0, diagnostic.getStartPosition()), sourceLen);
textHighlightPos_problemStart = (int) Math.min(Math.max(0, diagnostic.getPosition()), sourceLen);
textHighlightPos_problemEnd = (int) Math.min(Math.max(0, diagnostic.getEndPosition()), sourceLen);
final StringBuilder reformattedMessage = new StringBuilder();
final String message = diagnostic.getMessage(Locale.US);
final int messageCutOffPosition = message.indexOf("location:");
final String[] messageParts;
if (messageCutOffPosition >= 0) {
messageParts = message.substring(0, messageCutOffPosition).split("\n");
} else {
messageParts = message.split("\n");
}
for (String s : messageParts) {
String s2 = s.trim();
if (s2.length() > 0) {
boolean lengthChanged;
do {
final int lBeforeReplace = s2.length();
s2 = s2.replace(" ", " ");
lengthChanged = (s2.length() != lBeforeReplace);
} while (lengthChanged);
reformattedMessage.append(s2).append("\n");
}
}
codeOfConcern = sourceCode.substring(textHighlightPos_problemStart, textHighlightPos_problemEnd);
codeOfConcernLong = sourceCode.substring(textHighlightPos_lineStart, textHighlightPos_problemEnd);
if (!codeOfConcern.isEmpty()) {
reformattedMessage.append("Code of concern: \"").append(codeOfConcern).append('\"');
}
multiLineMessage = reformattedMessage.toString();
}
public String toStringForList() {
if (compilerInfo == null) {
return "No compiler!";
} else {
return compilerInfo.getCode();
}
}
public String toStringForDebugging() {
final StringBuilder ret = new StringBuilder();
ret.append("Type of problem: ").append(typeOfProblem_forDebugging).append("\n\n");
ret.append("Message:\n").append(multiLineMessage).append("\n\n");
ret.append(compilerInfo.getCode()).append("\n\n");
ret.append("line number: ").append(lineNumber).append("\n");
ret.append("column number: ").append(columnNumber).append("\n");
ret.append("textHighlightPos_lineStart: ").append(textHighlightPos_lineStart).append("\n");
ret.append("textHighlightPos_problemStart: ").append(textHighlightPos_problemStart).append("\n");
ret.append("textHighlightPos_problemEnd: ").append(textHighlightPos_problemEnd).append("\n");
return ret.toString();
}
#Override
public String toString() {
// return compilerInfo.getMessage(Locale.US);
return typeOfProblem + ": " + multiLineMessage + "\n";
}
}
}
UTILITY METHOD (Not needed for the three classes further up.):
final public static String PREFIX_CLASSNAME = "class ";
final public static String PREFIX_PACKAGENAME = "package ";
final public static String CHARSET_JAVAKEYWORDENDERS = " \n[](){}<>;,\"\\/*+-=%!&?#:";
/**
* #return e.g. "com.dreamspacepresident.TestClass" if the source's first root level "class" (I'm talking about {}
* hierarchy.) is named "TestClass", and if the "package" name is "com.dreamspacepresident". Null is returned if
* sourceCode is null or does not provide a class name. (Mind that the parsing is done in a quite crappy way.)
*/
public static String deriveFullClassNameFromSource(final String sourceCode) {
if (sourceCode == null) {
return null;
}
final int firstBr = sourceCode.indexOf('{');
if (firstBr >= 0) {
// DETERMINE CLASS NAME
final int firstClass = sourceCode.indexOf(PREFIX_CLASSNAME);
if (firstClass < firstBr) {
String className = sourceCode.substring(firstClass + PREFIX_CLASSNAME.length(), firstBr).trim();
final int classNameEnd = indexOfAnyOfThese(className, CHARSET_JAVAKEYWORDENDERS);
if (classNameEnd >= 0) {
className = className.substring(0, classNameEnd);
}
if (!className.isEmpty()) {
// DETERMINE PACKAGE NAME
String packageName = null;
final int firstPackage = sourceCode.indexOf(PREFIX_PACKAGENAME);
if (firstPackage >= 0 && firstPackage < firstBr && firstPackage < firstClass) {
packageName = sourceCode.substring(firstPackage + PREFIX_PACKAGENAME.length(), firstBr).trim();
final int packageNameEnd = indexOfAnyOfThese(packageName, CHARSET_JAVAKEYWORDENDERS);
if (packageNameEnd >= 0) {
packageName = packageName.substring(0, packageNameEnd);
}
}
return (packageName != null && !packageName.isEmpty() ? packageName + "." : "") + className;
}
}
}
return null;
}
/**
* Looks for the first occurrence of ANY of the given characters, which is easier than using a bunch of
* String.indexOf() calls.
*
* #return -1 if not found, otherwise the String index of the first hit
*/
public static int indexOfAnyOfThese(final String text, final String characters) {
if (text != null && !text.isEmpty() && characters != null && !characters.isEmpty()) {
final int lenT = text.length();
final int lenC = characters.length();
for (int i = 0; i < lenT; i++) {
final char c = text.charAt(i);
for (int ii = 0; ii < lenC; ii++) {
if (c == characters.charAt(ii)) {
return i;
}
}
}
}
return -1;
}
I wrote a library to do this a few years ago. It takes a String which can contain nested classes, compiles them and optionally loads them into the current class loader (so you don't need an additional class loader) If the JVM is running in debug mode it will write the generated code to a file so you can step through your generated code.
http://vanillajava.blogspot.co.uk/2010_11_01_archive.html
To paraphrase the example from erolagnab you can do
StringBuilder sourceCode = new StringBuilder();
sourceCode.append("package org.mdkt;\n")
.append("public class HelloClass {\n")
.append(" public String hello() { return \"hello\"; }")
.append("}");
Class<?> helloClass = CACHED_COMPILER.compile("org.mdkt.HelloClass",
sourceCode.toString());
Update, the source is available here https://github.com/OpenHFT/Java-Runtime-Compiler
And you can obtain the latest build via maven http://search.maven.org/#browse%7C842970587
A longer example.
// this writes the file to disk only when debugging is enabled.
CachedCompiler cc = CompilerUtils.DEBUGGING ?
new CachedCompiler(new File(parent, "src/test/java"), new File(parent, "target/compiled")) :
CompilerUtils.CACHED_COMPILER;
String text = "generated test " + new Date();
Class fooBarTeeClass = cc.loadFromJava("eg.FooBarTee", "package eg;\n" +
'\n' +
"import eg.components.BarImpl;\n" +
"import eg.components.TeeImpl;\n" +
"import eg.components.Foo;\n" +
'\n' +
"public class FooBarTee{\n" +
" public final String name;\n" +
" public final TeeImpl tee;\n" +
" public final BarImpl bar;\n" +
" public final BarImpl copy;\n" +
" public final Foo foo;\n" +
'\n' +
" public FooBarTee(String name) {\n" +
" // when viewing this file, ensure it is synchronised with the copy on disk.\n" +
" System.out.println(\"" + text + "\");\n" +
" this.name = name;\n" +
'\n' +
" tee = new TeeImpl(\"test\");\n" +
'\n' +
" bar = new BarImpl(tee, 55);\n" +
'\n' +
" copy = new BarImpl(tee, 555);\n" +
'\n' +
" // you should see the current date here after synchronisation.\n" +
" foo = new Foo(bar, copy, \"" + text + "\", 5);\n" +
" }\n" +
'\n' +
" public void start() {\n" +
" }\n" +
'\n' +
" public void stop() {\n" +
" }\n" +
'\n' +
" public void close() {\n" +
" stop();\n" +
'\n' +
" }\n" +
"}\n");
// add a debug break point here and step into this method.
FooBarTee fooBarTee = new FooBarTee("test foo bar tee");
Foo foo = fooBarTee.foo;
assertNotNull(foo);
assertEquals(text, foo.s);
I wanted:
in-memory compilation of a java file (useful for Java as a scripting language)
No additional dependencies (easy to setup)
Implementation in as low number of files as possible (easy to incorporate in a project)
You can try it first here: http://ideone.com/cu1GhE#view_edit_box
The following code is based on Rekha Kumari code:
Main.java
package com.mycompany.java;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
//private static final Logger logger = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
try {
StringWriter writer = new StringWriter();
PrintWriter out = new PrintWriter(writer);
out.println("package com.mycompany.script;");
out.println("");
out.println("public class HelloWorld {");
out.println(" public static void main(String args[]) {");
out.println(" System.out.println(\"This is in another java file\");");
out.println(" }");
out.println("}");
out.close();
String fullName = "com.mycompany.script.HelloWorld";
String src = writer.toString();
DynamicCompiler uCompiler = new DynamicCompiler(fullName, src);
uCompiler.compile();
uCompiler.run();
} catch (Exception e) {
//logger.error("Exception:", e);
System.out.print("Exception");
}
}
}
DynamicCompiler.java
package com.mycompany.java;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
import javax.tools.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.security.SecureClassLoader;
import java.util.ArrayList;
import java.util.List;
// Based on: http://javapracs.blogspot.cz/2011/06/dynamic-in-memory-compilation-using.html
public class DynamicCompiler {
//private static final Logger logger = LoggerFactory.getLogger(DynamicCompiler.class);
private JavaFileManager fileManager;
private String fullName;
private String sourceCode;
public DynamicCompiler(String fullName, String srcCode) {
this.fullName = fullName;
this.sourceCode = srcCode;
this.fileManager = initFileManager();
}
public JavaFileManager initFileManager() {
if (fileManager != null)
return fileManager;
else {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
fileManager = new
ClassFileManager(compiler
.getStandardFileManager(null, null, null));
return fileManager;
}
}
public void compile() {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
List<JavaFileObject> files = new ArrayList<>();
files.add(new CharSequenceJavaFileObject(fullName, sourceCode));
compiler.getTask(
null,
fileManager,
null,
null,
null,
files
).call();
}
public void run() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
try {
fileManager
.getClassLoader(null)
.loadClass(fullName)
.getDeclaredMethod("main", new Class[]{String[].class})
.invoke(null, new Object[]{null});
} catch (InvocationTargetException e) {
System.out.print("InvocationTargetException");
//logger.error("InvocationTargetException:", e);
} catch (NoSuchMethodException e) {
System.out.print("NoSuchMethodException ");
//logger.error("NoSuchMethodException:", e);
}
}
public class CharSequenceJavaFileObject extends SimpleJavaFileObject {
/**
* CharSequence representing the source code to be compiled
*/
private CharSequence content;
public CharSequenceJavaFileObject(String className, CharSequence content) {
super(URI.create("string:///" + className.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
this.content = content;
}
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return content;
}
}
public class ClassFileManager extends ForwardingJavaFileManager {
private JavaClassObject javaClassObject;
public ClassFileManager(StandardJavaFileManager standardManager) {
super(standardManager);
}
#Override
public ClassLoader getClassLoader(Location location) {
return new SecureClassLoader() {
#Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
byte[] b = javaClassObject.getBytes();
return super.defineClass(name, javaClassObject.getBytes(), 0, b.length);
}
};
}
public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling) throws IOException {
this.javaClassObject = new JavaClassObject(className, kind);
return this.javaClassObject;
}
}
public class JavaClassObject extends SimpleJavaFileObject {
protected final ByteArrayOutputStream bos =
new ByteArrayOutputStream();
public JavaClassObject(String name, Kind kind) {
super(URI.create("string:///" + name.replace('.', '/')
+ kind.extension), kind);
}
public byte[] getBytes() {
return bos.toByteArray();
}
#Override
public OutputStream openOutputStream() throws IOException {
return bos;
}
}
}
I'd like to introduce my solution which runs well in production.
Here are the three source code files.
MemoryJavaCompiler.java
package me.soulmachine.compiler;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.tools.*;
/**
* Simple interface to Java compiler using JSR 199 Compiler API.
*/
public class MemoryJavaCompiler {
private javax.tools.JavaCompiler tool;
private StandardJavaFileManager stdManager;
public MemoryJavaCompiler() {
tool = ToolProvider.getSystemJavaCompiler();
if (tool == null) {
throw new RuntimeException("Could not get Java compiler. Please, ensure that JDK is used instead of JRE.");
}
stdManager = tool.getStandardFileManager(null, null, null);
}
/**
* Compile a single static method.
*/
public Method compileStaticMethod(final String methodName, final String className,
final String source)
throws ClassNotFoundException {
final Map<String, byte[]> classBytes = compile(className + ".java", source);
final MemoryClassLoader classLoader = new MemoryClassLoader(classBytes);
final Class clazz = classLoader.loadClass(className);
final Method[] methods = clazz.getDeclaredMethods();
for (final Method method : methods) {
if (method.getName().equals(methodName)) {
if (!method.isAccessible()) method.setAccessible(true);
return method;
}
}
throw new NoSuchMethodError(methodName);
}
public Map<String, byte[]> compile(String fileName, String source) {
return compile(fileName, source, new PrintWriter(System.err), null, null);
}
/**
* compile given String source and return bytecodes as a Map.
*
* #param fileName source fileName to be used for error messages etc.
* #param source Java source as String
* #param err error writer where diagnostic messages are written
* #param sourcePath location of additional .java source files
* #param classPath location of additional .class files
*/
private Map<String, byte[]> compile(String fileName, String source,
Writer err, String sourcePath, String classPath) {
// to collect errors, warnings etc.
DiagnosticCollector<JavaFileObject> diagnostics =
new DiagnosticCollector<JavaFileObject>();
// create a new memory JavaFileManager
MemoryJavaFileManager fileManager = new MemoryJavaFileManager(stdManager);
// prepare the compilation unit
List<JavaFileObject> compUnits = new ArrayList<JavaFileObject>(1);
compUnits.add(fileManager.makeStringSource(fileName, source));
return compile(compUnits, fileManager, err, sourcePath, classPath);
}
private Map<String, byte[]> compile(final List<JavaFileObject> compUnits,
final MemoryJavaFileManager fileManager,
Writer err, String sourcePath, String classPath) {
// to collect errors, warnings etc.
DiagnosticCollector<JavaFileObject> diagnostics =
new DiagnosticCollector<JavaFileObject>();
// javac options
List<String> options = new ArrayList<String>();
options.add("-Xlint:all");
// options.add("-g:none");
options.add("-deprecation");
if (sourcePath != null) {
options.add("-sourcepath");
options.add(sourcePath);
}
if (classPath != null) {
options.add("-classpath");
options.add(classPath);
}
// create a compilation task
javax.tools.JavaCompiler.CompilationTask task =
tool.getTask(err, fileManager, diagnostics,
options, null, compUnits);
if (task.call() == false) {
PrintWriter perr = new PrintWriter(err);
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
perr.println(diagnostic);
}
perr.flush();
return null;
}
Map<String, byte[]> classBytes = fileManager.getClassBytes();
try {
fileManager.close();
} catch (IOException exp) {
}
return classBytes;
}
}
MemoryJavaFileManager.java
package me.soulmachine.compiler;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.nio.CharBuffer;
import java.util.HashMap;
import java.util.Map;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
import javax.tools.SimpleJavaFileObject;
/**
* JavaFileManager that keeps compiled .class bytes in memory.
*/
#SuppressWarnings("unchecked")
final class MemoryJavaFileManager extends ForwardingJavaFileManager {
/** Java source file extension. */
private final static String EXT = ".java";
private Map<String, byte[]> classBytes;
public MemoryJavaFileManager(JavaFileManager fileManager) {
super(fileManager);
classBytes = new HashMap<>();
}
public Map<String, byte[]> getClassBytes() {
return classBytes;
}
public void close() throws IOException {
classBytes = null;
}
public void flush() throws IOException {
}
/**
* A file object used to represent Java source coming from a string.
*/
private static class StringInputBuffer extends SimpleJavaFileObject {
final String code;
StringInputBuffer(String fileName, String code) {
super(toURI(fileName), Kind.SOURCE);
this.code = code;
}
public CharBuffer getCharContent(boolean ignoreEncodingErrors) {
return CharBuffer.wrap(code);
}
}
/**
* A file object that stores Java bytecode into the classBytes map.
*/
private class ClassOutputBuffer extends SimpleJavaFileObject {
private String name;
ClassOutputBuffer(String name) {
super(toURI(name), Kind.CLASS);
this.name = name;
}
public OutputStream openOutputStream() {
return new FilterOutputStream(new ByteArrayOutputStream()) {
public void close() throws IOException {
out.close();
ByteArrayOutputStream bos = (ByteArrayOutputStream)out;
classBytes.put(name, bos.toByteArray());
}
};
}
}
public JavaFileObject getJavaFileForOutput(JavaFileManager.Location location,
String className,
Kind kind,
FileObject sibling) throws IOException {
if (kind == Kind.CLASS) {
return new ClassOutputBuffer(className);
} else {
return super.getJavaFileForOutput(location, className, kind, sibling);
}
}
static JavaFileObject makeStringSource(String fileName, String code) {
return new StringInputBuffer(fileName, code);
}
static URI toURI(String name) {
File file = new File(name);
if (file.exists()) {
return file.toURI();
} else {
try {
final StringBuilder newUri = new StringBuilder();
newUri.append("mfm:///");
newUri.append(name.replace('.', '/'));
if(name.endsWith(EXT)) newUri.replace(newUri.length() - EXT.length(), newUri.length(), EXT);
return URI.create(newUri.toString());
} catch (Exception exp) {
return URI.create("mfm:///com/sun/script/java/java_source");
}
}
}
}
MemoryClassLoader.java
package me.soulmachine.compiler;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
/**
* ClassLoader that loads .class bytes from memory.
*/
final class MemoryClassLoader extends URLClassLoader {
private Map<String, byte[]> classBytes;
public MemoryClassLoader(Map<String, byte[]> classBytes,
String classPath, ClassLoader parent) {
super(toURLs(classPath), parent);
this.classBytes = classBytes;
}
public MemoryClassLoader(Map<String, byte[]> classBytes, String classPath) {
this(classBytes, classPath, ClassLoader.getSystemClassLoader());
}
public MemoryClassLoader(Map<String, byte[]> classBytes) {
this(classBytes, null, ClassLoader.getSystemClassLoader());
}
public Class load(String className) throws ClassNotFoundException {
return loadClass(className);
}
public Iterable<Class> loadAll() throws ClassNotFoundException {
List<Class> classes = new ArrayList<Class>(classBytes.size());
for (String name : classBytes.keySet()) {
classes.add(loadClass(name));
}
return classes;
}
protected Class findClass(String className) throws ClassNotFoundException {
byte[] buf = classBytes.get(className);
if (buf != null) {
// clear the bytes in map -- we don't need it anymore
classBytes.put(className, null);
return defineClass(className, buf, 0, buf.length);
} else {
return super.findClass(className);
}
}
private static URL[] toURLs(String classPath) {
if (classPath == null) {
return new URL[0];
}
List<URL> list = new ArrayList<URL>();
StringTokenizer st = new StringTokenizer(classPath, File.pathSeparator);
while (st.hasMoreTokens()) {
String token = st.nextToken();
File file = new File(token);
if (file.exists()) {
try {
list.add(file.toURI().toURL());
} catch (MalformedURLException mue) {}
} else {
try {
list.add(new URL(token));
} catch (MalformedURLException mue) {}
}
}
URL[] res = new URL[list.size()];
list.toArray(res);
return res;
}
}
Explanations:
In order to represent a Java source file in memory instead of disk, I defined a StringInputBuffer class in the MemoryJavaFileManager.java.
To save the compiled .class files in memory, I implemented a class MemoryJavaFileManager. The main idea is to override the function getJavaFileForOutput() to store bytecodes into a map.
To load the bytecodes in memory, I have to implement a customized classloader MemoryClassLoader, which reads bytecodes in the map and turn them into classes.
Here is a unite test.
package me.soulmachine.compiler;
import org.junit.Test;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import static org.junit.Assert.assertEquals;
public class MemoryJavaCompilerTest {
private final static MemoryJavaCompiler compiler = new MemoryJavaCompiler();
#Test public void compileStaticMethodTest()
throws ClassNotFoundException, InvocationTargetException, IllegalAccessException {
final String source = "public final class Solution {\n"
+ "public static String greeting(String name) {\n"
+ "\treturn \"Hello \" + name;\n" + "}\n}\n";
final Method greeting = compiler.compileStaticMethod("greeting", "Solution", source);
final Object result = greeting.invoke(null, "soulmachine");
assertEquals("Hello soulmachine", result.toString());
}
}
Reference
JavaCompiler.java from Cloudera Morphlines
How to create an object from a string in Java (how to eval a string)?
InMemoryJavaCompiler
Java-Runtime-Compiler
[动态的Java - 无废话JavaCompilerAPI中文指南]
Compile and Run Java Source Code in Memory.
String fileToCompile = ;
JavaCompile compiler = ToolProvider.getSystemJavaCompiler();
if(
compiler.run(null, null, null, "PACKAGE_NAME" + java.io.File.separator +"CLASS_NAME.java") == 0
)
System.out.println("Compilation is successful");
else
System.out.println("Compilation Failed");

Cannot get custom annotations from Java class

I want to get class level annotation from Java class:
class FixAnnotation {
public String[] author;
}
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.TYPE)
public #interface Fix {
public String[] author() default "";
}
I tried this example of compiled java class:
#Component("test")
#Fix(
author = {"Example author 1", "Example author 2"}
)
public class Order implements Action {
..
}
But when I try:
public List listLocalFilesAndDirsAllLevels(File baseDir) {
List<File> collectedFilesAndDirs = new ArrayList<>();
Deque<File> remainingDirs = new ArrayDeque<>();
if(baseDir.exists()) {
remainingDirs.add(baseDir);
while(!remainingDirs.isEmpty()) {
File dir = remainingDirs.removeLast();
List<File> filesInDir = Arrays.asList(dir.listFiles());
for(File fileOrDir : filesInDir) {
// We need to process only .class files
if(fileOrDir.getName().endsWith(".class")){
collectedFilesAndDirs.add(fileOrDir);
if(fileOrDir.isDirectory()) {
remainingDirs.add(fileOrDir);
}
}
}
}
}
return collectedFilesAndDirs;
}
List<File> list;
for(int i=0; i<list.size(); i++) {
File item = list.get(i);
System.out.println(item.getName());
Fix name = item.getClass().getAnnotation(Fix.class);
out.println("author: " + name.author());
}
I get NPE. Do you know how I can get the annotation content?
EDIT:
I tried this:
public static void main() throws Exception
{
final File folder = new File("/opt/test");
processAnnotatedFiles(listLocalFilesAndDirsAllLevels(folder));
}
public void processAnnotatedFiles(List<File> list) throws IOException, ClassNotFoundException {
out.println("Directory files size " + list.size());
for(int i=0; i<list.size(); i++) {
out.println("File " + list.get(i).getName());
File file = list.get(i);
String path = file.getPath();
String[] authors = getFixFromClassFile(Paths.get(path));
System.out.println(Arrays.toString(authors));
}
}
public List<File> listLocalFilesAndDirsAllLevels(File baseDir) {
List<File> collectedFilesAndDirs = new ArrayList<>();
Deque<File> remainingDirs = new ArrayDeque<>();
if(baseDir.exists()) {
remainingDirs.add(baseDir);
while(!remainingDirs.isEmpty()) {
File dir = remainingDirs.removeLast();
List<File> filesInDir = Arrays.asList(dir.listFiles());
for(File fileOrDir : filesInDir) {
// We need to process only .class files
if(fileOrDir.getName().endsWith(".class")){
collectedFilesAndDirs.add(fileOrDir);
if(fileOrDir.isDirectory()) {
remainingDirs.add(fileOrDir);
}
}
}
}
}
return collectedFilesAndDirs;
}
private String[] getFixFromClassFile(Path pathToClass) throws MalformedURLException, ClassNotFoundException {
// Create class loader based on path
URLClassLoader loader = new URLClassLoader(new URL[]{pathToClass.toUri().toURL()});
// convert path to class with package
String classWithPackage = getClassWithPackageFromPath(pathToClass);
// Load class dynamically
Class<?> clazz = loader.loadClass(classWithPackage);
Fix fix = clazz.getAnnotation(Fix.class);
if (fix == null) {
return new String[0];
}
return fix.author();
}
private String getClassWithPackageFromPath(Path pathToClass) {
final String packageStartsFrom = "com.";
final String classFileExtension = ".class";
final String pathWithDots = pathToClass.toString().replace(File.separator, ".");
return pathWithDots.substring(pathWithDots.indexOf(packageStartsFrom)).replace(classFileExtension, "");
}
I get java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1927)
When you invoke getClass method on File object it will return java.io.File Class instance. This method does not load class from given file.
If you want to load a class from given *.class file you need to use java.lang.ClassLoader implementation. For example, java.net.URLClassLoader. Below you can find example how to load class and check annotation:
import java.io.File;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
#Fix(author = "Test author")
public class ReflectionApp {
public static void main(String[] args) throws Exception {
String path = "path/to/com/so/ReflectionApp.class";
String[] authors = getFixFromClassFile(Paths.get(path));
System.out.println(Arrays.toString(authors));
}
private static String[] getFixFromClassFile(Path pathToClass) throws MalformedURLException, ClassNotFoundException {
// Create class loader based on path
URLClassLoader loader = new URLClassLoader(new URL[]{pathToClass.toUri().toURL()});
// convert path to class with package
String classWithPackage = getClassWithPackageFromPath(pathToClass);
// Load class dynamically
Class<?> clazz = loader.loadClass(classWithPackage);
Fix fix = clazz.getAnnotation(Fix.class);
if (fix == null) {
return new String[0];
}
return fix.author();
}
private static String getClassWithPackageFromPath(Path pathToClass) {
final String packageStartsFrom = "com.";
final String classFileExtension = ".class";
final String pathWithDots = pathToClass.toString().replace(File.separator, ".");
return pathWithDots.substring(pathWithDots.indexOf(packageStartsFrom)).replace(classFileExtension, "");
}
}
Above code prints:
[Test author]
See also:
Method to dynamically load java class files

In web3j, how do you create a TypeReference for array types discovered at runtime?

I'm trying to write a Java application with web3j that can read an arbitrary abi file, show the list of AbiDefinitions to the user and let him make a call to a constant function of his choice. How do I compute the outTypes below?
AbiDefinition functionDef = ...; // found at runtime
List<Type> args = ...; // I know how to do this
List<NamedType> outputs = functionDef.getOutputs(); // list of output parameters
List<TypeReference<?>> outTypes = ????;
Function function = new Function(functionDef.getName(), args, outTypes);
The TypeReference class uses tricks with generic types that work when the generic type is hardcoded in the source code like this:
new TypeReference.StaticArrayTypeReference< StaticArray< Int256>>(2){}
This is what the generated contract wrapper would do.
For simple types, I can do this:
Class<Type> type = (Class<Type>)AbiTypes.getType(typeName);
TypeReference<?> typeRef = TypeReference.create(type);
For array types like "int256[2]", what should I do?
uniswapV2 router
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts)
package com.test;
import org.web3j.abi.FunctionEncoder;
import org.web3j.abi.FunctionReturnDecoder;
import org.web3j.abi.TypeReference;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.DynamicArray;
import org.web3j.abi.datatypes.Function;
import org.web3j.abi.datatypes.Type;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.request.Transaction;
import org.web3j.protocol.core.methods.response.EthCall;
import org.web3j.protocol.http.HttpService;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class main {
private static String EMPTY_ADDRESS = "0x0000000000000000000000000000000000000000";
static Web3j web3j;
static String usdt = "0x55d398326f99059fF775485246999027B3197955";
static String weth = "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c";
static String pancakeRouter = "0x10ed43c718714eb63d5aa57b78b54704e256024e";
public static void main(String[] args) throws IOException {
web3j = Web3j.build(new HttpService("https://bsc-dataseed.binance.org/"));
String s = web3j.netVersion().send().getNetVersion();
System.out.println(s);
List<BigInteger> list1 = getAmountsOut(usdt, weth);
System.out.println("result::: ");
for (BigInteger a : list1) {
System.out.println(a);
}
}
public static List<BigInteger> getAmountsOut(String tokenInAddr, String tokenOutAddr) {
String methodName = "getAmountsOut";
String fromAddr = EMPTY_ADDRESS;
List<Type> inputParameters = new ArrayList<Type>();
Uint256 inAmount = new Uint256(new BigInteger("1000000000000000000"));
Address inAddr = new Address(tokenInAddr);
Address outAddr = new Address(tokenOutAddr);
DynamicArray<Address> addrArr = new DynamicArray<Address>(inAddr, outAddr);
inputParameters.add(inAmount);
inputParameters.add(addrArr);
List<TypeReference<?>> outputParameters = new ArrayList<TypeReference<?>>();
TypeReference<DynamicArray<Uint256>> oa = new TypeReference<DynamicArray<Uint256>>() {
};
outputParameters.add(oa);
Function function = new Function(methodName, inputParameters, outputParameters);
String data = FunctionEncoder.encode(function);
Transaction transaction = Transaction.createEthCallTransaction(fromAddr, pancakeRouter, data);
EthCall ethCall;
try {
ethCall = web3j.ethCall(transaction, DefaultBlockParameterName.LATEST).sendAsync().get();
List<Type> results = FunctionReturnDecoder.decode(ethCall.getValue(), function.getOutputParameters());
System.out.println(results);
List<BigInteger> resultArr = new ArrayList<>();
if (results.size() > 0) {
for (Type tt : results) {
DynamicArray<Uint256> da = (DynamicArray<Uint256>) tt;
List<Uint256> lu = da.getValue();
if (lu.size() > 0) {
for (Uint256 n : lu) {
resultArr.add((BigInteger) n.getValue());
}
}
}
return resultArr;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

JavaCompiler compiled class not found [duplicate]

This question already has answers here:
Why do I get a ClassNotFoundException when using Class.forName(...)?
(2 answers)
Closed 8 years ago.
I have used JavaCompiler to compile a class that I generate on the fly. The compile task succeeds. I then try to load the compiled class using Class.forName("MyClass"); and it fails with a ClassNotFoundException. Is there a known issue with doing this?
package com.amir.method;
import java.io.*;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import javax.tools.*;
public class MethodGenerator {
private final static MethodGenerator INSTANCE = new MethodGenerator();
private MethodGenerator() {
}
public static MethodGenerator get() {
return INSTANCE;
}
public static void main(String[] args) {
final Class<?> clz = MethodGenerator.get().compile("Foo", "doIt"); //<- args ignored for now
}
public Class compile(final String className,
final String methodName) {
try {
return doCompile(className, methodName);
} catch(final Exception e) {
throw new RuntimeException(this.toString(), e);
}
}
private Class doCompile(final String className,
final String methodName) throws IOException, ClassNotFoundException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
StringWriter writer = new StringWriter();
PrintWriter out = new PrintWriter(writer);
out.println("public class HelloWorld {");
out.println(" public static void main(String args[]) {");
out.println(" System.out.println(\"This is in another java file\");");
out.println(" }");
out.println("}");
out.close();
final JavaFileObject file = new JavaSourceFromString("HelloWorld", writer.toString());
final Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
final String classPath = System.getProperty("java.class.path") + File.pathSeparator;
final String bootClassPath = System.getProperty("sun.boot.class.path") + File.pathSeparator;
final List<String> options = new ArrayList<String>();
options.add("-classpath");
final StringBuilder builder = new StringBuilder();
builder.append(classPath);
builder.append(bootClassPath);
final URLClassLoader urlClassLoader = (URLClassLoader) ClassLoaderResolver.getClassLoader();
for (final URL url : urlClassLoader.getURLs()) {
builder.append(url.getFile()).append(File.pathSeparator);
}
final int lastIndexOfColon = builder.lastIndexOf(File.pathSeparator);
builder.replace(lastIndexOfColon, lastIndexOfColon + 1, "");
options.add(builder.toString());
final JavaCompiler.CompilationTask task = compiler.getTask(null, null, diagnostics, options, null, compilationUnits);
boolean success = task.call();
if(success) {
final Class<?> cls = Class.forName("HelloWorld", true, urlClassLoader);
return cls;
}
return null;
}
class JavaSourceFromString extends SimpleJavaFileObject {
final String code;
JavaSourceFromString(String name, String code) {
super(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension),Kind.SOURCE);
this.code = code;
}
#Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return code;
}
}
}
Try to load the class after compiling it by using, Thread.currentThread().getContextClassLoader().loadClass("com.ur.class");
Found this...check if this can help..
// Create a new custom class loader, pointing to the directory that contains the compiled
// classes, this should point to the top of the package structure!
URLClassLoader classLoader = new URLClassLoader(new URL[]{new File("./").toURI().toURL()});
// Load the class from the classloader by name....
Class<?> loadedClass = classLoader.loadClass("com.ur.class");
// Create a new instance...
Object obj = loadedClass.newInstance();
// Santity check
if (obj instanceof com.ur.class) {
// code here ...
}
For more information refer this: How do you dynamically compile and load external java classes?

Categories