Java 类javax.tools.DiagnosticCollector 实例源码

项目:monarch    文件:ClassBuilder.java   
/**
 * Compile the provided class. The className may have a package separated by /. For example:
 * my/package/myclass
 * 
 * @param className Name of the class to compile.
 * @param classCode Plain text contents of the class
 * @return The byte contents of the compiled class.
 * @throws IOException
 */
public byte[] compileClass(final String className, final String classCode) throws IOException {
  ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

  JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
  OutputStreamJavaFileManager<JavaFileManager> fileManager =
      new OutputStreamJavaFileManager<JavaFileManager>(
          javaCompiler.getStandardFileManager(null, null, null), byteArrayOutputStream);

  List<JavaFileObject> fileObjects = new ArrayList<JavaFileObject>();
  fileObjects.add(new JavaSourceFromString(className, classCode));

  List<String> options = Arrays.asList("-classpath", this.classPath);
  DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
  if (!javaCompiler.getTask(null, fileManager, diagnostics, options, null, fileObjects).call()) {
    StringBuilder errorMsg = new StringBuilder();
    for (Diagnostic d : diagnostics.getDiagnostics()) {
      String err = String.format("Compilation error: Line %d - %s%n", d.getLineNumber(),
          d.getMessage(null));
      errorMsg.append(err);
      System.err.print(err);
    }
    throw new IOException(errorMsg.toString());
  }
  return byteArrayOutputStream.toByteArray();
}
项目:otter-G    文件:JdkCompileTask.java   
public synchronized Class compile(final String className, final CharSequence javaSource,
                                  final DiagnosticCollector<JavaFileObject> diagnosticsList)
                                                                                            throws JdkCompileException,
                                                                                            ClassCastException {
    if (diagnosticsList != null) {
        diagnostics = diagnosticsList;
    } else {
        diagnostics = new DiagnosticCollector<JavaFileObject>();
    }

    Map<String, CharSequence> classes = new HashMap<String, CharSequence>(1);
    classes.put(className, javaSource);

    Map<String, Class> compiled = compile(classes, diagnosticsList);
    Class newClass = compiled.get(className);
    return newClass;
}
项目:OpenJSharp    文件:SchemaGenerator.java   
public static boolean compile(String[] args, File episode) throws Exception {

            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
            StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
            JavacOptions options = JavacOptions.parse(compiler, fileManager, args);
            List<String> unrecognizedOptions = options.getUnrecognizedOptions();
            if (!unrecognizedOptions.isEmpty())
                Logger.getLogger(SchemaGenerator.class.getName()).log(Level.WARNING, "Unrecognized options found: {0}", unrecognizedOptions);
            Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(options.getFiles());
            JavaCompiler.CompilationTask task = compiler.getTask(
                    null,
                    fileManager,
                    diagnostics,
                    options.getRecognizedOptions(),
                    options.getClassNames(),
                    compilationUnits);
            com.sun.tools.internal.jxc.ap.SchemaGenerator r = new com.sun.tools.internal.jxc.ap.SchemaGenerator();
            if (episode != null)
                r.setEpisodeFile(episode);
            task.setProcessors(Collections.singleton(r));
            return task.call();
        }
项目:Hydrograph    文件:ExpressionEditorUtil.java   
/**
 * This method validates the given expression and updates the expression-editor's datasturcture accordingly
 * 
 * @param expressionText
 * @param inputFields
 * @param expressionEditorData
 */
public static void validateExpression(String expressionText,Map<String, Class<?>> inputFields,ExpressionEditorData expressionEditorData ) {
    if(BuildExpressionEditorDataSturcture.INSTANCE.getCurrentProject()!=null){
    DiagnosticCollector<JavaFileObject> diagnosticCollector = null;
    try {
        inputFields.putAll(expressionEditorData.getExtraFieldDatatypeMap());
        diagnosticCollector = ValidateExpressionToolButton
                .compileExpresion(expressionText,inputFields,expressionEditorData.getComponentName());
        if (diagnosticCollector != null && !diagnosticCollector.getDiagnostics().isEmpty()) {
            for (Diagnostic<?> diagnostic : diagnosticCollector.getDiagnostics()) {
                if (StringUtils.equals(diagnostic.getKind().name(), Diagnostic.Kind.ERROR.name())) {
                    expressionEditorData.setValid(false);
                    return;
                }
            }
        }
    } catch (JavaModelException | InvocationTargetException | ClassNotFoundException | MalformedURLException
            | IllegalAccessException | IllegalArgumentException e) {
        expressionEditorData.setValid(false);
        return;
    }
    expressionEditorData.setValid(true);
    }
}
项目:openjdk-jdk10    文件:JavapTaskCtorFailWithNPE.java   
private void run() {
    File classToCheck = new File(System.getProperty("test.classes"),
        getClass().getSimpleName() + ".class");

    DiagnosticCollector<JavaFileObject> dc =
            new DiagnosticCollector<JavaFileObject>();
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    JavaFileManager fm = JavapFileManager.create(dc, pw);
    JavapTask t = new JavapTask(pw, fm, dc, null,
            Arrays.asList(classToCheck.getPath()));
    if (t.run() != 0)
        throw new Error("javap failed unexpectedly");

    List<Diagnostic<? extends JavaFileObject>> diags = dc.getDiagnostics();
    for (Diagnostic<? extends JavaFileObject> d: diags) {
        if (d.getKind() == Diagnostic.Kind.ERROR)
            throw new AssertionError(d.getMessage(Locale.ENGLISH));
    }
    String lineSep = System.getProperty("line.separator");
    String out = sw.toString().replace(lineSep, "\n");
    if (!out.equals(expOutput)) {
        throw new AssertionError("The output is not equal to the one expected");
    }
}
项目:openjdk-jdk10    文件:T7190862.java   
private String javap(List<String> args, List<String> classes) {
    DiagnosticCollector<JavaFileObject> dc = new DiagnosticCollector<JavaFileObject>();
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    JavaFileManager fm = JavapFileManager.create(dc, pw);
    JavapTask t = new JavapTask(pw, fm, dc, args, classes);
    if (t.run() != 0)
        throw new Error("javap failed unexpectedly");

    List<Diagnostic<? extends JavaFileObject>> diags = dc.getDiagnostics();
    for (Diagnostic<? extends JavaFileObject> d: diags) {
        if (d.getKind() == Diagnostic.Kind.ERROR)
            throw new Error(d.getMessage(Locale.ENGLISH));
    }
    return sw.toString();

}
项目:openjdk-jdk10    文件:JavacExtensionTest.java   
static List<? extends Tree> parse(String srcfile) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> fileObjects = fileManager.getJavaFileObjects(srcfile);
    String classPath = System.getProperty("java.class.path");
    List<String> options = Arrays.asList("-classpath", classPath);
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    Context context = new Context();
    JavacTaskImpl task = (JavacTaskImpl) ((JavacTool) compiler).getTask(null, null,
            diagnostics, options, null, fileObjects, context);
    TrialParserFactory.instance(context);
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    Iterator<? extends CompilationUnitTree> it = asts.iterator();
    if (it.hasNext()) {
        CompilationUnitTree cut = it.next();
        return cut.getTypeDecls();
    } else {
        throw new AssertionError("Expected compilation unit");
    }
}
项目:openjdk-jdk10    文件:JavacParserTest.java   
@Test
void testVariableInIfThen1() throws IOException {

    String code = "package t; class Test { " +
            "private static void t(String name) { " +
            "if (name != null) String nn = name.trim(); } }";

    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen1",
            Arrays.<String>asList("compiler.err.variable.not.allowed"),
            codes);
}
项目:openjdk-jdk10    文件:JavacParserTest.java   
@Test
void testVariableInIfThen2() throws IOException {

     String code = "package t; class Test { " +
             "private static void t(String name) { " +
             "if (name != null) class X {} } }";
     DiagnosticCollector<JavaFileObject> coll =
             new DiagnosticCollector<JavaFileObject>();
     JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
             null, Arrays.asList(new MyFileObject(code)));

     ct.parse();

     List<String> codes = new LinkedList<String>();

     for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
         codes.add(d.getCode());
     }

     assertEquals("testVariableInIfThen2",
             Arrays.<String>asList("compiler.err.class.not.allowed"), codes);
 }
项目:openjdk-jdk10    文件:JavacParserTest.java   
@Test
void testVariableInIfThen3() throws IOException {

    String code = "package t; class Test { "+
            "private static void t() { " +
            "if (true) abstract class F {} }}";
    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();
    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen3",
            Arrays.<String>asList("compiler.err.class.not.allowed"), codes);
}
项目:openjdk-jdk10    文件:JavacParserTest.java   
@Test
void testVariableInIfThen4() throws IOException {

    String code = "package t; class Test { "+
            "private static void t(String name) { " +
            "if (name != null) interface X {} } }";
    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();
    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen4",
            Arrays.<String>asList("compiler.err.class.not.allowed"), codes);
}
项目:openjdk-jdk10    文件:JavacParserTest.java   
@Test
void testVariableInIfThen5() throws IOException {

    String code = "package t; class Test { "+
            "private static void t() { " +
            "if (true) } }";
    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();
    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen5",
            Arrays.<String>asList("compiler.err.illegal.start.of.stmt"),
            codes);
}
项目:openjdk-jdk10    文件:TestCompileJARInClassPath.java   
void compileWithJSR199() throws IOException {
    String cpath = "C2.jar";
    File clientJarFile = new File(cpath);
    File sourceFileToCompile = new File("C3.java");


    javax.tools.JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    try (StandardJavaFileManager stdFileManager = javac.getStandardFileManager(diagnostics, null, null)) {

        List<File> files = new ArrayList<>();
        files.add(clientJarFile);

        stdFileManager.setLocation(StandardLocation.CLASS_PATH, files);

        Iterable<? extends JavaFileObject> sourceFiles = stdFileManager.getJavaFileObjects(sourceFileToCompile);

        if (!javac.getTask(null, stdFileManager, diagnostics, null, null, sourceFiles).call()) {
            throw new AssertionError("compilation failed");
        }
    }
}
项目:openjdk-jdk10    文件:TestBase.java   
private <S> InMemoryFileManager compile(
        List<String> options,
        Function<S, ? extends JavaFileObject> src2JavaFileObject,
        List<S> sources)
        throws IOException, CompilationException {

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    List<? extends JavaFileObject> src = sources.stream()
            .map(src2JavaFileObject)
            .collect(Collectors.toList());

    DiagnosticCollector<? super JavaFileObject> dc = new DiagnosticCollector<>();
    try (InMemoryFileManager fileManager
                 = new InMemoryFileManager(compiler.getStandardFileManager(null, null, null))) {
        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, dc, options, null, src);
        boolean success = task.call();
        if (!success) {
            String errorMessage = dc.getDiagnostics().stream()
                    .map(Object::toString)
                    .collect(Collectors.joining("\n"));
            throw new CompilationException("Compilation Error\n\n" + errorMessage);
        }
        return fileManager;
    }
}
项目:openjdk-jdk10    文件:RetentionAnnoCombo.java   
private boolean getCompileResult(String contents, String className,
        boolean shouldCompile) throws Exception{

    DiagnosticCollector<JavaFileObject> diagnostics =
            new DiagnosticCollector<JavaFileObject>();
    boolean ok = compileCode(className, contents, diagnostics);

    String expectedErrKey = "compiler.err.invalid.repeatable" +
                                    ".annotation.retention";
    if (!shouldCompile && !ok) {
        for (Diagnostic<?> d : diagnostics.getDiagnostics()) {
            if (!((d.getKind() == Diagnostic.Kind.ERROR) &&
                d.getCode().contains(expectedErrKey))) {
                error("FAIL: Incorrect error given, expected = "
                        + expectedErrKey + ", Actual = " + d.getCode()
                        + " for className = " + className, contents);
            }
        }
    }

    return (shouldCompile  == ok);
}
项目:openjdk-jdk10    文件:DocumentedAnnoCombo.java   
public void runTest() throws Exception {
    boolean ok = false;
    int testCtr = 0;

    // Create test source content
    for (TestCases className : TestCases.values()) {
        testCtr++;
        String contents = getContent(className.toString());

        // Compile the generated source file
        DiagnosticCollector<JavaFileObject> diagnostics =
                new DiagnosticCollector<JavaFileObject>();
        ok = compileCode(className.toString(), contents, diagnostics);
        if (!ok) {
            error("Class="+ className +" did not compile as expected", contents);
        } else {
            System.out.println("Test passed for className: " + className);
        }
    }

    System.out.println("Total number of tests run: " + testCtr);
    System.out.println("Total number of errors: " + errors);

    if (errors > 0)
        throw new Exception(errors + " errors found");
}
项目:java-debug    文件:CompileUtils.java   
public static void compileFiles(File projectRoot, List<String> javaFiles) {
    DiagnosticCollector diagnosticCollector = new DiagnosticCollector();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticCollector, Locale.ENGLISH, Charset.forName("utf-8"));
    Iterable<? extends JavaFileObject> javaFileObjects = fileManager.getJavaFileObjects(javaFiles.toArray(new String[0]));
    File outputFolder = new File(projectRoot, "bin");
    if (!outputFolder.exists()) {
        outputFolder.mkdir();
    }
    String[] options = new String[] { "-d", outputFolder.getAbsolutePath() , "-g", "-proc:none"};
    final StringWriter output = new StringWriter();
    CompilationTask task = compiler.getTask(output, fileManager, diagnosticCollector, Arrays.asList(options), null, javaFileObjects);
    boolean result = task.call();
    if (!result) {
        throw new IllegalArgumentException(
            "Compilation failed:\n" + output);
    }
    List list = diagnosticCollector.getDiagnostics();
    for (Object object : list) {
        Diagnostic d = (Diagnostic) object;
        System.out.println(d.getMessage(Locale.ENGLISH));
    }
}
项目:manifold-ij    文件:ManifoldPsiClass.java   
public void initialize( PsiClass delegate, List<IFile> files, String fqn, DiagnosticCollector issues )
{
  _ifiles = files;
  _fqn = fqn;
  _issues = issues;
  PsiManager manager = PsiManagerImpl.getInstance( delegate.getProject() );
  _files = new ArrayList<>( _ifiles.size() );
  for( IFile ifile : _ifiles )
  {
    VirtualFile vfile = ((IjFile)ifile).getVirtualFile();
    if( vfile != null )
    {
      PsiFile file = manager.findFile( vfile );
      _files.add( file );

      Module module = ModuleUtilCore.findModuleForFile( vfile, delegate.getProject() );
      if( module != null )
      {
        file.putUserData( ModuleUtil.KEY_MODULE, module );
      }
    }
  }
  delegate.getContainingFile().putUserData( KEY_MANIFOLD_PSI_CLASS, this );
}
项目:manifold    文件:CompilationTest.java   
@SafeVarargs
private final void compileFile( JavacTool javacTool, JavaFileManager fileManager, String file, Pair<IssueMsg, Integer>... msgs ) throws IOException, URISyntaxException
{
  DiagnosticCollector<JavaFileObject> dc = new DiagnosticCollector<>();
  String content = StreamUtil.getContent( StreamUtil.getInputStreamReader( getClass().getResourceAsStream( file ) ) );
  SourceFile srcFile = new SourceFile( file, content );
  StringWriter errors = new StringWriter();
  JavacTaskImpl javacTask = (JavacTaskImpl)javacTool.getTask( errors, fileManager, dc, Collections.singletonList( "-Xplugin:Manifold" ), null, Collections.singletonList( srcFile ) );
  javacTask.call();
  outer:
  for( Pair<IssueMsg, Integer> msg : msgs )
  {
    for( Diagnostic<? extends JavaFileObject> d : dc.getDiagnostics() )
    {
      if( d.getLineNumber() == msg.getSecond() )
      {
        if( msg.getFirst().isMessageSimilar( d.getMessage( Locale.getDefault() ) ) )
        {
          continue outer;
        }
      }
    }
    fail( "Did not find issue: " + msg.getFirst().get() + " at line: " + msg.getSecond() );
  }
}
项目:manifold    文件:JavaParser.java   
/**
 * Compiles specified Java class name.  Maintains cache between calls to this method, therefore subsequent calls to this
 * method will consult the cache and return the previously compiled class if cached.
 */
