List of usage examples for org.eclipse.jdt.internal.compiler CompilationResult getClassFiles
public ClassFile[] getClassFiles()
From source file:fr.inria.astor.core.manipulation.compiler.bytecode.JDTByteCodeCompiler.java
License:Open Source License
/** * /*from w w w . ja v a2 s. c o m*/ */ @Override public void acceptResult(CompilationResult result) { if (result.hasErrors()) { String problems = ""; for (CategorizedProblem cp : result.getAllProblems()) { problems += new String(result.getFileName()) + "-l:(" + cp.getSourceLineNumber() + "):" + cp.toString() + ", "; } classErrors.add(problems); } for (ClassFile f : result.getClassFiles()) { classFiles.add(f); } }
From source file:io.gige.compiler.internal.CompilerRequestorImpl.java
License:Apache License
@Override public void acceptResult(CompilationResult result) { if (result.hasProblems()) { report(Kind.ERROR, result.getErrors()); }// w w w . j a va 2s .c o m if (result.hasTasks()) { report(Kind.NOTE, result.getTasks()); } try { for (ClassFile cf : result.getClassFiles()) { String className = new String(cf.fileName()); JavaFileObject obj = this.manager.getJavaFileForOutput(StandardLocation.CLASS_OUTPUT, className, javax.tools.JavaFileObject.Kind.CLASS, null); try (OutputStream out = obj.openOutputStream()) { out.write(cf.getBytes()); } } } catch (IOException e) { throw new UncheckedIOException(e); } }
From source file:io.takari.maven.plugins.compile.jdt.CompilerJdt.java
License:Open Source License
@Override public void acceptResult(CompilationResult result) { if (result == null) { return; // ah? }/*from w w w . ja v a 2 s . c om*/ final String sourceName = new String(result.getFileName()); final File sourceFile = new File(sourceName); Resource<File> input = context.getProcessedSource(sourceFile); // track type references if (result.rootReferences != null && result.qualifiedReferences != null && result.simpleNameReferences != null) { context.setAttribute(input.getResource(), ATTR_REFERENCES, new ReferenceCollection( result.rootReferences, result.qualifiedReferences, result.simpleNameReferences)); } if (result.hasProblems() && (!isLenientProcOnly() || isShowWarnings())) { for (CategorizedProblem problem : result.getProblems()) { MessageSeverity severity = isLenientProcOnly() ? MessageSeverity.WARNING : problem.isError() ? MessageSeverity.ERROR : MessageSeverity.WARNING; input.addMessage(problem.getSourceLineNumber(), ((DefaultProblem) problem).column, problem.getMessage(), severity, null /* cause */); } } try { if (!result.hasErrors() && !isProcOnly()) { for (ClassFile classFile : result.getClassFiles()) { char[] filename = classFile.fileName(); int length = filename.length; char[] relativeName = new char[length + 6]; System.arraycopy(filename, 0, relativeName, 0, length); System.arraycopy(SuffixConstants.SUFFIX_class, 0, relativeName, length, 6); CharOperation.replace(relativeName, '/', File.separatorChar); String relativeStringName = new String(relativeName); writeClassFile(input, relativeStringName, classFile); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // XXX double check affected sources are recompiled when this source has errors }
From source file:ma.glasnost.orika.impl.generator.eclipsejdt.CompilerRequestor.java
License:Apache License
public void acceptResult(CompilationResult result) { boolean hasErrors = false; if (result.hasProblems()) { problems = result.getProblems(); }//w w w. ja v a2 s.co m if (!hasErrors) { ClassFile[] classFiles = result.getClassFiles(); for (int i = 0; i < classFiles.length; i++) { ClassFile classFile = classFiles[i]; char[][] compoundName = classFile.getCompoundName(); StringBuilder className = new StringBuilder(); String sep = ""; for (int j = 0; j < compoundName.length; j++) { className.append(sep); className.append(new String(compoundName[j])); sep = "."; } byte[] bytes = classFile.getBytes(); compiledClassFiles.put(className.toString(), bytes); } } }
From source file:net.sf.j2s.core.builder.AbstractImageBuilder.java
License:Open Source License
public void acceptResult(CompilationResult result) { // In Batch mode, we write out the class files, hold onto the dependency info // & additional types and report problems. // In Incremental mode, when writing out a class file we need to compare it // against the previous file, remembering if structural changes occured. // Before reporting the new problems, we need to update the problem count & // remove the old problems. Plus delete additional class files that no longer exist. SourceFile compilationUnit = (SourceFile) result.getCompilationUnit(); // go directly back to the sourceFile if (!this.workQueue.isCompiled(compilationUnit)) { this.workQueue.finished(compilationUnit); try {/*w w w .j a va 2 s. c om*/ updateProblemsFor(compilationUnit, result); // record compilation problems before potentially adding duplicate errors updateTasksFor(compilationUnit, result); // record tasks } catch (CoreException e) { throw internalException(e); } if (result.hasInconsistentToplevelHierarchies) // ensure that this file is always retrieved from source for the rest of the build if (!this.problemSourceFiles.contains(compilationUnit)) this.problemSourceFiles.add(compilationUnit); IType mainType = null; String mainTypeName = null; String typeLocator = compilationUnit.typeLocator(); ClassFile[] classFiles = result.getClassFiles(); int length = classFiles.length; ArrayList duplicateTypeNames = null; ArrayList definedTypeNames = new ArrayList(length); for (int i = 0; i < length; i++) { ClassFile classFile = classFiles[i]; char[][] compoundName = classFile.getCompoundName(); char[] typeName = compoundName[compoundName.length - 1]; boolean isNestedType = classFile.isNestedType; // Look for a possible collision, if one exists, report an error but do not write the class file if (isNestedType) { String qualifiedTypeName = new String(classFile.outerMostEnclosingClassFile().fileName()); if (this.newState.isDuplicateLocator(qualifiedTypeName, typeLocator)) continue; } else { String qualifiedTypeName = new String(classFile.fileName()); // the qualified type name "p1/p2/A" if (this.newState.isDuplicateLocator(qualifiedTypeName, typeLocator)) { if (duplicateTypeNames == null) duplicateTypeNames = new ArrayList(); duplicateTypeNames.add(compoundName); if (mainType == null) { try { mainTypeName = compilationUnit.initialTypeName; // slash separated qualified name "p1/p1/A" mainType = this.javaBuilder.javaProject.findType(mainTypeName.replace('/', '.')); } catch (JavaModelException e) { // ignore } } IType type; if (qualifiedTypeName.equals(mainTypeName)) { type = mainType; } else { String simpleName = qualifiedTypeName.substring(qualifiedTypeName.lastIndexOf('/') + 1); type = mainType == null ? null : mainType.getCompilationUnit().getType(simpleName); } createProblemFor(compilationUnit.resource, type, Messages.bind(Messages.build_duplicateClassFile, new String(typeName)), JavaCore.ERROR); continue; } this.newState.recordLocatorForType(qualifiedTypeName, typeLocator); if (result.checkSecondaryTypes && !qualifiedTypeName.equals(compilationUnit.initialTypeName)) acceptSecondaryType(classFile); } try { definedTypeNames.add(writeClassFile(classFile, compilationUnit, !isNestedType)); } catch (CoreException e) { Util.log(e, "JavaBuilder handling CoreException"); //$NON-NLS-1$ if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) createProblemFor(compilationUnit.resource, null, Messages.bind(Messages.build_classFileCollision, e.getMessage()), JavaCore.ERROR); else createProblemFor(compilationUnit.resource, null, Messages.build_inconsistentClassFile, JavaCore.ERROR); } } if (result.hasAnnotations && this.filesWithAnnotations != null) // only initialized if an annotation processor is attached this.filesWithAnnotations.add(compilationUnit); this.compiler.lookupEnvironment.releaseClassFiles(classFiles); finishedWith(typeLocator, result, compilationUnit.getMainTypeName(), definedTypeNames, duplicateTypeNames); this.notifier.compiled(compilationUnit); } }
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 ww. java 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.ant4eclipse.lib.jdt.ecj.internal.tools.CompilerRequestorImpl.java
License:Open Source License
/** * {@inheritDoc}//w w w .j a v a 2 s . co m */ public void acceptResult(CompilationResult result) { // get the compilation unit... CompilationUnitImpl compilationUnitImpl = (CompilationUnitImpl) result.getCompilationUnit(); // ...and the source file SourceFile sourceFile = compilationUnitImpl.getSourceFile(); // return immediately if the source file is a ReferableSourceFile if (sourceFile instanceof ReferableSourceFile) { // add the problems... if (result.getAllProblems() != null) { if (A4ELogging.isTraceingEnabled()) { A4ELogging.trace("Could not compile referenced class '%s'. Reason: %s", sourceFile.getSourceFileName(), Arrays.asList(result.getAllProblems())); } } return; } // get the destination directory File destinationDirectory = sourceFile.getDestinationFolder(); if (!result.hasErrors()) { ClassFile[] classFiles = result.getClassFiles(); for (ClassFile classFile2 : classFiles) { char[][] compoundName = classFile2.getCompoundName(); StringBuffer classFileName = new StringBuffer(); for (int j = 0; j < compoundName.length; j++) { classFileName.append(compoundName[j]); if (j < compoundName.length - 1) { classFileName.append('/'); } } classFileName.append(".class"); File classFile = new File(destinationDirectory, classFileName.toString()); File classDir = classFile.getParentFile(); if (!classDir.exists()) { classDir.mkdirs(); } try { A4ELogging.debug("writing class file: '%s'", classFile); Utilities.writeFile(classFile, classFile2.getBytes()); this._compiledClassFiles.put(classFileName.toString(), classFile); } catch (Ant4EclipseException ioe) { A4ELogging.error("Could not write classfile '%s': %s", classFileName.toString(), ioe.toString()); ioe.printStackTrace(); this._compilationSuccessful = false; } } } else { this._compilationSuccessful = false; } // add the problems... if (result.getAllProblems() != null) { this._categorizedProblems.addAll(Arrays.asList(result.getAllProblems())); } }
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 {/*from w w w .j ava 2s . 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.sling.scripting.java.jdt.CompilationUnit.java
License:Apache License
/** * @see org.eclipse.jdt.internal.compiler.ICompilerRequestor#acceptResult(org.eclipse.jdt.internal.compiler.CompilationResult) *//* w ww . j a v a 2s .c om*/ 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]; handleError(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(); final StringBuffer b = new StringBuffer(this.options.getDestinationPath()); b.append('/'); b.append(className.toString().replace('.', '/')); b.append(".class"); OutputStream fout = ioProvider.getOutputStream(b.toString()); BufferedOutputStream bos = new BufferedOutputStream(fout); bos.write(bytes); bos.close(); } } } catch (IOException exc) { exc.printStackTrace(); } }
From source file:org.apache.tuscany.maven.compiler.CompilerRequestor.java
License:Apache License
public void acceptResult(CompilationResult result) { boolean hasErrors = false; if (result.hasProblems()) { // Convert JDT IProblems into plexus CompilerErrors for (IProblem problem : result.getProblems()) { if (problem.isWarning()) { if (showWarnings) { compilerErrors.add(new CompilerError(new String(problem.getOriginatingFileName()), false, problem.getSourceLineNumber(), problem.getSourceStart(), problem.getSourceLineNumber(), problem.getSourceEnd(), problem.getMessage())); }//from www . j av a2 s. c om } else if (problem.isError()) { hasErrors = true; compilerErrors.add(new CompilerError(new String(problem.getOriginatingFileName()), true, problem.getSourceLineNumber(), problem.getSourceStart(), problem.getSourceLineNumber(), problem.getSourceEnd(), problem.getMessage())); } } } // Write the class files if (!hasErrors) { ClassFile[] classFiles = result.getClassFiles(); for (ClassFile classFile : classFiles) { // Create file and parent directories StringBuffer className = new StringBuffer(); for (char[] name : classFile.getCompoundName()) { if (className.length() != 0) { className.append('.'); } className.append(name); } File file = new File(outputDirectory, className.toString().replace('.', '/') + ".class"); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } // Write class file contents FileOutputStream fos = null; try { fos = new FileOutputStream(file); fos.write(classFile.getBytes()); } catch (FileNotFoundException e) { throw new IllegalArgumentException(e); } catch (IOException e) { throw new IllegalArgumentException(e); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { } } } } } }