/* <<<diasoft #DIA_DBMS_JAVA>>> Компиляция Java-исходников из SQL. */
|
package ru.rudb.java;
|
|
import java.io.ByteArrayOutputStream;
|
import java.io.OutputStream;
|
import java.net.URI;
|
import java.util.LinkedHashMap;
|
import java.util.List;
|
import java.util.Map;
|
|
import javax.tools.FileObject;
|
import javax.tools.ForwardingJavaFileManager;
|
import javax.tools.JavaCompiler;
|
import javax.tools.JavaFileObject;
|
import javax.tools.SimpleJavaFileObject;
|
import javax.tools.ToolProvider;
|
|
final class MemCompiler
|
{
|
private MemCompiler()
|
{
|
}
|
|
static Map<String, byte[]> compile(String dotted, String source)
|
{
|
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
|
if (compiler == null)
|
throw new IllegalStateException("нет javac в JDK");
|
final Map<String, ClassFile> written = new LinkedHashMap<String, ClassFile>();
|
javax.tools.StandardJavaFileManager files = compiler.getStandardFileManager(null, null, null);
|
ForwardingJavaFileManager<javax.tools.StandardJavaFileManager> mgr =
|
new ForwardingJavaFileManager<javax.tools.StandardJavaFileManager>(files)
|
{
|
@Override
|
public JavaFileObject getJavaFileForOutput(Location location, String className,
|
JavaFileObject.Kind kind, FileObject sibling)
|
{
|
String key = className.replace('.', '/');
|
ClassFile file = written.get(key);
|
if (file == null)
|
{
|
file = new ClassFile(className);
|
written.put(key, file);
|
}
|
return file;
|
}
|
};
|
JavaFileObject unit = new SourceFile(dotted, source);
|
ByteArrayOutputStream log = new ByteArrayOutputStream();
|
Boolean ok = compiler.getTask(new java.io.OutputStreamWriter(log), mgr, null,
|
List.of("--release", "11"), null, List.of(unit)).call();
|
Map<String, byte[]> out = new LinkedHashMap<String, byte[]>();
|
for (Map.Entry<String, ClassFile> entry : written.entrySet())
|
{
|
byte[] bytes = entry.getValue().bytes();
|
if (bytes.length > 0)
|
out.put(entry.getKey(), bytes);
|
}
|
if (ok == null || !ok || out.isEmpty())
|
throw new IllegalArgumentException(log.toString());
|
return out;
|
}
|
|
private static final class SourceFile extends SimpleJavaFileObject
|
{
|
private final String code;
|
|
SourceFile(String dotted, String code)
|
{
|
super(URI.create("string:///" + dotted.replace('.', '/') + ".java"), Kind.SOURCE);
|
this.code = code;
|
}
|
|
@Override
|
public CharSequence getCharContent(boolean ignoreEncodingErrors)
|
{
|
return code;
|
}
|
}
|
|
private static final class ClassFile extends SimpleJavaFileObject
|
{
|
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
|
|
ClassFile(String dotted)
|
{
|
super(URI.create("bytes:///" + dotted.replace('.', '/') + ".class"), Kind.CLASS);
|
}
|
|
@Override
|
public OutputStream openOutputStream()
|
{
|
return out;
|
}
|
|
byte[] bytes()
|
{
|
return out.toByteArray();
|
}
|
}
|
}
|