use of org.eclipse.jdt.internal.compiler.env.INameEnvironment in project opennms by OpenNMS.
the class CustomJRJdtCompiler method compileUnits.
@Override
protected String compileUnits(final JRCompilationUnit[] units, String classpath, File tempDirFile) {
final INameEnvironment env = getNameEnvironment(units);
final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
final CompilerOptions options = getJdtSettings();
final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
final CompilerRequestor requestor = getCompilerRequestor(units);
final Compiler compiler = new Compiler(env, policy, options, requestor, problemFactory);
do {
CompilationUnit[] compilationUnits = requestor.processCompilationUnits();
compiler.compile(compilationUnits);
} while (requestor.hasMissingMethods());
requestor.processProblems();
return requestor.getFormattedProblems();
}
use of org.eclipse.jdt.internal.compiler.env.INameEnvironment in project drools by kiegroup.
the class EclipseJavaCompiler method compile.
public org.drools.compiler.commons.jci.compilers.CompilationResult compile(final String[] pSourceFiles, final ResourceReader pReader, final ResourceStore pStore, final ClassLoader pClassLoader, final JavaCompilerSettings pSettings) {
final Collection problems = new ArrayList();
final ICompilationUnit[] compilationUnits = new ICompilationUnit[pSourceFiles.length];
for (int i = 0; i < compilationUnits.length; i++) {
final String sourceFile = pSourceFiles[i];
if (pReader.isAvailable(sourceFile)) {
compilationUnits[i] = new CompilationUnit(pReader, sourceFile);
} else {
// log.error("source not found " + sourceFile);
final CompilationProblem problem = new CompilationProblem() {
public int getEndColumn() {
return 0;
}
public int getEndLine() {
return 0;
}
public String getFileName() {
return sourceFile;
}
public String getMessage() {
return "Source " + sourceFile + " could not be found";
}
public int getStartColumn() {
return 0;
}
public int getStartLine() {
return 0;
}
public boolean isError() {
return true;
}
public String toString() {
return getMessage();
}
};
if (problemHandler != null) {
problemHandler.handle(problem);
}
problems.add(problem);
}
}
if (problems.size() > 0) {
final CompilationProblem[] result = new CompilationProblem[problems.size()];
problems.toArray(result);
return new org.drools.compiler.commons.jci.compilers.CompilationResult(result);
}
final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
final INameEnvironment nameEnvironment = new INameEnvironment() {
public NameEnvironmentAnswer findType(final char[][] pCompoundTypeName) {
final StringBuilder result = new StringBuilder();
for (int i = 0; i < pCompoundTypeName.length; i++) {
if (i != 0) {
result.append('.');
}
result.append(pCompoundTypeName[i]);
}
return findType(result.toString());
}
public NameEnvironmentAnswer findType(final char[] pTypeName, final char[][] pPackageName) {
final StringBuilder result = new StringBuilder();
for (int i = 0; i < pPackageName.length; i++) {
result.append(pPackageName[i]);
result.append('.');
}
// log.debug("finding typeName=" + new String(typeName) + " packageName=" + result.toString());
result.append(pTypeName);
return findType(result.toString());
}
private NameEnvironmentAnswer findType(final String pClazzName) {
final String resourceName = ClassUtils.convertClassToResourcePath(pClazzName);
final byte[] clazzBytes = pStore.read(resourceName);
if (clazzBytes != null) {
try {
return createNameEnvironmentAnswer(pClazzName, clazzBytes);
} catch (final ClassFormatException e) {
throw new RuntimeException("ClassFormatException in loading class '" + pClazzName + "' with JCI.");
}
}
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
is = pClassLoader.getResourceAsStream(resourceName);
if (is == null) {
return null;
}
if (ClassUtils.isWindows() || ClassUtils.isOSX()) {
// check it really is a class, this issue is due to windows case sensitivity issues for the class org.kie.Process and path org/droosl/process
try {
pClassLoader.loadClass(pClazzName);
} catch (ClassNotFoundException e) {
return null;
} catch (NoClassDefFoundError e) {
return null;
}
}
final byte[] buffer = new byte[8192];
baos = new ByteArrayOutputStream(buffer.length);
int count;
while ((count = is.read(buffer, 0, buffer.length)) > 0) {
baos.write(buffer, 0, count);
}
baos.flush();
return createNameEnvironmentAnswer(pClazzName, baos.toByteArray());
} catch (final IOException e) {
throw new RuntimeException("could not read class", e);
} catch (final ClassFormatException e) {
throw new RuntimeException("wrong class format", e);
} finally {
try {
if (baos != null) {
baos.close();
}
} catch (final IOException oe) {
throw new RuntimeException("could not close output stream", oe);
}
try {
if (is != null) {
is.close();
}
} catch (final IOException ie) {
throw new RuntimeException("could not close input stream", ie);
}
}
}
private NameEnvironmentAnswer createNameEnvironmentAnswer(final String pClazzName, final byte[] clazzBytes) throws ClassFormatException {
final char[] fileName = pClazzName.toCharArray();
final ClassFileReader classFileReader = new ClassFileReader(clazzBytes, fileName, true);
return new NameEnvironmentAnswer(classFileReader, null);
}
private boolean isSourceAvailable(final String pClazzName, final ResourceReader pReader) {
// FIXME: this should not be tied to the extension
final String javaSource = pClazzName.replace('.', '/') + ".java";
final String classSource = pClazzName.replace('.', '/') + ".class";
return pReader.isAvailable(prefix + javaSource) || pReader.isAvailable(prefix + classSource);
}
private boolean isPackage(final String pClazzName) {
InputStream is = null;
try {
is = pClassLoader.getResourceAsStream(ClassUtils.convertClassToResourcePath(pClazzName));
if (is != null) {
if (ClassUtils.isWindows() || ClassUtils.isOSX()) {
try {
Class cls = pClassLoader.loadClass(pClazzName);
if (cls != null) {
return false;
}
} catch (ClassNotFoundException e) {
return true;
} catch (NoClassDefFoundError e) {
return true;
}
}
}
boolean result = is == null && !isSourceAvailable(pClazzName, pReader);
return result;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
throw new RuntimeException("Unable to close stream for resource: " + pClazzName);
}
}
}
}
public boolean isPackage(char[][] parentPackageName, char[] pPackageName) {
final StringBuilder result = new StringBuilder();
if (parentPackageName != null) {
for (int i = 0; i < parentPackageName.length; i++) {
if (i != 0) {
result.append('.');
}
result.append(parentPackageName[i]);
}
}
if (parentPackageName != null && parentPackageName.length > 0) {
result.append('.');
}
result.append(pPackageName);
return isPackage(result.toString());
}
public void cleanup() {
}
};
final ICompilerRequestor compilerRequestor = new ICompilerRequestor() {
public void acceptResult(final CompilationResult pResult) {
if (pResult.hasProblems()) {
final IProblem[] iproblems = pResult.getProblems();
for (int i = 0; i < iproblems.length; i++) {
final IProblem iproblem = iproblems[i];
final CompilationProblem problem = new EclipseCompilationProblem(iproblem);
if (problemHandler != null) {
problemHandler.handle(problem);
}
problems.add(problem);
}
}
if (!pResult.hasErrors()) {
final ClassFile[] clazzFiles = pResult.getClassFiles();
for (int i = 0; i < clazzFiles.length; i++) {
final ClassFile clazzFile = clazzFiles[i];
final char[][] compoundName = clazzFile.getCompoundName();
final StringBuilder clazzName = new StringBuilder();
for (int j = 0; j < compoundName.length; j++) {
if (j != 0) {
clazzName.append('.');
}
clazzName.append(compoundName[j]);
}
pStore.write(clazzName.toString().replace('.', '/') + ".class", clazzFile.getBytes());
}
}
}
};
final Map settingsMap = new EclipseJavaCompilerSettings(pSettings).toNativeSettings();
CompilerOptions compilerOptions = new CompilerOptions(settingsMap);
compilerOptions.parseLiteralExpressionsAsConstants = false;
final Compiler compiler = new Compiler(nameEnvironment, policy, compilerOptions, compilerRequestor, problemFactory);
if (ClassGenerator.DUMP_GENERATED_CLASSES) {
dumpUnits(compilationUnits, pReader);
}
compiler.compile(compilationUnits);
final CompilationProblem[] result = new CompilationProblem[problems.size()];
problems.toArray(result);
return new org.drools.compiler.commons.jci.compilers.CompilationResult(result);
}
use of org.eclipse.jdt.internal.compiler.env.INameEnvironment in project opennms by OpenNMS.
the class CustomJRJdtCompiler method getNameEnvironment.
protected INameEnvironment getNameEnvironment(final JRCompilationUnit[] units) {
final INameEnvironment env = new INameEnvironment() {
@Override
public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
final StringBuilder result = new StringBuilder();
String sep = "";
for (int i = 0; i < compoundTypeName.length; i++) {
result.append(sep);
result.append(compoundTypeName[i]);
sep = ".";
}
return findType(result.toString());
}
@Override
public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) {
final StringBuilder result = new StringBuilder();
String sep = "";
for (int i = 0; i < packageName.length; i++) {
result.append(sep);
result.append(packageName[i]);
sep = ".";
}
result.append(sep);
result.append(typeName);
return findType(result.toString());
}
private int getClassIndex(String className) {
int classIdx;
for (classIdx = 0; classIdx < units.length; ++classIdx) {
if (className.equals(units[classIdx].getName())) {
break;
}
}
if (classIdx >= units.length) {
classIdx = -1;
}
return classIdx;
}
private NameEnvironmentAnswer findType(String className) {
try {
int classIdx = getClassIndex(className);
if (classIdx >= 0) {
ICompilationUnit compilationUnit = new CompilationUnit(units[classIdx].getSourceCode(), className);
return new NameEnvironmentAnswer(compilationUnit, null);
}
String resourceName = className.replace('.', '/') + ".class";
InputStream is = getResource(resourceName);
if (is != null) {
try {
byte[] classBytes = JRLoader.loadBytes(is);
char[] fileName = className.toCharArray();
ClassFileReader classFileReader = new ClassFileReader(classBytes, fileName, true);
return new NameEnvironmentAnswer(classFileReader, null);
} finally {
try {
is.close();
} catch (IOException e) {
// ignore
}
}
}
} catch (JRException e) {
LOG.error("Compilation error", e);
} catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) {
LOG.error("Compilation error", exc);
} catch (IllegalArgumentException e) {
throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_NAME_ENVIRONMENT_ANSWER_INSTANCE_ERROR, (Object[]) null, e);
}
return null;
}
private boolean isPackage(String result) {
int classIdx = getClassIndex(result);
if (classIdx >= 0) {
return false;
}
String resourceName = result.replace('.', '/') + ".class";
boolean isPackage = true;
InputStream is = getResource(resourceName);
if (is != null) {
// 1.5 plugin
try {
isPackage = (is.read() > 0);
} catch (IOException e) {
// ignore
} finally {
try {
is.close();
} catch (IOException e) {
// ignore
}
}
}
return isPackage;
}
@Override
public boolean isPackage(char[][] parentPackageName, char[] packageName) {
final StringBuilder result = new StringBuilder();
String sep = "";
if (parentPackageName != null) {
for (int i = 0; i < parentPackageName.length; i++) {
result.append(sep);
result.append(parentPackageName[i]);
sep = ".";
}
}
if (Character.isUpperCase(packageName[0])) {
if (!isPackage(result.toString())) {
return false;
}
}
result.append(sep);
result.append(packageName);
return isPackage(result.toString());
}
@Override
public void cleanup() {
}
};
return env;
}
use of org.eclipse.jdt.internal.compiler.env.INameEnvironment in project querydsl by querydsl.
the class ECJEvaluatorFactory method compile.
protected void compile(String source, ClassType projectionType, String[] names, Type[] types, String id, Map<String, Object> constants) throws IOException {
// create source
source = createSource(source, projectionType, names, types, id, constants);
// compile
final char[] targetContents = source.toCharArray();
final String targetName = id;
final ICompilationUnit[] targetCompilationUnits = new ICompilationUnit[] { new ICompilationUnit() {
@Override
public char[] getContents() {
return targetContents;
}
@Override
public char[] getMainTypeName() {
int dot = targetName.lastIndexOf('.');
if (dot > 0) {
return targetName.substring(dot + 1).toCharArray();
} else {
return targetName.toCharArray();
}
}
@Override
public char[][] getPackageName() {
StringTokenizer tok = new StringTokenizer(targetName, ".");
char[][] result = new char[tok.countTokens() - 1][];
for (int j = 0; j < result.length; j++) {
result[j] = tok.nextToken().toCharArray();
}
return result;
}
@Override
public char[] getFileName() {
return CharOperation.concat(targetName.toCharArray(), ".java".toCharArray());
}
@Override
public boolean ignoreOptionalProblems() {
return true;
}
} };
INameEnvironment env = new INameEnvironment() {
private String join(char[][] compoundName, char separator) {
if (compoundName == null) {
return "";
} else {
List<String> parts = new ArrayList<>(compoundName.length);
for (char[] part : compoundName) {
parts.add(new String(part));
}
return parts.stream().collect(Collectors.joining(new String(new char[] { separator })));
}
}
@Override
public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
return findType(join(compoundTypeName, '.'));
}
@Override
public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) {
return findType(CharOperation.arrayConcat(packageName, typeName));
}
private boolean isClass(String result) {
if (result == null || result.isEmpty()) {
return false;
}
// if it's the class we're compiling, then of course it's a class
if (result.equals(targetName)) {
return true;
}
InputStream is = null;
try {
// if this is a class we've already compiled, it's a class
is = loader.getResourceAsStream(result);
if (is == null) {
// use our normal class loader now...
String resourceName = result.replace('.', '/') + ".class";
is = parentClassLoader.getResourceAsStream(resourceName);
if (is == null && !result.contains(".")) {
// we couldn't find the class, and it has no package; is it a core class?
is = parentClassLoader.getResourceAsStream("java/lang/" + resourceName);
}
}
return is != null;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ex) {
}
}
}
}
@Override
public boolean isPackage(char[][] parentPackageName, char[] packageName) {
// if the parent is a class, the child can't be a package
String parent = join(parentPackageName, '.');
if (isClass(parent)) {
return false;
}
// if the child is a class, it's not a package
String qualifiedName = (parent.isEmpty() ? "" : parent + ".") + new String(packageName);
return !isClass(qualifiedName);
}
@Override
public void cleanup() {
}
private NameEnvironmentAnswer findType(String className) {
String resourceName = className.replace('.', '/') + ".class";
InputStream is = null;
try {
// we're only asking ECJ to compile a single class; we shouldn't need this
if (className.equals(targetName)) {
return new NameEnvironmentAnswer(targetCompilationUnits[0], null);
}
is = loader.getResourceAsStream(resourceName);
if (is == null) {
is = parentClassLoader.getResourceAsStream(resourceName);
}
if (is != null) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[1024];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
ClassFileReader cfr = new ClassFileReader(buffer.toByteArray(), className.toCharArray(), true);
return new NameEnvironmentAnswer(cfr, null);
} else {
return null;
}
} catch (ClassFormatException | IOException ex) {
throw new RuntimeException(ex);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
}
};
ICompilerRequestor requestor = new ICompilerRequestor() {
@Override
public void acceptResult(CompilationResult result) {
if (result.hasErrors()) {
for (CategorizedProblem problem : result.getProblems()) {
if (problem.isError()) {
problemList.add(problem.getMessage());
}
}
} else {
for (ClassFile clazz : result.getClassFiles()) {
try {
MemJavaFileObject jfo = (MemJavaFileObject) fileManager.getJavaFileForOutput(StandardLocation.CLASS_OUTPUT, new String(clazz.fileName()), JavaFileObject.Kind.CLASS, null);
OutputStream os = jfo.openOutputStream();
os.write(clazz.getBytes());
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
}
};
problemList.clear();
IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.exitAfterAllProblems();
IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
try {
// Compiler compiler = new Compiler(env, policy, getCompilerOptions(), requestor, problemFactory, true);
Compiler compiler = new Compiler(env, policy, compilerOptions, requestor, problemFactory);
compiler.compile(targetCompilationUnits);
if (!problemList.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (String problem : problemList) {
sb.append("\t").append(problem).append("\n");
}
throw new CodegenException("Compilation of " + id + " failed:\n" + source + "\n" + sb.toString());
}
} catch (RuntimeException ex) {
// if we encountered an IOException, unbox and throw it;
// if we encountered a ClassFormatException, box it as an IOException and throw it
// otherwise, it's a legit RuntimeException,
// not one of our checked exceptions boxed as unchecked; just rethrow
Throwable cause = ex.getCause();
if (cause != null) {
if (cause instanceof IOException) {
throw (IOException) cause;
} else if (cause instanceof ClassFormatException) {
throw new IOException(cause);
}
}
throw ex;
}
}
use of org.eclipse.jdt.internal.compiler.env.INameEnvironment in project Japid by branaway.
the class RendererCompiler method compile.
/**
* Please compile this className and set the bytecode to the class holder
*/
@SuppressWarnings("deprecation")
public void compile(String[] classNames) {
ICompilationUnit[] compilationUnits = new CompilationUnit[classNames.length];
for (int i = 0; i < classNames.length; i++) {
compilationUnits[i] = new CompilationUnit(this, classNames[i]);
}
IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.exitOnFirstError();
IProblemFactory problemFactory = new DefaultProblemFactory(Locale.ENGLISH);
/**
* To find types ...
*/
INameEnvironment nameEnvironment = new NameEnv(this);
/**
* Compilation result
*/
ICompilerRequestor compilerRequestor = new CompilerRequestor(this);
/**
* The JDT compiler
*/
Compiler jdtCompiler = new Compiler(nameEnvironment, policy, settings, compilerRequestor, problemFactory) {
@Override
protected void handleInternalException(Throwable e, CompilationUnitDeclaration ud, CompilationResult result) {
}
};
// Go !
jdtCompiler.compile(compilationUnits);
}
Aggregations