JavaCompilerCore/test/bytecode/JavaTXCompilerTest.java

72 lines
2.3 KiB
Java
Raw Normal View History

2017-08-30 16:08:05 +00:00
package bytecode;
import de.dhbwstuttgart.bytecode.BytecodeGen;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import org.junit.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static org.junit.Assert.*;
2017-10-05 17:21:30 +00:00
public class JavaTXCompilerTest {
2017-08-30 16:08:05 +00:00
private static final String rootDirectory = System.getProperty("user.dir")+"/test/javFiles/";
private static final List<File> filesToTest = new ArrayList<>();
@Test
public void test() throws IOException, java.lang.ClassNotFoundException {
2017-10-06 11:31:36 +00:00
System.out.println(rootDirectory);
2017-08-30 16:08:05 +00:00
filesToTest.add(new File(rootDirectory+"EmptyClass.jav"));
2017-10-05 17:21:30 +00:00
JavaTXCompiler compiler = new JavaTXCompiler(filesToTest);
2017-10-06 11:31:36 +00:00
System.out.println("test");
2017-08-30 16:08:05 +00:00
for(File f : filesToTest){
String content = readFile(f.getPath(), StandardCharsets.UTF_8);
2017-10-05 17:21:30 +00:00
HashMap<String,byte[]> bytecode = this.getBytecode(compiler.sourceFiles.get(f));
2017-08-30 16:08:05 +00:00
this.writeClassFile(bytecode, "EmptyClass");
}
}
public HashMap<String,byte[]> getBytecode(SourceFile sf) {
HashMap<String,byte[]> classFiles = new HashMap<>();
BytecodeGen bytecodeGen = new BytecodeGen(classFiles);
bytecodeGen.visit(sf);
return bytecodeGen.getClassFiles();
}
public void writeClassFile(HashMap<String,byte[]> classFiles, String name) {
FileOutputStream output;
byte[] bytecode = classFiles.get(name);
try {
System.out.println("generating .class file");
2017-11-03 13:17:36 +00:00
output = new FileOutputStream(new File(System.getProperty("user.dir") + "/testBytecode/generatedBC/" +name+".class"));
2017-08-30 16:08:05 +00:00
output.write(bytecode);
output.close();
System.out.println(".class file generated");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
}