Java Code Examples for javax.tools.DiagnosticListener

The following examples show how to use javax.tools.DiagnosticListener. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: TencentKona-8   Source File: JavapTask.java    License: GNU General Public License v2.0 6 votes vote down vote up
public JavapTask(Writer out,
        JavaFileManager fileManager,
        DiagnosticListener<? super JavaFileObject> diagnosticListener,
        Iterable<String> options,
        Iterable<String> classes) {
    this(out, fileManager, diagnosticListener);

    this.classes = new ArrayList<String>();
    for (String classname: classes) {
        classname.getClass(); // null-check
        this.classes.add(classname);
    }

    try {
        if (options != null)
            handleOptions(options, false);
    } catch (BadArgs e) {
        throw new IllegalArgumentException(e.getMessage());
    }
}
 
Example 2
Source Project: manifold   Source File: HighjumpTypeManifold.java    License: Apache License 2.0 6 votes vote down vote up
private String makeSymbolClass( String fqn, DiagnosticListener<JavaFileObject> errorHandler )
{
  Symbol symbol = _fqnToSymbol.get( fqn );

  SrcClass srcClass = new SrcClass( fqn, AbstractSrcClass.Kind.Class );
  srcClass.modifiers( Modifier.PUBLIC | Modifier.FINAL );
  SrcField field = new SrcField( symbol.getName(), symbol.getType() )
    .modifiers( Modifier.PUBLIC | Modifier.STATIC );
  if( symbol.getInitialValue() != null )
  {
    //todo: add call to "Highjump.getInitialValue(\"" + symbol.getUid() + '$' + symbol.getName() + "\")" which will
    // get the initialValue from the _fqnToSymbol map.
  }
  srcClass.addField( field );

  return null;
}
 
Example 3
Source Project: buck   Source File: BuckJavacTaskProxy.java    License: Apache License 2.0 6 votes vote down vote up
static BuckJavacTaskProxy getTask(
    PluginClassLoaderFactory loaderFactory,
    JavaCompiler compiler,
    Writer out,
    JavaFileManager fileManager,
    DiagnosticListener<? super JavaFileObject> diagnosticListener,
    Iterable<String> options,
    Iterable<String> classes,
    Iterable<? extends JavaFileObject> compilationUnits) {
  JavaCompiler.CompilationTask task =
      compiler.getTask(out, fileManager, diagnosticListener, options, classes, compilationUnits);

  PluginClassLoader loader = loaderFactory.getPluginClassLoader(task);
  Class<? extends BuckJavacTaskProxy> proxyImplClass =
      loader.loadClass(
          "com.facebook.buck.jvm.java.plugin.adapter.BuckJavacTaskProxyImpl",
          BuckJavacTaskProxy.class);

  try {
    return proxyImplClass.getConstructor(JavaCompiler.CompilationTask.class).newInstance(task);
  } catch (ReflectiveOperationException e) {
    throw new RuntimeException(e);
  }
}
 
Example 4
Source Project: openjdk-jdk9   Source File: JavahTask.java    License: GNU General Public License v2.0 6 votes vote down vote up
JavahTask(Writer out,
        JavaFileManager fileManager,
        DiagnosticListener<? super JavaFileObject> diagnosticListener,
        Iterable<String> options,
        Iterable<String> classes) {
    this();
    this.log = getPrintWriterForWriter(out);
    this.fileManager = fileManager;
    this.diagnosticListener = diagnosticListener;

    try {
        handleOptions(options, false);
    } catch (BadArgs e) {
        throw new IllegalArgumentException(e.getMessage());
    }

    this.classes = new ArrayList<>();
    if (classes != null) {
        for (String classname: classes) {
            Objects.requireNonNull(classname);
            this.classes.add(classname);
        }
    }
}
 