public InMemoryClassJavaFileObject compile( String fqn, Iterable<String> options, DiagnosticCollector<JavaFileObject> errorHandler )
{
  init();

  InMemoryClassJavaFileObject compiledClass = _gfm.findCompiledFile( fqn );
  if( compiledClass != null )
  {
    return compiledClass;
  }

  Pair<JavaFileObject, String> fileObj = findJavaSource( fqn, errorHandler );
  if( fileObj == null )
  {
    return null;
  }

  StringWriter errors = new StringWriter();
  JavacTaskImpl javacTask = (JavacTaskImpl)_javac.getTask( errors, _gfm, errorHandler, options, null, Collections.singletonList( fileObj.getFirst() ) );
  initTypeProcessing( javacTask, Collections.singleton( fqn ) );
  javacTask.call();
  return _gfm.findCompiledFile( fileObj.getSecond() );
}
项目:openjdk9    文件:JavapTaskCtorFailWithNPE.java   
private void run() {
    File classToCheck = new File(System.getProperty("test.classes"),
        getClass().getSimpleName() + ".class");

    DiagnosticCollector<JavaFileObject> dc =
            new DiagnosticCollector<JavaFileObject>();
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    JavaFileManager fm = JavapFileManager.create(dc, pw);
    JavapTask t = new JavapTask(pw, fm, dc, null,
            Arrays.asList(classToCheck.getPath()));
    if (t.run() != 0)
        throw new Error("javap failed unexpectedly");

    List<Diagnostic<? extends JavaFileObject>> diags = dc.getDiagnostics();
    for (Diagnostic<? extends JavaFileObject> d: diags) {
        if (d.getKind() == Diagnostic.Kind.ERROR)
            throw new AssertionError(d.getMessage(Locale.ENGLISH));
    }
    String lineSep = System.getProperty("line.separator");
    String out = sw.toString().replace(lineSep, "\n");
    if (!out.equals(expOutput)) {
        throw new AssertionError("The output is not equal to the one expected");
    }
}
项目:openjdk9    文件:T7190862.java   
private String javap(List<String> args, List<String> classes) {
    DiagnosticCollector<JavaFileObject> dc = new DiagnosticCollector<JavaFileObject>();
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    JavaFileManager fm = JavapFileManager.create(dc, pw);
    JavapTask t = new JavapTask(pw, fm, dc, args, classes);
    if (t.run() != 0)
        throw new Error("javap failed unexpectedly");

    List<Diagnostic<? extends JavaFileObject>> diags = dc.getDiagnostics();
    for (Diagnostic<? extends JavaFileObject> d: diags) {
        if (d.getKind() == Diagnostic.Kind.ERROR)
            throw new Error(d.getMessage(Locale.ENGLISH));
    }
    return sw.toString();

}
项目:openjdk9    文件:JavacExtensionTest.java   
static List<? extends Tree> parse(String srcfile) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> fileObjects = fileManager.getJavaFileObjects(srcfile);
    String classPath = System.getProperty("java.class.path");
    List<String> options = Arrays.asList("-classpath", classPath);
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    Context context = new Context();
    JavacTaskImpl task = (JavacTaskImpl) ((JavacTool) compiler).getTask(null, null,
            diagnostics, options, null, fileObjects, context);
    TrialParserFactory.instance(context);
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    Iterator<? extends CompilationUnitTree> it = asts.iterator();
    if (it.hasNext()) {
        CompilationUnitTree cut = it.next();
        return cut.getTypeDecls();
    } else {
        throw new AssertionError("Expected compilation unit");
    }
}
项目:openjdk9    文件:JavacParserTest.java   
@Test
void testVariableInIfThen3() throws IOException {

    String code = "package t; class Test { "+
            "private static void t() { " +
            "if (true) abstract class F {} }}";
    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();
    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen3",
            Arrays.<String>asList("compiler.err.class.not.allowed"), codes);
}
项目:openjdk9    文件:JavacParserTest.java   
@Test
void testVariableInIfThen4() throws IOException {

    String code = "package t; class Test { "+
            "private static void t(String name) { " +
            "if (name != null) interface X {} } }";
    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();
    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen4",
            Arrays.<String>asList("compiler.err.class.not.allowed"), codes);
}
项目:openjdk9    文件:JavacParserTest.java   
@Test
void testVariableInIfThen5() throws IOException {

    String code = "package t; class Test { "+
            "private static void t() { " +
            "if (true) } }";
    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();
    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen5",
            Arrays.<String>asList("compiler.err.illegal.start.of.stmt"),
            codes);
}
项目:openjdk9    文件:TestCompileJARInClassPath.java   
void compileWithJSR199() throws IOException {
    String cpath = "C2.jar";
    File clientJarFile = new File(cpath);
    File sourceFileToCompile = new File("C3.java");


    javax.tools.JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    try (StandardJavaFileManager stdFileManager = javac.getStandardFileManager(diagnostics, null, null)) {

        List<File> files = new ArrayList<>();
        files.add(clientJarFile);

        stdFileManager.setLocation(StandardLocation.CLASS_PATH, files);

        Iterable<? extends JavaFileObject> sourceFiles = stdFileManager.getJavaFileObjects(sourceFileToCompile);

        if (!javac.getTask(null, stdFileManager, diagnostics, null, null, sourceFiles).call()) {
            throw new AssertionError("compilation failed");
        }
    }
}
项目:openjdk9    文件:TestBase.java   
private <S> InMemoryFileManager compile(
        List<String> options,
        Function<S, ? extends JavaFileObject> src2JavaFileObject,
        List<S> sources)
        throws IOException, CompilationException {

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    List<? extends JavaFileObject> src = sources.stream()
            .map(src2JavaFileObject)
            .collect(Collectors.toList());

    DiagnosticCollector<? super JavaFileObject> dc = new DiagnosticCollector<>();
    try (InMemoryFileManager fileManager
                 = new InMemoryFileManager(compiler.getStandardFileManager(null, null, null))) {
        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, dc, options, null, src);
        boolean success = task.call();
        if (!success) {
            String errorMessage = dc.getDiagnostics().stream()
                    .map(Object::toString)
                    .collect(Collectors.joining("\n"));
            throw new CompilationException("Compilation Error\n\n" + errorMessage);
        }
        return fileManager;
    }
}
项目:openjdk9    文件:ProfileOptionTest.java   
@Test
void testClassesInProfiles() throws Exception {
    for (Profile p: Profile.values()) {
        for (Map.Entry<Profile, List<JavaFileObject>> e: testClasses.entrySet()) {
            for (JavaFileObject fo: e.getValue()) {
                DiagnosticCollector<JavaFileObject> dl =
                        new DiagnosticCollector<JavaFileObject>();
                List<String> opts = (p == Profile.DEFAULT)
                        ? Collections.<String>emptyList()
                        : Arrays.asList("-profile", p.name);
                JavacTask task = (JavacTask) javac.getTask(null, fm, dl, opts, null,
                        Arrays.asList(fo));
                task.analyze();

                List<String> expectDiagCodes = (p.value >= e.getKey().value)
                        ? Collections.<String>emptyList()
                        : Arrays.asList("compiler.err.not.in.profile");

                checkDiags(opts + " " + fo.getName(), dl.getDiagnostics(), expectDiagCodes);
            }
        }
    }
}
项目:openjdk9    文件:RetentionAnnoCombo.java   
private boolean getCompileResult(String contents, String className,
        boolean shouldCompile) throws Exception{

    DiagnosticCollector<JavaFileObject> diagnostics =
            new DiagnosticCollector<JavaFileObject>();
    boolean ok = compileCode(className, contents, diagnostics);

    String expectedErrKey = "compiler.err.invalid.repeatable" +
                                    ".annotation.retention";
    if (!shouldCompile && !ok) {
        for (Diagnostic<?> d : diagnostics.getDiagnostics()) {
            if (!((d.getKind() == Diagnostic.Kind.ERROR) &&
                d.getCode().contains(expectedErrKey))) {
                error("FAIL: Incorrect error given, expected = "
                        + expectedErrKey + ", Actual = " + d.getCode()
                        + " for className = " + className, contents);
            }
        }
    }

    return (shouldCompile  == ok);
}
项目:openjdk9    文件:DocumentedAnnoCombo.java   
public void runTest() throws Exception {
    boolean ok = false;
    int testCtr = 0;

    // Create test source content
    for (TestCases className : TestCases.values()) {
        testCtr++;
        String contents = getContent(className.toString());

        // Compile the generated source file
        DiagnosticCollector<JavaFileObject> diagnostics =
                new DiagnosticCollector<JavaFileObject>();
        ok = compileCode(className.toString(), contents, diagnostics);
        if (!ok) {
            error("Class="+ className +" did not compile as expected", contents);
        } else {
            System.out.println("Test passed for className: " + className);
        }
    }

    System.out.println("Total number of tests run: " + testCtr);
    System.out.println("Total number of errors: " + errors);

    if (errors > 0)
        throw new Exception(errors + " errors found");
}
项目:vscode-javac    文件:RecompileTest.java   
@Test
public void fixParseError() {
    URI bad = FindResource.uri("/org/javacs/example/FixParseErrorBefore.java");
    URI good = FindResource.uri("/org/javacs/example/FixParseErrorAfter.java");
    JavacHolder compiler = newCompiler();
    DiagnosticCollector<JavaFileObject> badErrors =
            compiler.compileBatch(Collections.singletonMap(bad, Optional.empty()));

    assertThat(badErrors.getDiagnostics(), not(empty()));

    // Parse again
    DiagnosticCollector<JavaFileObject> goodErrors =
            compiler.compileBatch(Collections.singletonMap(good, Optional.empty()));

    assertThat(goodErrors.getDiagnostics(), empty());
}
项目:vscode-javac    文件:RecompileTest.java   
@Test
public void fixTypeError() {
    URI bad = FindResource.uri("/org/javacs/example/FixTypeErrorBefore.java");
    URI good = FindResource.uri("/org/javacs/example/FixTypeErrorAfter.java");
    JavacHolder compiler = newCompiler();
    DiagnosticCollector<JavaFileObject> badErrors =
            compiler.compileBatch(Collections.singletonMap(bad, Optional.empty()));

    assertThat(badErrors.getDiagnostics(), not(empty()));

    // Parse again
    DiagnosticCollector<JavaFileObject> goodErrors =
            compiler.compileBatch(Collections.singletonMap(good, Optional.empty()));

    assertThat(goodErrors.getDiagnostics(), empty());
}
项目:vscode-javac    文件:LinterTest.java   
@Test
public void parseError() {
    URI file = URI.create("/org/javacs/example/ArrowTry.java");
    String source =
            "package org.javacs.example;\n"
                    + "\n"
                    + "class Example {\n"
                    + "    private static <In, Out> Function<In, Stream<Out>> catchClasspathErrors(Function<In, Stream<Out>> f) {\n"
                    + "        return in -> try {\n"
                    + "            return f.apply(in);\n"
                    + "        } catch (Symbol.CompletionFailure failed) {\n"
                    + "            LOG.warning(failed.getMessage());\n"
                    + "            return Stream.empty();\n"
                    + "        };\n"
                    + "    }\n"
                    + "}";
    DiagnosticCollector<JavaFileObject> compile =
            compiler.compileBatch(Collections.singletonMap(file, Optional.of(source)));

    assertThat(compile.getDiagnostics(), not(empty()));
}
项目:yugong    文件:JdkCompiler.java   
public synchronized Class compile(String packageName, String className, final CharSequence javaSource)
                                                                                                      throws JdkCompileException,
                                                                                                      ClassCastException {
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    JavaFileManagerImpl javaFileManager = buildFileManager(classLoader, classLoader.getParent(), diagnostics);

    JavaFileObjectImpl source = new JavaFileObjectImpl(className, javaSource);
    javaFileManager.putFileForInput(StandardLocation.SOURCE_PATH, packageName, className + EXTENSION, source);

    CompilationTask task = compiler.getTask(null,
        javaFileManager,
        diagnostics,
        options,
        null,
        Arrays.asList(source));
    final Boolean result = task.call();
    if (result == null || !result.booleanValue()) {
        throw new JdkCompileException("Compilation failed.", diagnostics);
    }

    try {
        return (Class<T>) classLoader.loadClass(packageName + "." + className);
    } catch (Throwable e) {
        throw new JdkCompileException(e, diagnostics);
    }
}
项目:yugong    文件:JdkCompiler.java   
private JavaFileManagerImpl buildFileManager(JdkCompilerClassLoader classLoader, ClassLoader loader,
                                             DiagnosticCollector<JavaFileObject> diagnostics) {
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
    if (loader instanceof URLClassLoader
        && (!"sun.misc.Launcher$AppClassLoader".equalsIgnoreCase(loader.getClass().getName()))) {
        try {
            URLClassLoader urlClassLoader = (URLClassLoader) loader;
            List<File> paths = new ArrayList<File>();
            for (URL url : urlClassLoader.getURLs()) {
                File file = new File(url.getFile());
                paths.add(file);
            }

            fileManager.setLocation(StandardLocation.CLASS_PATH, paths);
        } catch (Throwable e) {
            throw new YuGongException(e);
        }
    }

    return new JavaFileManagerImpl(fileManager, classLoader);
}
项目:toothpick    文件:ClassCreator.java   
private Map<String, byte[]> compile(Map<String, String> mapClassNameToJavaSource) {
  DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  InMemoryJavaFileManager fileManager = new InMemoryJavaFileManager(compiler.getStandardFileManager(diagnostics, null, null));

  List<JavaFileObject> compilationUnit = new ArrayList<>();
  for (Map.Entry<String, String> classNameToSourceEntry : mapClassNameToJavaSource.entrySet()) {
    JavaFileObject source = new JavaSourceFromString(classNameToSourceEntry.getKey(), classNameToSourceEntry.getValue());
    compilationUnit.add(source);
  }

  JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnit);
  if (!task.call()) {
    for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
      System.out.format("Error on line %d in %s%n", diagnostic.getLineNumber(), diagnostic.getSource());
    }
    return null;
  }
  return fileManager.getAllBuffers();
}
项目:wava    文件:TestTypesEclipse.java   
static private boolean compile(Iterable<? extends Processor> processors)
{
    JavaCompiler compiler = new EclipseCompiler();
    DiagnosticCollector<JavaFileObject> diagnosticCollector =
            new DiagnosticCollector<JavaFileObject>();
    JavaFileManager fileManager = compiler.getStandardFileManager(diagnosticCollector, Locale.getDefault(), UTF_8);
    JavaCompiler.CompilationTask task = compiler.getTask(
            null,
            fileManager,
            diagnosticCollector,
            ImmutableSet.<String>of(),
            ImmutableSet.of(TestTypesEclipse.class.getCanonicalName()),
            ImmutableSet.<JavaFileObject>of());
    task.setProcessors(processors);
    return task.call();
}
项目:listing    文件:Compilation.java   
/** Convenient JavaCompiler facade returning a ClassLoader with all compiled units. */
static ClassLoader compile(
    ClassLoader parent,
    List<String> options,
    List<Processor> processors,
    List<JavaFileObject> units) {
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  Objects.requireNonNull(compiler, "no system java compiler available - JDK is required!");
  DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
  StandardJavaFileManager sjfm =
      compiler.getStandardFileManager(diagnostics, Locale.getDefault(), StandardCharsets.UTF_8);
  Manager manager = new Manager(sjfm, parent);
  CompilationTask task = compiler.getTask(null, manager, diagnostics, options, null, units);
  if (!processors.isEmpty()) {
    task.setProcessors(processors);
  }
  boolean success = task.call();
  if (!success) {
    throw new RuntimeException("compilation failed! " + diagnostics.getDiagnostics());
  }
  return manager.getClassLoader(StandardLocation.CLASS_PATH);
}
项目:Rapture    文件:RapturePluginClassLoaderIntegrationTest.java   
private Boolean compileJavaFiles(HashSet<File> javaFiles) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();

    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
    // Setting the location results in creating the directory structure of the package, instead
    // of putting the .class files directly in the tmpFolder.
    fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(tmpFolder.getRoot()));

    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(javaFiles);

    JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits);
    boolean success = task.call();
    fileManager.close();

    return success;
}