List of usage examples for org.eclipse.jdt.internal.compiler ICompilerRequestor ICompilerRequestor
ICompilerRequestor
From source file:com.android.tools.lint.EcjParser.java
License:Apache License
/** Parse the given source units and class path and store it into the given output map */ public static INameEnvironment parse(CompilerOptions options, @NonNull List<ICompilationUnit> sourceUnits, @NonNull List<String> classPath, @NonNull Map<ICompilationUnit, CompilationUnitDeclaration> outputMap, @Nullable LintClient client) {//w w w . jav a 2s . co m INameEnvironment environment = new FileSystem(classPath.toArray(new String[classPath.size()]), new String[0], options.defaultEncoding); IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems(); IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault()); ICompilerRequestor requestor = new ICompilerRequestor() { @Override public void acceptResult(CompilationResult result) { // Not used; we need the corresponding CompilationUnitDeclaration for the source // units (the AST parsed from source) which we don't get access to here, so we // instead subclass AST to get our hands on them. } }; NonGeneratingCompiler compiler = new NonGeneratingCompiler(environment, policy, options, requestor, problemFactory, outputMap); try { compiler.compile(sourceUnits.toArray(new ICompilationUnit[sourceUnits.size()])); } catch (OutOfMemoryError e) { environment.cleanup(); // Since we're running out of memory, if it's all still held we could potentially // fail attempting to log the failure. Actively get rid of the large ECJ data // structure references first so minimize the chance of that //noinspection UnusedAssignment compiler = null; //noinspection UnusedAssignment environment = null; //noinspection UnusedAssignment requestor = null; //noinspection UnusedAssignment problemFactory = null; //noinspection UnusedAssignment policy = null; String msg = "Ran out of memory analyzing .java sources with ECJ: Some lint checks " + "may not be accurate (missing type information from the compiler)"; if (client != null) { // Don't log exception too; this isn't a compiler error per se where we // need to pin point the exact unlucky code that asked for memory when it // had already run out client.log(null, msg); } else { System.out.println(msg); } } catch (Throwable t) { if (client != null) { CompilationUnitDeclaration currentUnit = compiler.getCurrentUnit(); if (currentUnit == null || currentUnit.getFileName() == null) { client.log(t, "ECJ compiler crashed"); } else { client.log(t, "ECJ compiler crashed processing %1$s", new String(currentUnit.getFileName())); } } else { t.printStackTrace(); } environment.cleanup(); environment = null; } return environment; }
From source file:com.mysema.codegen.ECJEvaluatorFactory.java
License:Apache License
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/*w w w . java 2 s .com*/ 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 = Lists.newArrayListWithCapacity(compoundName.length); for (char[] part : compoundName) { parts.add(new String(part)); } return Joiner.on(separator).join(parts); } } @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 (Strings.isNullOrEmpty(result)) { 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) { ClassFileReader cfr = new ClassFileReader(ByteStreams.toByteArray(is), className.toCharArray(), true); return new NameEnvironmentAnswer(cfr, null); } else { return null; } } catch (ClassFormatException ex) { throw new RuntimeException(ex); } catch (IOException e) { throw new RuntimeException(e); } 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; } }
From source file:com.opensymphony.webwork.util.classloader.compilers.eclipse.EclipseJavaCompiler.java
License:Apache License
public void compile(final String[] pClazzNames, final ResourceReader pReader, final ResourceStore pStore, final CompilationProblemHandler pProblemHandler) { final Map settingsMap = settings.getMap(); final Set clazzIndex = new HashSet(); ICompilationUnit[] compilationUnits = new ICompilationUnit[pClazzNames.length]; for (int i = 0; i < compilationUnits.length; i++) { final String clazzName = pClazzNames[i]; compilationUnits[i] = new CompilationUnit(pReader, clazzName); clazzIndex.add(clazzName);//from w w w . ja v a2 s .c om log.debug("compiling " + clazzName); } final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems(); final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault()); final INameEnvironment nameEnvironment = new INameEnvironment() { public NameEnvironmentAnswer findType(final char[][] compoundTypeName) { final StringBuffer result = new StringBuffer(); for (int i = 0; i < compoundTypeName.length; i++) { if (i != 0) { result.append('.'); } result.append(compoundTypeName[i]); } return findType(result.toString()); } public NameEnvironmentAnswer findType(final char[] typeName, final char[][] packageName) { final StringBuffer result = new StringBuffer(); for (int i = 0; i < packageName.length; i++) { result.append(packageName[i]); result.append('.'); } result.append(typeName); return findType(result.toString()); } private NameEnvironmentAnswer findType(final String clazzName) { byte[] clazzBytes = pStore.read(clazzName); if (clazzBytes != null) { // log.debug("loading from store " + clazzName); final char[] fileName = clazzName.toCharArray(); try { final ClassFileReader classFileReader = new ClassFileReader(clazzBytes, fileName, true); return new NameEnvironmentAnswer(classFileReader, null); } catch (final ClassFormatException e) { log.error("wrong class format", e); } } else { if (pReader.isAvailable(clazzName.replace('.', '/') + ".java")) { log.debug("compile " + clazzName); ICompilationUnit compilationUnit = new CompilationUnit(pReader, clazzName); return new NameEnvironmentAnswer(compilationUnit, null); } final String resourceName = clazzName.replace('.', '/') + ".class"; final InputStream is = this.getClass().getClassLoader().getResourceAsStream(resourceName); if (is != null) { final byte[] buffer = new byte[8192]; final ByteArrayOutputStream baos = new ByteArrayOutputStream(buffer.length); int count; try { while ((count = is.read(buffer, 0, buffer.length)) > 0) { baos.write(buffer, 0, count); } baos.flush(); clazzBytes = baos.toByteArray(); final char[] fileName = clazzName.toCharArray(); ClassFileReader classFileReader = new ClassFileReader(clazzBytes, fileName, true); return new NameEnvironmentAnswer(classFileReader, null); } catch (final IOException e) { log.error("could not read class", e); } catch (final ClassFormatException e) { log.error("wrong class format", e); } finally { try { baos.close(); } catch (final IOException oe) { log.error("could not close output stream", oe); } try { is.close(); } catch (final IOException ie) { log.error("could not close input stream", ie); } } } } return null; } private boolean isPackage(final String clazzName) { final String resourceName = clazzName.replace('.', '/') + ".class"; final URL resource = this.getClass().getClassLoader().getResource(resourceName); return resource == null; } public boolean isPackage(char[][] parentPackageName, char[] packageName) { final StringBuffer result = new StringBuffer(); if (parentPackageName != null) { for (int i = 0; i < parentPackageName.length; i++) { if (i != 0) { result.append('.'); } result.append(parentPackageName[i]); } } if (Character.isUpperCase(packageName[0])) { return false; } if (parentPackageName != null && parentPackageName.length > 0) { result.append('.'); } result.append(packageName); return isPackage(result.toString()); } public void cleanup() { } }; final ICompilerRequestor compilerRequestor = new ICompilerRequestor() { public void acceptResult(CompilationResult result) { if (result.hasProblems()) { if (pProblemHandler != null) { final IProblem[] problems = result.getProblems(); for (int i = 0; i < problems.length; i++) { final IProblem problem = problems[i]; pProblemHandler.handle(new EclipseCompilationProblem(problem)); } } } if (!result.hasErrors()) { final ClassFile[] clazzFiles = result.getClassFiles(); for (int i = 0; i < clazzFiles.length; i++) { final ClassFile clazzFile = clazzFiles[i]; final char[][] compoundName = clazzFile.getCompoundName(); final StringBuffer clazzName = new StringBuffer(); for (int j = 0; j < compoundName.length; j++) { if (j != 0) { clazzName.append('.'); } clazzName.append(compoundName[j]); } pStore.write(clazzName.toString(), clazzFile.getBytes()); } } } }; pProblemHandler.onStart(); try { final Compiler compiler = new Compiler(nameEnvironment, policy, settingsMap, compilerRequestor, problemFactory); compiler.compile(compilationUnits); } finally { pProblemHandler.onStop(); } }
From source file:lombok.RunTestsViaEcj.java
License:Open Source License
@Override public void transformCode(Collection<CompilerMessage> messages, StringWriter result, File file, String encoding, Map<String, String> formatPreferences) throws Throwable { final AtomicReference<CompilationResult> compilationResult_ = new AtomicReference<CompilationResult>(); final AtomicReference<CompilationUnitDeclaration> compilationUnit_ = new AtomicReference<CompilationUnitDeclaration>(); ICompilerRequestor bitbucketRequestor = new ICompilerRequestor() { @Override// w ww .ja v a 2 s . c o m public void acceptResult(CompilationResult result) { compilationResult_.set(result); } }; String source = readFile(file); final CompilationUnit sourceUnit = new CompilationUnit(source.toCharArray(), file.getName(), encoding == null ? "UTF-8" : encoding); Compiler ecjCompiler = new Compiler(createFileSystem(file), ecjErrorHandlingPolicy(), ecjCompilerOptions(), bitbucketRequestor, new DefaultProblemFactory(Locale.ENGLISH)) { @Override protected synchronized void addCompilationUnit(ICompilationUnit inUnit, CompilationUnitDeclaration parsedUnit) { if (inUnit == sourceUnit) compilationUnit_.set(parsedUnit); super.addCompilationUnit(inUnit, parsedUnit); } }; ecjCompiler.compile(new ICompilationUnit[] { sourceUnit }); CompilationResult compilationResult = compilationResult_.get(); CategorizedProblem[] problems = compilationResult.getAllProblems(); if (problems != null) for (CategorizedProblem p : problems) { messages.add(new CompilerMessage(p.getSourceLineNumber(), p.getSourceStart(), p.isError(), p.getMessage())); } CompilationUnitDeclaration cud = compilationUnit_.get(); if (cud == null) result.append("---- NO CompilationUnit provided by ecj ----"); else result.append(cud.toString()); }
From source file:net.sf.jasperreports.engine.design.JRJdtCompiler.java
License:LGPL
protected ICompilerRequestor getCompilerRequestor(final JRCompilationUnit[] units, final StringBuffer problemBuffer) { final ICompilerRequestor requestor = new ICompilerRequestor() { public void acceptResult(CompilationResult result) { String className = ((CompilationUnit) result.getCompilationUnit()).className; int classIdx; for (classIdx = 0; classIdx < units.length; ++classIdx) { if (className.equals(units[classIdx].getName())) { break; }/*from w w w . j a v a 2 s. c o m*/ } if (result.hasErrors()) { String sourceCode = units[classIdx].getSourceCode(); IProblem[] problems = getJavaCompilationErrors(result); for (int i = 0; i < problems.length; i++) { IProblem problem = problems[i]; //if (problem.isError()) { problemBuffer.append(i + 1); problemBuffer.append(". "); problemBuffer.append(problem.getMessage()); if (problem.getSourceStart() >= 0 && problem.getSourceEnd() >= 0) { int problemStartIndex = sourceCode.lastIndexOf("\n", problem.getSourceStart()) + 1; int problemEndIndex = sourceCode.indexOf("\n", problem.getSourceEnd()); if (problemEndIndex < 0) { problemEndIndex = sourceCode.length(); } problemBuffer.append("\n"); problemBuffer.append(sourceCode.substring(problemStartIndex, problemEndIndex)); problemBuffer.append("\n"); for (int j = problemStartIndex; j < problem.getSourceStart(); j++) { problemBuffer.append(" "); } if (problem.getSourceStart() == problem.getSourceEnd()) { problemBuffer.append("^"); } else { problemBuffer.append("<"); for (int j = problem.getSourceStart() + 1; j < problem.getSourceEnd(); j++) { problemBuffer.append("-"); } problemBuffer.append(">"); } } problemBuffer.append("\n"); } } problemBuffer.append(problems.length); problemBuffer.append(" errors\n"); } if (problemBuffer.length() == 0) { ClassFile[] resultClassFiles = result.getClassFiles(); for (int i = 0; i < resultClassFiles.length; i++) { units[classIdx].setCompileData(resultClassFiles[i].getBytes()); } } } }; return requestor; }
From source file:org.apache.cocoon.components.language.programming.java.EclipseJavaCompiler.java
License:Apache License
public boolean compile() throws IOException { final String targetClassName = makeClassName(sourceFile); final ClassLoader classLoader = ClassUtils.getClassLoader(); String[] fileNames = new String[] { sourceFile }; String[] classNames = new String[] { targetClassName }; class CompilationUnit implements ICompilationUnit { String className;/*from ww w .j a va 2 s .c om*/ String sourceFile; CompilationUnit(String sourceFile, String className) { this.className = className; this.sourceFile = sourceFile; } public char[] getFileName() { return className.toCharArray(); } public char[] getContents() { char[] result = null; FileReader fr = null; try { fr = new FileReader(sourceFile); Reader reader = new BufferedReader(fr); if (reader != null) { char[] chars = new char[8192]; StringBuffer buf = new StringBuffer(); 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) { handleError(className, -1, -1, e.getMessage()); } return result; } public char[] getMainTypeName() { int dot = className.lastIndexOf('.'); if (dot > 0) { return className.substring(dot + 1).toCharArray(); } return className.toCharArray(); } 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; } } final INameEnvironment env = new INameEnvironment() { public NameEnvironmentAnswer findType(char[][] compoundTypeName) { StringBuffer result = new StringBuffer(); for (int i = 0; i < compoundTypeName.length; i++) { if (i > 0) { result.append("."); } result.append(compoundTypeName[i]); } return findType(result.toString()); } public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) { StringBuffer result = new StringBuffer(); for (int i = 0; i < packageName.length; i++) { if (i > 0) { result.append("."); } result.append(packageName[i]); } result.append("."); result.append(typeName); return findType(result.toString()); } private NameEnvironmentAnswer findType(String className) { try { if (className.equals(targetClassName)) { ICompilationUnit compilationUnit = new CompilationUnit(sourceFile, className); return new NameEnvironmentAnswer(compilationUnit); } String resourceName = className.replace('.', '/') + ".class"; 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); } } catch (IOException exc) { handleError(className, -1, -1, exc.getMessage()); } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) { handleError(className, -1, -1, exc.getMessage()); } return null; } private boolean isPackage(String result) { if (result.equals(targetClassName)) { return false; } String resourceName = result.replace('.', '/') + ".class"; InputStream is = classLoader.getResourceAsStream(resourceName); return is == null; } public boolean isPackage(char[][] parentPackageName, char[] packageName) { StringBuffer result = new StringBuffer(); if (parentPackageName != null) { for (int i = 0; i < parentPackageName.length; i++) { if (i > 0) { result.append("."); } result.append(parentPackageName[i]); } } String str = new String(packageName); if (Character.isUpperCase(str.charAt(0)) && !isPackage(result.toString())) { return false; } result.append("."); result.append(str); return isPackage(result.toString()); } public void cleanup() { // EMPTY } }; final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems(); final Map settings = new HashMap(9); settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); settings.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE); settings.put(CompilerOptions.OPTION_ReportUnusedImport, CompilerOptions.IGNORE); if (sourceEncoding != null) { settings.put(CompilerOptions.OPTION_Encoding, sourceEncoding); } if (debug) { settings.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); } // Set the sourceCodeVersion switch (this.compilerComplianceLevel) { case 150: settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5); settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5); break; case 140: settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4); break; default: settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3); } // Set the target platform switch (SystemUtils.JAVA_VERSION_INT) { case 150: settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5); break; case 140: settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4); break; default: settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3); } final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault()); final ICompilerRequestor requestor = new ICompilerRequestor() { public void acceptResult(CompilationResult result) { try { if (result.hasErrors()) { IProblem[] errors = result.getErrors(); for (int i = 0; i < errors.length; i++) { IProblem error = errors[i]; String name = new String(errors[i].getOriginatingFileName()); handleError(name, error.getSourceLineNumber(), -1, error.getMessage()); } } else { ClassFile[] classFiles = result.getClassFiles(); for (int i = 0; i < classFiles.length; i++) { ClassFile classFile = classFiles[i]; char[][] compoundName = classFile.getCompoundName(); StringBuffer className = new StringBuffer(); for (int j = 0; j < compoundName.length; j++) { if (j > 0) { className.append("."); } className.append(compoundName[j]); } byte[] bytes = classFile.getBytes(); String outFile = destDir + "/" + className.toString().replace('.', '/') + ".class"; FileOutputStream fout = new FileOutputStream(outFile); BufferedOutputStream bos = new BufferedOutputStream(fout); bos.write(bytes); bos.close(); } } } catch (IOException exc) { exc.printStackTrace(); } } }; 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); } Compiler compiler = new Compiler(env, policy, settings, requestor, problemFactory); compiler.compile(compilationUnits); return errors.size() == 0; }
From source file:org.apache.commons.jci.compilers.EclipseJavaCompiler.java
License:Apache License
public org.apache.commons.jci.compilers.CompilationResult compile(final String[] pSourceFiles, final ResourceReader pReader, final ResourceStore pStore, final ClassLoader pClassLoader, final JavaCompilerSettings pSettings) { final Map<String, String> settingsMap = new EclipseJavaCompilerSettings(pSettings).toNativeSettings(); final Collection<CompilationProblem> problems = new ArrayList<CompilationProblem>(); 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); log.debug("compiling " + sourceFile); } else {// ww w.jav a2 s . c o m // 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; } @Override 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.apache.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]); } //log.debug("finding compoundTypeName=" + result.toString()); 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) { if (isPackage(pClazzName)) { return null; } log.debug("finding " + pClazzName); final String resourceName = ConversionUtils.convertClassToResourcePath(pClazzName); final byte[] clazzBytes = pStore.read(resourceName); if (clazzBytes != null) { log.debug("loading from store " + pClazzName); final char[] fileName = pClazzName.toCharArray(); try { final ClassFileReader classFileReader = new ClassFileReader(clazzBytes, fileName, true); return new NameEnvironmentAnswer(classFileReader, null); } catch (final ClassFormatException e) { log.error("wrong class format", e); return null; } } log.debug("not in store " + pClazzName); final InputStream is = pClassLoader.getResourceAsStream(resourceName); if (is == null) { log.debug("class " + pClazzName + " not found"); return null; } final byte[] buffer = new byte[8192]; final ByteArrayOutputStream baos = new ByteArrayOutputStream(buffer.length); int count; try { while ((count = is.read(buffer, 0, buffer.length)) > 0) { baos.write(buffer, 0, count); } baos.flush(); final char[] fileName = pClazzName.toCharArray(); final ClassFileReader classFileReader = new ClassFileReader(baos.toByteArray(), fileName, true); return new NameEnvironmentAnswer(classFileReader, null); } catch (final IOException e) { log.error("could not read class", e); return null; } catch (final ClassFormatException e) { log.error("wrong class format", e); return null; } finally { try { baos.close(); } catch (final IOException oe) { log.error("could not close output stream", oe); } try { is.close(); } catch (final IOException ie) { log.error("could not close input stream", ie); } } } private boolean isPackage(final String pClazzName) { // reject this early as it is cheap if (pClazzName.contains("-")) { // "-" is not valid in package names return false; } final InputStream is = pClassLoader .getResourceAsStream(ConversionUtils.convertClassToResourcePath(pClazzName)); if (is != null) { log.debug("found the class for " + pClazzName + "- no package"); try { is.close(); } catch (final IOException ie) { log.error("could not close input stream", ie); } return false; } // FIXME: this should not be tied to the extension final String source = pClazzName.replace('.', '/') + ".java"; if (pReader.isAvailable(source)) { log.debug("found the source " + source + " for " + pClazzName + " - no package "); return false; } /* * See https://issues.apache.org/jira/browse/JCI-59 * At present, the code assumes that anything else is a package name * This is wrong, as for example jci.AdditionalTopLevel is not a package name. * It's not clear how to fix this in general. * It would seem to need access to the input classpath and/or the generated classes. */ return true; } 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]); } } // log.debug("isPackage parentPackageName=" + result.toString() + " packageName=" + new String(packageName)); if (parentPackageName != null && parentPackageName.length > 0) { result.append('.'); } result.append(pPackageName); return isPackage(result.toString()); } public void cleanup() { log.debug("cleanup"); } }; final ICompilerRequestor compilerRequestor = new ICompilerRequestor() { public void acceptResult(final CompilationResult pResult) { if (pResult.hasProblems()) { for (IProblem iproblem : pResult.getProblems()) { final CompilationProblem problem = new EclipseCompilationProblem(iproblem); if (problemHandler != null) { problemHandler.handle(problem); } problems.add(problem); } } if (!pResult.hasErrors()) { final ClassFile[] clazzFiles = pResult.getClassFiles(); for (ClassFile clazzFile : clazzFiles) { 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 Compiler compiler = new Compiler(nameEnvironment, policy, new CompilerOptions(settingsMap), compilerRequestor, problemFactory); compiler.compile(compilationUnits); final CompilationProblem[] result = new CompilationProblem[problems.size()]; problems.toArray(result); return new org.apache.commons.jci.compilers.CompilationResult(result); }
From source file:org.apache.jasper.compiler.JDTCompiler.java
License:Apache License
/** * Compile the servlet from .java file to .class file *///from w w w . j a v a2 s. co m @Override protected void generateClass(String[] smap) 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 ArrayList<JavacErrorDetail> problemList = new ArrayList<JavacErrorDetail>(); 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; FileInputStream is = null; InputStreamReader isr = null; Reader reader = null; try { is = new FileInputStream(sourceFile); isr = new InputStreamReader(is, ctxt.getOptions().getJavaEncoding()); 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("Compilation error", e); } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) { /*Ignore*/} } if (isr != null) { try { isr.close(); } catch (IOException ioe) { /*Ignore*/} } if (is != null) { try { is.close(); } catch (IOException exc) { /*Ignore*/} } } 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) { String result = ""; String sep = ""; for (int i = 0; i < compoundTypeName.length; i++) { result += sep; result += new String(compoundTypeName[i]); sep = "."; } return findType(result); } @Override public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) { String result = ""; String sep = ""; for (int i = 0; i < packageName.length; i++) { result += sep; result += new String(packageName[i]); sep = "."; } result += sep; result += new String(typeName); return findType(result); } private NameEnvironmentAnswer findType(String className) { InputStream is = null; try { if (className.equals(targetClassName)) { ICompilationUnit compilationUnit = new CompilationUnit(sourceFile, className); return new NameEnvironmentAnswer(compilationUnit, null); } String resourceName = className.replace('.', '/') + ".class"; 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 exc) { log.error("Compilation error", exc); } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) { log.error("Compilation error", exc); } finally { if (is != null) { try { is.close(); } catch (IOException exc) { // Ignore } } } return null; } private boolean isPackage(String result) { if (result.equals(targetClassName)) { return false; } String resourceName = result.replace('.', '/') + ".class"; InputStream is = classLoader.getResourceAsStream(resourceName); return is == null; } @Override public boolean isPackage(char[][] parentPackageName, char[] packageName) { String result = ""; String sep = ""; if (parentPackageName != null) { for (int i = 0; i < parentPackageName.length; i++) { result += sep; String str = new String(parentPackageName[i]); result += str; sep = "."; } } String str = new String(packageName); if (Character.isUpperCase(str.charAt(0))) { if (!isPackage(result)) { return false; } } result += sep; result += str; return isPackage(result); } @Override public void cleanup() { } }; final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems(); final Map<String, String> settings = new HashMap<String, String>(); 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 { log.warn("Unknown source VM " + opt + " ignored."); settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5); } } else { // Default to 1.5 settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5); } // 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 { log.warn("Unknown target VM " + opt + " ignored."); settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5); } } else { // Default to 1.5 settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5); settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5); } 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 (int i = 0; i < problems.length; i++) { IProblem problem = problems[i]; if (problem.isError()) { String name = new String(problems[i].getOriginatingFileName()); try { problemList.add(ErrorDispatcher.createJavacError(name, pageNodes, new StringBuilder(problem.getMessage()), problem.getSourceLineNumber(), ctxt)); } catch (JasperException e) { log.error("Error visiting node", e); } } } } if (problemList.isEmpty()) { ClassFile[] classFiles = result.getClassFiles(); for (int i = 0; i < classFiles.length; i++) { ClassFile classFile = classFiles[i]; char[][] compoundName = classFile.getCompoundName(); String className = ""; String sep = ""; for (int j = 0; j < compoundName.length; j++) { className += sep; className += new String(compoundName[j]); sep = "."; } byte[] bytes = classFile.getBytes(); String outFile = outputDir + "/" + className.replace('.', '/') + ".class"; FileOutputStream fout = new FileOutputStream(outFile); BufferedOutputStream bos = new BufferedOutputStream(fout); bos.write(bytes); bos.close(); } } } catch (IOException exc) { log.error("Compilation error", 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); cOptions.parseLiteralExpressionsAsConstants = true; Compiler compiler = new Compiler(env, policy, cOptions, requestor, problemFactory); compiler.compile(compilationUnits); if (!ctxt.keepGenerated()) { File javaFile = new File(ctxt.getServletJavaFileName()); javaFile.delete(); } 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(smap); } }
From source file:org.apache.jasper.compiler.JDTJavaCompiler.java
License:Open Source License
public JavacErrorDetail[] compile(final String targetClassName, final Node.Nodes pageNodes) throws JasperException { final String sourceFile = ctxt.getServletJavaFileName(); final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath(); String packageName = ctxt.getServletPackageName(); final ClassLoader classLoader = ctxt.getJspLoader(); String[] fileNames = new String[] { sourceFile }; String[] classNames = new String[] { targetClassName }; final ArrayList<JavacErrorDetail> problemList = new ArrayList<JavacErrorDetail>(); class CompilationUnit implements ICompilationUnit { String className;//w ww .ja va2 s . c o m String sourceFile; CompilationUnit(String sourceFile, String className) { this.className = className; this.sourceFile = sourceFile; } public char[] getFileName() { return className.toCharArray(); } public char[] getContents() { char[] result = null; Reader reader = null; try { InputStreamReader isReader = new InputStreamReader(new FileInputStream(sourceFile), ctxt.getOptions().getJavaEncoding()); reader = new BufferedReader(isReader); if (reader != null) { 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.log(Level.SEVERE, "Compilation error", e); } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) { // Ignore } } } return result; } public char[] getMainTypeName() { int dot = className.lastIndexOf('.'); if (dot > 0) { return className.substring(dot + 1).toCharArray(); } return className.toCharArray(); } 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; } } final INameEnvironment env = new INameEnvironment() { public NameEnvironmentAnswer findType(char[][] compoundTypeName) { String result = ""; String sep = ""; for (int i = 0; i < compoundTypeName.length; i++) { result += sep; result += new String(compoundTypeName[i]); sep = "."; } return findType(result); } public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) { String result = ""; String sep = ""; for (int i = 0; i < packageName.length; i++) { result += sep; result += new String(packageName[i]); sep = "."; } result += sep; result += new String(typeName); return findType(result); } private NameEnvironmentAnswer findType(String className) { InputStream is = null; try { if (className.equals(targetClassName)) { ICompilationUnit compilationUnit = new CompilationUnit(sourceFile, className); return new NameEnvironmentAnswer(compilationUnit, null); } String resourceName = className.replace('.', '/') + ".class"; 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 exc) { log.log(Level.SEVERE, "Compilation error", exc); } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) { log.log(Level.SEVERE, "Compilation error", exc); } finally { if (is != null) { try { is.close(); } catch (IOException exc) { // Ignore } } } return null; } private boolean isPackage(String result) { if (result.equals(targetClassName)) { return false; } String resourceName = result.replace('.', '/') + ".class"; InputStream is = classLoader.getResourceAsStream(resourceName); return is == null; } public boolean isPackage(char[][] parentPackageName, char[] packageName) { String result = ""; String sep = ""; if (parentPackageName != null) { for (int i = 0; i < parentPackageName.length; i++) { result += sep; String str = new String(parentPackageName[i]); result += str; sep = "."; } } String str = new String(packageName); if (Character.isUpperCase(str.charAt(0))) { if (!isPackage(result)) { return false; } } result += sep; result += str; return isPackage(result); } public void cleanup() { } }; final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems(); if (ctxt.getOptions().getJavaEncoding() != null) { settings.put(CompilerOptions.OPTION_Encoding, ctxt.getOptions().getJavaEncoding()); } final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault()); final ICompilerRequestor requestor = new ICompilerRequestor() { public void acceptResult(CompilationResult result) { try { if (result.hasProblems()) { IProblem[] problems = safeGetProblems(result); for (int i = 0; i < problems.length; i++) { IProblem problem = problems[i]; if (problem.isError()) { String name = new String(problems[i].getOriginatingFileName()); try { problemList.add(ErrorDispatcher.createJavacError(name, pageNodes, new StringBuilder(problem.getMessage()), problem.getSourceLineNumber())); } catch (JasperException e) { log.log(Level.SEVERE, "Error visiting node", e); } } } } if (problemList.isEmpty()) { ClassFile[] classFiles = result.getClassFiles(); for (int i = 0; i < classFiles.length; i++) { ClassFile classFile = classFiles[i]; char[][] compoundName = classFile.getCompoundName(); String className = ""; String sep = ""; for (int j = 0; j < compoundName.length; j++) { className += sep; className += new String(compoundName[j]); sep = "."; } byte[] bytes = classFile.getBytes(); String outFile = outputDir + "/" + className.replace('.', '/') + ".class"; FileOutputStream fout = new FileOutputStream(outFile); BufferedOutputStream bos = new BufferedOutputStream(fout); bos.write(bytes); bos.close(); } } } catch (IOException exc) { log.log(Level.SEVERE, "Compilation error", exc); } } }; ICompilationUnit[] compilationUnits = new ICompilationUnit[classNames.length]; for (int i = 0; i < compilationUnits.length; i++) { compilationUnits[i] = new CompilationUnit(fileNames[i], classNames[i]); } Compiler compiler = new Compiler(env, policy, settings, requestor, problemFactory); compiler.compile(compilationUnits); if (problemList.isEmpty()) { return null; } return problemList.toArray(new JavacErrorDetail[] {}); }
From source file:org.apache.sling.scripting.jsp.jasper.compiler.JDTCompiler.java
License:Apache License
/** * Compile the servlet from .java file to .class file *///from ww w . ja va 2s . co m protected void generateClass(String[] smap) throws FileNotFoundException, JasperException, Exception { long t1 = 0; if (log.isDebugEnabled()) { t1 = System.currentTimeMillis(); } final String sourceFile = ctxt.getServletJavaFileName(); final String outputDir = ctxt.getOptions().getScratchDir(); String packageName = ctxt.getServletPackageName(); final String targetClassName = ((packageName.length() != 0) ? (packageName + ".") : "") + ctxt.getServletClassName(); String[] fileNames = new String[] { sourceFile }; String[] classNames = new String[] { targetClassName }; final ArrayList problemList = new ArrayList(); class CompilationUnit implements ICompilationUnit { String className; String sourceFile; CompilationUnit(String sourceFile, String className) { this.className = className; this.sourceFile = sourceFile; } public char[] getFileName() { return sourceFile.toCharArray(); } public char[] getContents() { char[] result = null; InputStream is = null; try { is = ctxt.getInputStream(sourceFile); Reader reader = new BufferedReader( new InputStreamReader(is, ctxt.getOptions().getJavaEncoding())); if (reader != null) { char[] chars = new char[8192]; StringBuffer buf = new StringBuffer(); 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("Compilation error", e); } finally { if (is != null) { try { is.close(); } catch (IOException exc) { // Ignore } } } return result; } public char[] getMainTypeName() { int dot = className.lastIndexOf('.'); if (dot > 0) { return className.substring(dot + 1).toCharArray(); } return className.toCharArray(); } 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; } } final INameEnvironment env = new INameEnvironment() { public NameEnvironmentAnswer findType(char[][] compoundTypeName) { String result = ""; String sep = ""; for (int i = 0; i < compoundTypeName.length; i++) { result += sep; result += new String(compoundTypeName[i]); sep = "."; } return findType(result); } public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) { String result = ""; String sep = ""; for (int i = 0; i < packageName.length; i++) { result += sep; result += new String(packageName[i]); sep = "."; } result += sep; result += new String(typeName); return findType(result); } private NameEnvironmentAnswer findType(String className) { InputStream is = null; try { if (className.equals(targetClassName)) { ICompilationUnit compilationUnit = new CompilationUnit(sourceFile, className); return new NameEnvironmentAnswer(compilationUnit, null); } String resourceName = className.replace('.', '/') + ".class"; is = ctxt.getClassLoader().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 exc) { log.error("Compilation error", exc); } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) { log.error("Compilation error", exc); } finally { if (is != null) { try { is.close(); } catch (IOException exc) { // Ignore } } } return null; } private boolean isPackage(String result) { if (result.equals(targetClassName)) { return false; } String resourceName = result.replace('.', '/') + ".class"; InputStream is = ctxt.getClassLoader().getResourceAsStream(resourceName); return is == null; } public boolean isPackage(char[][] parentPackageName, char[] packageName) { String result = ""; String sep = ""; if (parentPackageName != null) { for (int i = 0; i < parentPackageName.length; i++) { result += sep; String str = new String(parentPackageName[i]); result += str; sep = "."; } } String str = new String(packageName); if (Character.isUpperCase(str.charAt(0))) { if (!isPackage(result)) { return false; } } result += sep; result += str; return isPackage(result); } public void cleanup() { } }; final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems(); final Map 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 { log.warn("Unknown source VM " + opt + " ignored."); settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5); } } else { // Default to 1.5 settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5); } // 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 { log.warn("Unknown target VM " + opt + " ignored."); settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5); } } else { // Default to 1.5 settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5); settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5); } final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault()); final ICompilerRequestor requestor = new ICompilerRequestor() { public void acceptResult(CompilationResult result) { try { if (result.hasProblems()) { IProblem[] problems = result.getProblems(); for (int i = 0; i < problems.length; i++) { IProblem problem = problems[i]; if (problem.isError()) { String name = new String(problems[i].getOriginatingFileName()); try { problemList.add(ErrorDispatcher.createJavacError(name, pageNodes, new StringBuffer(problem.getMessage()), problem.getSourceLineNumber(), ctxt)); } catch (JasperException e) { log.error("Error visiting node", e); } } } } if (problemList.isEmpty()) { ClassFile[] classFiles = result.getClassFiles(); for (int i = 0; i < classFiles.length; i++) { ClassFile classFile = classFiles[i]; char[][] compoundName = classFile.getCompoundName(); String className = ""; String sep = ""; for (int j = 0; j < compoundName.length; j++) { className += sep; className += new String(compoundName[j]); sep = "."; } byte[] bytes = classFile.getBytes(); String outFile = outputDir + "/" + className.replace('.', '/') + ".class"; OutputStream out = ctxt.getOutputStream(outFile); BufferedOutputStream bos = new BufferedOutputStream(out); bos.write(bytes); bos.close(); } } } catch (IOException exc) { log.error("Compilation error", 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); } Compiler compiler = new Compiler(env, policy, settings, requestor, problemFactory, true); compiler.compile(compilationUnits); if (!ctxt.keepGenerated()) { ctxt.delete(ctxt.getServletJavaFileName()); } if (!problemList.isEmpty()) { JavacErrorDetail[] jeds = (JavacErrorDetail[]) 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(getCompilationContext(), smap); } }