Example 5
Source Project: manifold   Source File: JavascriptCodeGen.java    License: Apache License 2.0 6 votes vote down vote up
private void reportErrors( DiagnosticListener<JavaFileObject> errorHandler, ProgramNode programNode )
{
  if( programNode.errorCount() > 0 )
  {
    JavaFileObject file;
    try
    {
      file = new SourceJavaFileObject( _file.toURI() );
    }
    catch( Exception e )
    {
      file = null;
    }

    for( ParseError error : programNode.getErrorList() )
    {
      Token token = error.getToken();
      errorHandler.report( new JavacDiagnostic( file, Diagnostic.Kind.ERROR, token.getOffset(), token.getLineNumber(), token.getCol(), error.getMessage() ) );
    }
  }
}
 
Example 6
Source Project: netbeans   Source File: JavacParser.java    License: Apache License 2.0 6 votes vote down vote up
public static JavacTaskImpl createJavacTask (
        @NonNull final ClasspathInfo cpInfo,
        @NullAllowed final DiagnosticListener<? super JavaFileObject> diagnosticListener,
        @NullAllowed final String sourceLevel,
        @NullAllowed final SourceLevelQuery.Profile sourceProfile,
        @NullAllowed FQN2Files fqn2Files,
        @NullAllowed final CancelService cancelService,
        @NullAllowed final APTUtils aptUtils,
        @NullAllowed final CompilerOptionsQuery.Result compilerOptions,
        @NonNull Iterable<? extends JavaFileObject> files) {
    return createJavacTask(
            cpInfo,
            diagnosticListener,
            sourceLevel,
            sourceProfile,
            EnumSet.of(ConfigFlags.BACKGROUND_COMPILATION, ConfigFlags.MULTI_SOURCE),
            fqn2Files,
            cancelService,
            aptUtils,
            compilerOptions,
            Collections.emptySet(),
            files);
}
 
Example 7
Source Project: netbeans   Source File: CompilationInfoImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new CompilationInfoImpl for given source file
 * @param parser used to parse the file
 * @param file to be parsed
 * @param root the owner of the parsed file
 * @param javacTask used javac or null if new one should be created
 * @param snapshot rendered content of the file
 * @param detached true if the CompilationInfoImpl is detached from parsing infrastructure.
 * @throws java.io.IOException
 */
CompilationInfoImpl (final JavacParser parser,
                     final FileObject file,
                     final FileObject root,
                     final JavacTaskImpl javacTask,
                     final DiagnosticListener<JavaFileObject> diagnosticListener,
                     final Snapshot snapshot,
                     final boolean detached) throws IOException {
    assert parser != null;
    this.parser = parser;
    this.cpInfo = parser.getClasspathInfo();
    assert cpInfo != null;
    this.file = file;
    this.root = root;
    this.snapshot = snapshot;
    assert file == null || snapshot != null;
    this.jfo = file != null ?
        FileObjects.sourceFileObject(file, root, JavaFileFilterQuery.getFilter(file), snapshot.getText()) :
        null;
    this.javacTask = javacTask;
    this.diagnosticListener = diagnosticListener;
    this.isClassFile = false;
    this.isDetached = detached;
}
 
Example 8
JavahTask(Writer out,
        JavaFileManager fileManager,
        DiagnosticListener<? super JavaFileObject> diagnosticListener,
        Iterable<String> options,
        Iterable<String> classes) {
    this();
    this.log = getPrintWriterForWriter(out);
    this.fileManager = fileManager;
    this.diagnosticListener = diagnosticListener;

    try {
        handleOptions(options, false);
    } catch (BadArgs e) {
        throw new IllegalArgumentException(e.getMessage());
    }

    this.classes = new ArrayList<String>();
    if (classes != null) {
        for (String classname: classes) {
            classname.getClass(); // null-check
            this.classes.add(classname);
        }
    }
}
 
Example 9
Source Project: jdk8u60   Source File: JavahTask.java    License: GNU General Public License v2.0 6 votes vote down vote up
JavahTask(Writer out,
        JavaFileManager fileManager,
        DiagnosticListener<? super JavaFileObject> diagnosticListener,
        Iterable<String> options,
        Iterable<String> classes) {
    this();
    this.log = getPrintWriterForWriter(out);
    this.fileManager = fileManager;
    this.diagnosticListener = diagnosticListener;

    try {
        handleOptions(options, false);
    } catch (BadArgs e) {
        throw new IllegalArgumentException(e.getMessage());
    }

    this.classes = new ArrayList<String>();
    if (classes != null) {
        for (String classname: classes) {
            classname.getClass(); // null-check
            this.classes.add(classname);
        }
    }
}
 
Example 10
Source Project: cxf   Source File: Compiler.java    License: Apache License 2.0 6 votes vote down vote up
protected DiagnosticListener<JavaFileObject> setupDiagnosticListener() {
    return new DiagnosticListener<JavaFileObject>() {
        public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
            switch (diagnostic.getKind()) {
            case ERROR:
                errors.add(diagnostic.toString());
                if (verbose) {
                    System.err.println(diagnostic.toString());
                }
                break;
            case WARNING:
            case MANDATORY_WARNING:
                warnings.add(diagnostic.toString());
                if (verbose) {
                    System.err.println(diagnostic.toString());
                }
                break;
            default:
                break;
            }
        }
    };
}
 
Example 11
Source Project: doma   Source File: AptinaTestCase.java    License: Apache License 2.0 6 votes vote down vote up
public void compile() throws IOException {
  javaCompiler = ToolProvider.getSystemJavaCompiler();
  diagnostics = new DiagnosticCollector<JavaFileObject>();
  final DiagnosticListener<JavaFileObject> listener = new LoggingDiagnosticListener(diagnostics);

  standardJavaFileManager = javaCompiler.getStandardFileManager(listener, locale, charset);
  standardJavaFileManager.setLocation(StandardLocation.SOURCE_PATH, sourcePaths);
  testingJavaFileManager = new TestingJavaFileManager(standardJavaFileManager, charset);

  final CompilationTask task =
      javaCompiler.getTask(
          out, testingJavaFileManager, listener, options, null, getCompilationUnits());
  task.setProcessors(processors);
  compiledResult = task.call();
  compilationUnits.clear();
}
 
Example 12
Source Project: openjdk-8-source   Source File: JavahTask.java    License: GNU General Public License v2.0 6 votes vote down vote up
JavahTask(Writer out,
        JavaFileManager fileManager,
        DiagnosticListener<? super JavaFileObject> diagnosticListener,
        Iterable<String> options,
        Iterable<String> classes) {
    this();
    this.log = getPrintWriterForWriter(out);
    this.fileManager = fileManager;
    this.diagnosticListener = diagnosticListener;

    try {
        handleOptions(options, false);
    } catch (BadArgs e) {
        throw new IllegalArgumentException(e.getMessage());
    }

    this.classes = new ArrayList<String>();
    if (classes != null) {
        for (String classname: classes) {
            classname.getClass(); // null-check
            this.classes.add(classname);
        }
    }
}
 
Example 13
Source Project: java-n-IDE-for-Android   Source File: CompileHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static int compileJava(Context context, JavaProjectFolder projectFile, @Nullable DiagnosticListener listener) {
    try {

        String[] args = new String[]{
                "-verbose",
                "-cp", projectFile.getJavaClassPath(context),
                "-sourcepath", projectFile.getSourcePath(), //sourcepath
                "-d", projectFile.getDirBuildClasses().getPath(), //output dir
                projectFile.getMainClass().getPath(projectFile) //main class
        };
        DLog.d(TAG, "compileJava args = " + Arrays.toString(args));
        int compileStatus;
        compileStatus = Javac.compile(args, listener);
        return compileStatus;
    } catch (Throwable e) {
        e.printStackTrace();
    }
    return Main.EXIT_ERROR;
}
 
Example 14
Source Project: openjdk-jdk8u   Source File: JavapTask.java    License: GNU General Public License v2.0 6 votes vote down vote up
public JavapTask(Writer out,
        JavaFileManager fileManager,
        DiagnosticListener<? super JavaFileObject> diagnosticListener,
        Iterable<String> options,
        Iterable<String> classes) {
    this(out, fileManager, diagnosticListener);

    this.classes = new ArrayList<String>();
    for (String classname: classes) {
        classname.getClass(); // null-check
        this.classes.add(classname);
    }

    try {
        if (options != null)
            handleOptions(options, false);
    } catch (BadArgs e) {
        throw new IllegalArgumentException(e.getMessage());
    }
}
 
Example 15
Source Project: hottub   Source File: JavapTask.java    License: GNU General Public License v2.0 6 votes vote down vote up
private DiagnosticListener<JavaFileObject> getDiagnosticListenerForWriter(Writer w) {
    final PrintWriter pw = getPrintWriterForWriter(w);
    return new DiagnosticListener<JavaFileObject> () {
        public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
            switch (diagnostic.getKind()) {
                case ERROR:
                    pw.print(getMessage("err.prefix"));
                    break;
                case WARNING:
                    pw.print(getMessage("warn.prefix"));
                    break;
                case NOTE:
                    pw.print(getMessage("note.prefix"));
                    break;
            }
            pw.print(" ");
            pw.println(diagnostic.getMessage(null));
        }
    };
}
 
Example 16
Source Project: netbeans   Source File: JavacParser.java    License: Apache License 2.0 5 votes vote down vote up
private static CompilationInfoImpl createCurrentInfo (final JavacParser parser,
        final FileObject file,
        final FileObject root,
        final Snapshot snapshot,
        final JavacTaskImpl javac,
        final DiagnosticListener<JavaFileObject> diagnosticListener) throws IOException {
    CompilationInfoImpl info = new CompilationInfoImpl(parser, file, root, javac, diagnosticListener, snapshot, false);
    if (file != null) {
        Logger.getLogger("TIMER").log(Level.FINE, "CompilationInfo",    //NOI18N
                new Object[] {file, info});
    }
    return info;
}
 
Example 17
Source Project: manifold   Source File: JavaParser.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Pair<JavaFileObject, String> findJavaSource( String fqn, DiagnosticListener<JavaFileObject> errorHandler )
{
  init();

  if( _mfm == null )
  {
    // short-circuit reentrancy during init()
    return null;
  }

  JavaFileObject fileObj = _mfm.getSourceFileForInput( StandardLocation.SOURCE_PATH, fqn, JavaFileObject.Kind.SOURCE, errorHandler );
  if( fileObj == null )
  {
    int iDot = fqn.lastIndexOf( '.' );
    if( iDot > 0 )
    {
      String enclosingFqn = fqn.substring( 0, iDot );
      return findJavaSource( enclosingFqn, errorHandler );
    }
    return null;
  }
  else
  {
    return new Pair<>( fileObj, fqn );
  }
}
 
Example 18
public static JavapFileManager create(final DiagnosticListener<? super JavaFileObject> dl, PrintWriter log) {
    Context javac_context = new Context();

    if (dl != null)
        javac_context.put(DiagnosticListener.class, dl);
    javac_context.put(com.sun.tools.javac.util.Log.outKey, log);

    return new JavapFileManager(javac_context, null);
}
 
Example 19
Source Project: manifold   Source File: PropertiesTypeManifold.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected String contribute( JavaFileManager.Location location, String topLevelFqn, boolean genStubs, String existing, Model model, DiagnosticListener<JavaFileObject> errorHandler )
{
  List<IFile> files = findFilesForType( topLevelFqn );
  SrcClass srcClass = new PropertiesCodeGen( model.getCache(), files.isEmpty() ? null : files.get( 0 ), topLevelFqn ).make( getModule(), location, errorHandler );
  StringBuilder sb = srcClass.render( new StringBuilder(), 0 );
  return sb.toString();
}
 
