use of org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException in project che by eclipse.
the class Util method getJdkLevel.
/**
* Get the jdk level of this root.
* The value can be:
* <ul>
* <li>major<<16 + minor : see predefined constants on ClassFileConstants </li>
* <li><code>0</null> if the root is a source package fragment root or if a Java model exception occured</li>
* </ul>
* Returns the jdk level
*/
public static long getJdkLevel(Object targetLibrary) {
try {
ClassFileReader reader = null;
if (targetLibrary instanceof IFolder) {
// only internal classfolders are allowed
IFile classFile = findFirstClassFile((IFolder) targetLibrary);
if (classFile != null)
reader = Util.newClassFileReader(classFile);
} else {
// root is a jar file or a zip file
ZipFile jar = null;
try {
IPath path = null;
if (targetLibrary instanceof IResource) {
path = ((IResource) targetLibrary).getFullPath();
} else if (targetLibrary instanceof File) {
File f = (File) targetLibrary;
if (!f.isDirectory()) {
path = new Path(((File) targetLibrary).getPath());
}
}
if (path != null) {
jar = JavaModelManager.getJavaModelManager().getZipFile(path);
for (Enumeration e = jar.entries(); e.hasMoreElements(); ) {
ZipEntry member = (ZipEntry) e.nextElement();
String entryName = member.getName();
if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(entryName)) {
reader = ClassFileReader.read(jar, entryName);
break;
}
}
}
} catch (CoreException e) {
// ignore
} finally {
JavaModelManager.getJavaModelManager().closeZipFile(jar);
}
}
if (reader != null) {
return reader.getVersion();
}
} catch (CoreException e) {
// ignore
} catch (ClassFormatException e) {
// ignore
} catch (IOException e) {
// ignore
}
return 0;
}
use of org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException in project tomcat by apache.
the class JDTCompiler method generateClass.
/**
* Compile the servlet from .java file to .class file
*/
@Override
protected void generateClass(Map<String, SmapStratum> smaps) throws FileNotFoundException, JasperException, Exception {
long t1 = 0;
if (log.isDebugEnabled()) {
t1 = System.currentTimeMillis();
}
final String sourceFile = ctxt.getServletJavaFileName();
final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath();
String packageName = ctxt.getServletPackageName();
final String targetClassName = ((packageName.length() != 0) ? (packageName + ".") : "") + ctxt.getServletClassName();
final ClassLoader classLoader = ctxt.getJspLoader();
String[] fileNames = new String[] { sourceFile };
String[] classNames = new String[] { targetClassName };
final List<JavacErrorDetail> problemList = new ArrayList<>();
class CompilationUnit implements ICompilationUnit {
private final String className;
private final String sourceFile;
CompilationUnit(String sourceFile, String className) {
this.className = className;
this.sourceFile = sourceFile;
}
@Override
public char[] getFileName() {
return sourceFile.toCharArray();
}
@Override
public char[] getContents() {
char[] result = null;
try (FileInputStream is = new FileInputStream(sourceFile);
InputStreamReader isr = new InputStreamReader(is, ctxt.getOptions().getJavaEncoding());
Reader reader = new BufferedReader(isr)) {
char[] chars = new char[8192];
StringBuilder buf = new StringBuilder();
int count;
while ((count = reader.read(chars, 0, chars.length)) > 0) {
buf.append(chars, 0, count);
}
result = new char[buf.length()];
buf.getChars(0, result.length, result, 0);
} catch (IOException e) {
log.error(Localizer.getMessage("jsp.error.compilation.source", sourceFile), e);
}
return result;
}
@Override
public char[] getMainTypeName() {
int dot = className.lastIndexOf('.');
if (dot > 0) {
return className.substring(dot + 1).toCharArray();
}
return className.toCharArray();
}
@Override
public char[][] getPackageName() {
StringTokenizer izer = new StringTokenizer(className, ".");
char[][] result = new char[izer.countTokens() - 1][];
for (int i = 0; i < result.length; i++) {
String tok = izer.nextToken();
result[i] = tok.toCharArray();
}
return result;
}
@Override
public boolean ignoreOptionalProblems() {
return false;
}
}
final INameEnvironment env = new INameEnvironment() {
@Override
public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < compoundTypeName.length; i++) {
if (i > 0) {
result.append('.');
}
result.append(compoundTypeName[i]);
}
return findType(result.toString());
}
@Override
public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) {
StringBuilder result = new StringBuilder();
int i = 0;
for (; i < packageName.length; i++) {
if (i > 0) {
result.append('.');
}
result.append(packageName[i]);
}
if (i > 0) {
result.append('.');
}
result.append(typeName);
return findType(result.toString());
}
private NameEnvironmentAnswer findType(String className) {
if (className.equals(targetClassName)) {
ICompilationUnit compilationUnit = new CompilationUnit(sourceFile, className);
return new NameEnvironmentAnswer(compilationUnit, null);
}
String resourceName = className.replace('.', '/') + ".class";
try (InputStream is = classLoader.getResourceAsStream(resourceName)) {
if (is != null) {
byte[] classBytes;
byte[] buf = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream(buf.length);
int count;
while ((count = is.read(buf, 0, buf.length)) > 0) {
baos.write(buf, 0, count);
}
baos.flush();
classBytes = baos.toByteArray();
char[] fileName = className.toCharArray();
ClassFileReader classFileReader = new ClassFileReader(classBytes, fileName, true);
return new NameEnvironmentAnswer(classFileReader, null);
}
} catch (IOException | ClassFormatException exc) {
log.error(Localizer.getMessage("jsp.error.compilation.dependent", className), exc);
}
return null;
}
private boolean isPackage(String result) {
if (result.equals(targetClassName) || result.startsWith(targetClassName + '$')) {
return false;
}
String resourceName = result.replace('.', '/') + ".class";
try (InputStream is = classLoader.getResourceAsStream(resourceName)) {
return is == null;
} catch (IOException e) {
// we are here, since close on is failed. That means it was not null
return false;
}
}
@Override
public boolean isPackage(char[][] parentPackageName, char[] packageName) {
StringBuilder result = new StringBuilder();
int i = 0;
if (parentPackageName != null) {
for (; i < parentPackageName.length; i++) {
if (i > 0) {
result.append('.');
}
result.append(parentPackageName[i]);
}
}
if (Character.isUpperCase(packageName[0])) {
if (!isPackage(result.toString())) {
return false;
}
}
if (i > 0) {
result.append('.');
}
result.append(packageName);
return isPackage(result.toString());
}
@Override
public void cleanup() {
}
};
final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
final Map<String, String> settings = new HashMap<>();
settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
settings.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE);
if (ctxt.getOptions().getJavaEncoding() != null) {
settings.put(CompilerOptions.OPTION_Encoding, ctxt.getOptions().getJavaEncoding());
}
if (ctxt.getOptions().getClassDebugInfo()) {
settings.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE);
}
// Source JVM
if (ctxt.getOptions().getCompilerSourceVM() != null) {
String opt = ctxt.getOptions().getCompilerSourceVM();
if (opt.equals("1.1")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_1);
} else if (opt.equals("1.2")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_2);
} else if (opt.equals("1.3")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
} else if (opt.equals("1.4")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
} else if (opt.equals("1.5")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
} else if (opt.equals("1.6")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_6);
} else if (opt.equals("1.7")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_7);
} else if (opt.equals("1.8")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_8);
// Version format changed from Java 9 onwards.
// Support old format that was used in EA implementation as well
} else if (opt.equals("9") || opt.equals("1.9")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_9);
} else if (opt.equals("10")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_10);
} else if (opt.equals("11")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_11);
} else if (opt.equals("12")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_12);
} else if (opt.equals("13")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_13);
} else if (opt.equals("14")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_14);
} else if (opt.equals("15")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_15);
} else if (opt.equals("16")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_16);
} else if (opt.equals("17")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_17);
} else if (opt.equals("18")) {
// Constant not available in latest ECJ version shipped with
// Tomcat. May be supported in a snapshot build.
// This is checked against the actual version below.
settings.put(CompilerOptions.OPTION_Source, "18");
} else {
log.warn(Localizer.getMessage("jsp.warning.unknown.sourceVM", opt));
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_11);
}
} else {
// Default to 11
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_11);
}
// Target JVM
if (ctxt.getOptions().getCompilerTargetVM() != null) {
String opt = ctxt.getOptions().getCompilerTargetVM();
if (opt.equals("1.1")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
} else if (opt.equals("1.2")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2);
} else if (opt.equals("1.3")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3);
} else if (opt.equals("1.4")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
} else if (opt.equals("1.5")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5);
} else if (opt.equals("1.6")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_6);
} else if (opt.equals("1.7")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_7);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_7);
} else if (opt.equals("1.8")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_8);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_8);
// Version format changed from Java 9 onwards.
// Support old format that was used in EA implementation as well
} else if (opt.equals("9") || opt.equals("1.9")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_9);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_9);
} else if (opt.equals("10")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_10);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_10);
} else if (opt.equals("11")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_11);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_11);
} else if (opt.equals("12")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_12);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_12);
} else if (opt.equals("13")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_13);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_13);
} else if (opt.equals("14")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_14);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_14);
} else if (opt.equals("15")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_15);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_15);
} else if (opt.equals("16")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_16);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_16);
} else if (opt.equals("17")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_17);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_17);
} else if (opt.equals("18")) {
// Constant not available in latest ECJ version shipped with
// Tomcat. May be supported in a snapshot build.
// This is checked against the actual version below.
settings.put(CompilerOptions.OPTION_TargetPlatform, "18");
settings.put(CompilerOptions.OPTION_Compliance, "18");
} else {
log.warn(Localizer.getMessage("jsp.warning.unknown.targetVM", opt));
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_11);
}
} else {
// Default to 11
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_11);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_11);
}
final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
final ICompilerRequestor requestor = new ICompilerRequestor() {
@Override
public void acceptResult(CompilationResult result) {
try {
if (result.hasProblems()) {
IProblem[] problems = result.getProblems();
for (IProblem problem : problems) {
if (problem.isError()) {
String name = new String(problem.getOriginatingFileName());
try {
problemList.add(ErrorDispatcher.createJavacError(name, pageNodes, new StringBuilder(problem.getMessage()), problem.getSourceLineNumber(), ctxt));
} catch (JasperException e) {
log.error(Localizer.getMessage("jsp.error.compilation.jdtProblemError"), e);
}
}
}
}
if (problemList.isEmpty()) {
ClassFile[] classFiles = result.getClassFiles();
for (ClassFile classFile : classFiles) {
char[][] compoundName = classFile.getCompoundName();
StringBuilder classFileName = new StringBuilder(outputDir).append('/');
for (int j = 0; j < compoundName.length; j++) {
if (j > 0) {
classFileName.append('/');
}
classFileName.append(compoundName[j]);
}
byte[] bytes = classFile.getBytes();
classFileName.append(".class");
try (FileOutputStream fout = new FileOutputStream(classFileName.toString());
BufferedOutputStream bos = new BufferedOutputStream(fout)) {
bos.write(bytes);
}
}
}
} catch (IOException exc) {
log.error(Localizer.getMessage("jsp.error.compilation.jdt"), exc);
}
}
};
ICompilationUnit[] compilationUnits = new ICompilationUnit[classNames.length];
for (int i = 0; i < compilationUnits.length; i++) {
String className = classNames[i];
compilationUnits[i] = new CompilationUnit(fileNames[i], className);
}
CompilerOptions cOptions = new CompilerOptions(settings);
// Check source/target JDK versions as the newest versions are allowed
// in Tomcat configuration but may not be supported by the ECJ version
// being used.
String requestedSource = ctxt.getOptions().getCompilerSourceVM();
if (requestedSource != null) {
String actualSource = CompilerOptions.versionFromJdkLevel(cOptions.sourceLevel);
if (!requestedSource.equals(actualSource)) {
log.warn(Localizer.getMessage("jsp.warning.unsupported.sourceVM", requestedSource, actualSource));
}
}
String requestedTarget = ctxt.getOptions().getCompilerTargetVM();
if (requestedTarget != null) {
String actualTarget = CompilerOptions.versionFromJdkLevel(cOptions.targetJDK);
if (!requestedTarget.equals(actualTarget)) {
log.warn(Localizer.getMessage("jsp.warning.unsupported.targetVM", requestedTarget, actualTarget));
}
}
cOptions.parseLiteralExpressionsAsConstants = true;
Compiler compiler = new Compiler(env, policy, cOptions, requestor, problemFactory);
compiler.compile(compilationUnits);
if (!ctxt.keepGenerated()) {
File javaFile = new File(ctxt.getServletJavaFileName());
if (!javaFile.delete()) {
throw new JasperException(Localizer.getMessage("jsp.warning.compiler.javafile.delete.fail", javaFile));
}
}
if (!problemList.isEmpty()) {
JavacErrorDetail[] jeds = problemList.toArray(new JavacErrorDetail[0]);
errDispatcher.javacError(jeds);
}
if (log.isDebugEnabled()) {
long t2 = System.currentTimeMillis();
log.debug("Compiled " + ctxt.getServletJavaFileName() + " " + (t2 - t1) + "ms");
}
if (ctxt.isPrototypeMode()) {
return;
}
// JSR45 Support
if (!options.isSmapSuppressed()) {
SmapUtil.installSmap(smaps);
}
}
use of org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException 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.classfmt.ClassFormatException 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.classfmt.ClassFormatException in project Japid by branaway.
the class NameEnv method findType.
private NameEnvironmentAnswer findType(final String name) {
try {
if (!name.startsWith("japidviews.")) {
// let super class loader to load the bytecode
// byte[] bytes = this.rendererCompiler.crlr.getClassDefinition(name);
byte[] bytes = this.rendererCompiler.crlr.getClassDefinition(name);
return bytes == null ? null : new NameEnvironmentAnswer(new ClassFileReader(bytes, name.toCharArray(), true), null);
} else {
char[] fileName = name.toCharArray();
RendererClass applicationClass = this.rendererCompiler.japidClasses.get(name);
// ApplicationClass exists
if (applicationClass != null) {
byte[] bytecode = applicationClass.getBytecode();
if (bytecode != null) {
ClassFileReader classFileReader = new ClassFileReader(bytecode, fileName, true);
return new NameEnvironmentAnswer(classFileReader, null);
}
// Cascade compilation
ICompilationUnit compilationUnit = new CompilationUnit(this.rendererCompiler, name);
return new NameEnvironmentAnswer(compilationUnit, null);
}
return null;
}
} catch (ClassFormatException e) {
// Something very very bad
throw new RuntimeException(e);
}
}
Aggregations