List of usage examples for org.eclipse.jdt.internal.compiler ClassFile getCompoundName
public char[][] getCompoundName()
From source file:org.rapidoid.compile.impl.EcjCompilation.java
License:Apache License
public void addResult(CompilationResult result) { for (ClassFile cls : result.getClassFiles()) { classes.put(U.join(".", cls.getCompoundName()), cls.getBytes()); }/*w w w .j av a 2 s . c o m*/ CategorizedProblem[] problems = result.getAllProblems(); if (problems != null) { for (CategorizedProblem problem : problems) { if (problem.isError()) { errors.add(diagnostic(problem)); } else if (problem.isWarning()) { warnings.add(diagnostic(problem)); } else { Log.warn("Unknown problem type!", "problem", problem); } } } }
From source file:org.rythmengine.internal.compiler.TemplateCompiler.java
License:Apache License
/** * Please compile this className//w ww. j av a 2 s .c om */ @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(classNames[i]); } IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.exitOnFirstError(); IProblemFactory problemFactory = new DefaultProblemFactory(Locale.ENGLISH); /** * To find types ... */ 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 findStandType(final String name) throws ClassFormatException { if (notFoundTypes.contains(name)) { return null; } RythmEngine engine = engine(); byte[] bytes = engine.classLoader().getClassDefinition(name); if (bytes != null) { ClassFileReader classFileReader = new ClassFileReader(bytes, name.toCharArray(), true); return new NameEnvironmentAnswer(classFileReader, null); } if (engine.isProdMode()) { notFoundTypes.add(name); } else if (name.matches("^(java\\.|play\\.|com\\.greenlaw110\\.).*")) { notFoundTypes.add(name); } return null; } private NameEnvironmentAnswer findType(final String name) { try { if (!name.contains(TemplateClass.CN_SUFFIX)) { return findStandType(name); } char[] fileName = name.toCharArray(); TemplateClass templateClass = classCache.getByClassName(name); // TemplateClass exists if (templateClass != null) { if (templateClass.javaByteCode != null) { ClassFileReader classFileReader = new ClassFileReader(templateClass.javaByteCode, fileName, true); return new NameEnvironmentAnswer(classFileReader, null); } // Cascade compilation ICompilationUnit compilationUnit = new CompilationUnit(name); return new NameEnvironmentAnswer(compilationUnit, null); } // So it's a standard class return findStandType(name); } catch (ClassFormatException e) { // Something very very bad throw new RuntimeException(e); } } @Override public boolean isPackage(char[][] parentPackageName, char[] packageName) { // Rebuild something usable StringBuilder sb = new StringBuilder(); if (parentPackageName != null) { for (char[] p : parentPackageName) { sb.append(new String(p)); sb.append("."); } } sb.append(new String(packageName)); String name = sb.toString(); if (packagesCache.containsKey(name)) { return packagesCache.get(name).booleanValue(); } // Check if thera a .java or .class for this resource if (engine().classLoader().getClassDefinition(name) != null) { packagesCache.put(name, false); return false; } if (engine().classes().getByClassName(name) != null) { packagesCache.put(name, false); return false; } packagesCache.put(name, true); return true; } public void cleanup() { } }; final RythmEngine engine = engine(); /** * Compilation result */ ICompilerRequestor compilerRequestor = new ICompilerRequestor() { public void acceptResult(CompilationResult result) { // If error if (result.hasErrors()) { for (IProblem problem : result.getErrors()) { int line = problem.getSourceLineNumber(); int column = problem.getSourceStart(); String message = problem.getMessage(); throw CompileException.compilerException( String.valueOf(result.compilationUnit.getMainTypeName()), line, message); } } // Something has been compiled 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]); } if (logger.isTraceEnabled()) { logger.trace("Compiled %s", getTemplateByClassName(clazzName.toString())); } String cn = clazzName.toString(); TemplateClass tc = classCache.getByClassName(cn); if (null == tc) { int pos = cn.indexOf("$"); if (-1 != pos) { // inner class TemplateClass root = classCache.getByClassName(cn.substring(0, pos)); tc = TemplateClass.createInnerClass(cn, clazzFile.getBytes(), root); tc.delayedEnhance(root); classCache.add(tc); } else { throw new RuntimeException("Cannot find class by name: " + cn); } } else { tc.compiled(clazzFile.getBytes()); } } } }; /** * 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); }
From source file:org.tinygroup.jspengine.compiler.JDTJavaCompiler.java
License:GNU General Public 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 . jav a 2 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]; 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 (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.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; } 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 StringBuffer(problem.getMessage()), problem.getSourceLineNumber())); } 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++) { 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.z2env.impl.components.java.jdt.CompilerRequestorImpl.java
License:Apache License
public void acceptResult(CompilationResult result) { if (result.hasProblems()) { IProblem[] problems = result.getProblems(); for (IProblem problem : problems) { if (problem.isWarning()) { if (logger.isLoggable(Level.FINEST)) { logger.warning(String.format("Compile Warning %s", problemToText(problem))); }//from w w w .j av a 2 s. co m } else if (problem.isError()) { this.hasError = true; logger.severe(String.format("\n\nCompile Error %s\n", problemToText(problem))); } } } if (!this.hasError) { ClassFile[] classFiles = result.getClassFiles(); for (ClassFile classFile : classFiles) { String classFileName = NameEnvironmentImpl.concat(classFile.getCompoundName()) + ".class"; if (logger.isLoggable(Level.FINEST)) { logger.finest("Writing class file " + classFileName + " into " + this.outFolder); } byte[] bytes = classFile.getBytes(); File outFile = new File(this.outFolder, classFileName); if (!outFile.getParentFile().exists()) { outFile.getParentFile().mkdirs(); } FileOutputStream fout = null; try { try { fout = new FileOutputStream(outFile); fout.write(bytes); } finally { fout.close(); } } catch (Exception e) { throw new RuntimeException("Failed to write .class file: " + classFileName, e); } } } }