Example 20
void clear() {
    drop(Arguments.argsKey);
    drop(DiagnosticListener.class);
    drop(Log.outKey);
    drop(Log.errKey);
    drop(JavaFileManager.class);
    drop(JavacTask.class);
    drop(JavacTrees.class);
    drop(JavacElements.class);

    if (ht.get(Log.logKey) instanceof ReusableLog) {
        //log already inited - not first round
        ((ReusableLog)Log.instance(this)).clear();
        Enter.instance(this).newRound();
        ((ReusableJavaCompiler)ReusableJavaCompiler.instance(this)).clear();
        Types.instance(this).newRound();
        Check.instance(this).newRound();
        Modules.instance(this).newRound();
        Annotate.instance(this).newRound();
        CompileStates.instance(this).clear();
        MultiTaskListener.instance(this).clear();

        //find if any of the roots have redefined java.* classes
        Symtab syms = Symtab.instance(this);
        pollutionScanner.scan(roots, syms);
        roots.clear();
    }
}
 
Example 21
Source Project: openjdk-jdk8u   Source File: JavahTool.java    License: GNU General Public License v2.0 5 votes vote down vote up
public NativeHeaderTask getTask(Writer out,
        JavaFileManager fileManager,
        DiagnosticListener<? super JavaFileObject> diagnosticListener,
        Iterable<String> options,
        Iterable<String> classes) {
    return new JavahTask(out, fileManager, diagnosticListener, options, classes);
}
 
Example 22
Source Project: manifold   Source File: Model.java    License: Apache License 2.0 5 votes vote down vote up
void report( DiagnosticListener<JavaFileObject> errorHandler )
{
  if( _issues == null || errorHandler == null )
  {
    return;
  }

  JavaFileObject file = new SourceJavaFileObject( getFile().toURI() );
  for( IIssue issue : _issues.getIssues() )
  {
    Diagnostic.Kind kind = issue.getKind() == IIssue.Kind.Error ? Diagnostic.Kind.ERROR : Diagnostic.Kind.WARNING;
    errorHandler.report( new JavacDiagnostic( file, kind, issue.getStartOffset(), issue.getLine(), issue.getColumn(), issue.getMessage() ) );
  }
}
 
Example 23
Source Project: buck   Source File: Jsr199JavacIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public StandardJavaFileManager getStandardFileManager(
    DiagnosticListener<? super JavaFileObject> diagnosticListener,
    Locale locale,
    Charset charset) {
  throw new OutOfMemoryError("abcdef");
}
 
Example 24
Source Project: hottub   Source File: JavadocTool.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public DocumentationTask getTask(
        Writer out,
        JavaFileManager fileManager,
        DiagnosticListener<? super JavaFileObject> diagnosticListener,
        Class<?> docletClass,
        Iterable<String> options,
        Iterable<? extends JavaFileObject> compilationUnits) {
    Context context = new Context();
    return getTask(out, fileManager, diagnosticListener,
            docletClass, options, compilationUnits, context);
}
 
Example 25
public static JavapFileManager create(final DiagnosticListener<? super JavaFileObject> dl, PrintWriter log) {
    Context javac_context = new Context();

    if (dl != null)
        javac_context.put(DiagnosticListener.class, dl);
    javac_context.put(com.sun.tools.javac.util.Log.outKey, log);

    return new JavapFileManager(javac_context, null);
}
 
Example 26
Source Project: hottub   Source File: JavacParserTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
void performWildcardPositionsTest(final String code,
        List<String> golden) throws IOException {

    final List<Diagnostic<? extends JavaFileObject>> errors =
            new LinkedList<Diagnostic<? extends JavaFileObject>>();

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null,
            new DiagnosticListener<JavaFileObject>() {
                public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
                    errors.add(diagnostic);
                }
            }, null, null, Arrays.asList(new MyFileObject(code)));

    final CompilationUnitTree cut = ct.parse().iterator().next();
    final List<String> content = new LinkedList<String>();
    final Trees trees = Trees.instance(ct);

    new TreeScanner<Void, Void>() {
        @Override
        public Void scan(Tree node, Void p) {
            if (node == null) {
                return null;
            }
            long start = trees.getSourcePositions().getStartPosition(cut, node);

            if (start == (-1)) {
                return null; // synthetic tree
            }
            long end = trees.getSourcePositions().getEndPosition(cut, node);
            String s = code.substring((int) start, (int) end);
            content.add(s);

            return super.scan(node, p);
        }
    }.scan(((MethodTree) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0)).getBody().getStatements().get(0), null);

    assertEquals("performWildcardPositionsTest",golden.toString(),
            content.toString());
}
 
Example 27
Source Project: manifold   Source File: GqlParentType.java    License: Apache License 2.0 5 votes vote down vote up
void render( StringBuilder sb, JavaFileManager.Location location, IModule module, DiagnosticListener<JavaFileObject> errorHandler )
{
  SrcLinkedClass srcClass = new SrcLinkedClass( getFqn(), Class, _file, location, module, errorHandler )
    .addAnnotation( new SrcAnnotationExpression( DisableStringLiteralTemplates.class.getSimpleName() ) )
    .addAnnotation( new SrcAnnotationExpression( FragmentValue.class.getSimpleName() )
      .addArgument( "methodName", String.class, "fragmentValue" )
      .addArgument( "type", String.class, getFqn() ) )
    .modifiers( Modifier.PUBLIC );
  addImports( srcClass );
  addInnerTypes( srcClass );
  addInnerOperations( srcClass );
  addFragmentValueMethod( srcClass );
  srcClass.render( sb, 0 );
}
 
Example 28
Source Project: openjdk-8   Source File: JavahTool.java    License: GNU General Public License v2.0 5 votes vote down vote up
public NativeHeaderTask getTask(Writer out,
        JavaFileManager fileManager,
        DiagnosticListener<? super JavaFileObject> diagnosticListener,
        Iterable<String> options,
        Iterable<String> classes) {
    return new JavahTask(out, fileManager, diagnosticListener, options, classes);
}
 
Example 29
Source Project: openjdk-jdk8u   Source File: ResolveHarness.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected void check() throws Exception {
    String[] options = {
        "-XDshouldStopPolicy=ATTR",
        "-XDverboseResolution=success,failure,applicable,inapplicable,deferred-inference,predef"
    };

    AbstractProcessor[] processors = { new ResolveCandidateFinder(), null };

    @SuppressWarnings("unchecked")
    DiagnosticListener<? super JavaFileObject>[] diagListeners =
            new DiagnosticListener[] { new DiagnosticHandler(false), new DiagnosticHandler(true) };

    for (int i = 0 ; i < options.length ; i ++) {
        JavacTask ct = (JavacTask)comp.getTask(null, fm, diagListeners[i],
                Arrays.asList(options[i]), null, Arrays.asList(jfo));
        if (processors[i] != null) {
            ct.setProcessors(Collections.singleton(processors[i]));
        }
        ct.analyze();
    }

    //check diags
    for (Diagnostic<? extends JavaFileObject> diag : diags) {
        for (DiagnosticProcessor proc : diagProcessors) {
            if (proc.matches(diag)) {
                proc.process(diag);
                break;
            }
        }
    }
    //check all candidates have been used up
    for (Map.Entry<ElementKey, Candidate> entry : candidatesMap.entrySet()) {
        if (!seenCandidates.contains(entry.getKey())) {
            error("Redundant @Candidate annotation on method " + entry.getKey().elem + " sig = " + entry.getKey().elem.asType());
        }
    }
}
 
Example 30
Source Project: jdk8u60   Source File: JavahFileManager.java    License: GNU General Public License v2.0 5 votes vote down vote up
static JavahFileManager create(final DiagnosticListener<? super JavaFileObject> dl, PrintWriter log) {
    Context javac_context = new Context();

    if (dl != null)
        javac_context.put(DiagnosticListener.class, dl);
    javac_context.put(com.sun.tools.javac.util.Log.outKey, log);

    return new JavahFileManager(javac_context, null);
}