Example usage for org.eclipse.jdt.internal.compiler CompilationResult getErrors

List of usage examples for org.eclipse.jdt.internal.compiler CompilationResult getErrors

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.compiler CompilationResult getErrors.

Prototype

public CategorizedProblem[] getErrors() 

Source Link

Document

Answer the errors encountered during compilation.

Usage

From source file:com.google.gwt.dev.javac.GWTProblemTest.java

License:Apache License

public void testRecordError() {
    String fileName = "TestCompilationUnit.java";
    String errorMessage = "Unit has errors";
    CompilationResult compilationResult = new CompilationResult(fileName.toCharArray(), 0, 0, 0);
    CompilationUnitDeclaration cud = new CompilationUnitDeclaration(null, compilationResult, 0);

    HelpInfo info = new HelpInfo() {
    };//from ww w. j  a  va 2s .  c om

    // Pick an Expression subtype to pass in
    GWTProblem.recordError(new Wildcard(Wildcard.EXTENDS), cud, errorMessage, info);

    CategorizedProblem[] errors = compilationResult.getErrors();
    assertEquals(1, errors.length);
    GWTProblem problem = (GWTProblem) errors[0];
    assertTrue(problem.isError());
    assertEquals(1, problem.getSourceLineNumber());
    assertEquals(errorMessage, problem.getMessage());
    assertSame(info, problem.getHelpInfo());
}

From source file:com.google.gwt.dev.jjs.JavaToJavaScriptCompiler.java

License:Apache License

/**
 * Look through the list of compiled units for errors and log them to the
 * console.//from  www  .j ava 2  s  . com
 * 
 * @param logger logger to use for compilation errors
 * @param cuds compiled units to analyze for errors.
 * @param itemizeErrors log each error or simply log one message if the build
 *          failed.
 * @throws UnableToCompleteException if a compilation error is found in the
 *           cuds argument.
 */
static void checkForErrors(TreeLogger logger, CompilationUnitDeclaration[] cuds, boolean itemizeErrors)
        throws UnableToCompleteException {
    Event checkForErrorsEvent = SpeedTracerLogger.start(CompilerEventType.CHECK_FOR_ERRORS);
    boolean compilationFailed = false;
    if (cuds.length == 0) {
        compilationFailed = true;
    }
    for (CompilationUnitDeclaration cud : cuds) {
        final CompilationResult result = cud.compilationResult();
        if (result.hasErrors()) {
            compilationFailed = true;
            // Early out if we don't need to itemize.
            if (!itemizeErrors) {
                break;
            }
            String typeName = new String(cud.getMainTypeName());
            CompilationProblemReporter.reportErrors(logger, result.getErrors(), new String(cud.getFileName()),
                    true, new SourceFetcher() {
                        public String getSource() {
                            return new String(result.getCompilationUnit().getContents());
                        }
                    }, typeName, false);
        }
    }
    checkForErrorsEvent.end();
    if (compilationFailed) {
        logger.log(TreeLogger.ERROR, "Cannot proceed due to previous errors", null);
        throw new UnableToCompleteException();
    }
}

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());
    }//from   ww  w. j  a  va  2 s.  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: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)
 *//*from w ww . jav a  2s . com*/
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.bonitasoft.studio.validation.constraints.GroovyCompilationOnScriptExpressionConstraint.java

License:Open Source License

private IStatus evaluateExpression(IValidationContext context, final EObject eObj) {
    final Expression expression = (Expression) eObj;
    String scriptText = expression.getContent();
    IJavaProject javaProject = RepositoryManager.getInstance().getCurrentRepository().getJavaProject();
    final GroovySnippetCompiler compiler = new GroovySnippetCompiler(new GroovyProjectFacade(javaProject));
    final CompilationResult result = compiler.compileForErrors(scriptText, null);
    CategorizedProblem[] problems = result.getErrors();
    if (problems != null && problems.length > 0) {
        StringBuilder sb = new StringBuilder();
        for (CategorizedProblem problem : problems) {
            sb.append(problem.getMessage());
            sb.append(", ");
        }//from  w w  w . j  a va  2  s .c  o  m
        if (sb.length() > 1) {
            sb.delete(sb.length() - 2, sb.length());
            return context.createFailureStatus(new Object[] {
                    Messages.bind(Messages.groovyCompilationProblem, expression.getName(), sb.toString()) });
        }
    }

    return context.createSuccessStatus();
}

From source file:org.codehaus.groovy.eclipse.core.compiler.GroovySnippetParser.java

License:Open Source License

/**
 * Compiles source code into a ModuleNode.  Source code
 * must be a complete file including package declaration
 * and import statements./*from   w w w  . j a v  a  2 s.  c o  m*/
 *
 * @param source the groovy source code to compile
 */
@SuppressWarnings("unchecked")
public ModuleNode parse(String source) {

    Hashtable table = JavaCore.getOptions();
    table.put(CompilerOptions.OPTIONG_BuildGroovyFiles, CompilerOptions.ENABLED);
    CompilerOptions options = new CompilerOptions(table);
    ProblemReporter reporter = new ProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(),
            options, new DefaultProblemFactory());

    GroovyParser parser = new GroovyParser(options, reporter, false, true);
    ICompilationUnit unit = new MockCompilationUnit(source.toCharArray(), "Hello.groovy".toCharArray());
    CompilationResult compilationResult = new CompilationResult(unit, 0, 0, options.maxProblemsPerUnit);

    GroovyCompilationUnitDeclaration decl = (GroovyCompilationUnitDeclaration) parser.dietParse(unit,
            compilationResult);
    ModuleNode node = decl.getModuleNode();

    if (node == null) {
        return null;
    }
    // Remove any remaining synthetic methods
    for (ClassNode classNode : (Iterable<ClassNode>) node.getClasses()) {
        for (Iterator<MethodNode> methodIter = classNode.getMethods().iterator(); methodIter.hasNext();) {
            MethodNode method = methodIter.next();
            if ((method.getModifiers() & Opcodes.ACC_SYNTHETIC) != 0) {
                methodIter.remove();
            }
        }
    }

    problems = compilationResult.getErrors();
    return node;
}

From source file:org.conqat.engine.java.ecj.CollectingCompilerRequestor.java

License:Apache License

/** Returns all errors */
public List<CategorizedProblem> getErrors() {
    ArrayList<CategorizedProblem> errors = new ArrayList<CategorizedProblem>();
    for (CompilationResult result : results.values()) {
        addAllProblems(result.getErrors(), errors);
    }/* w  w w. j a va  2 s  . com*/
    return errors;
}

From source file:org.conqat.engine.java.ecj.CollectingCompilerRequestor.java

License:Apache License

/**
 * Returns the errors for the specified type.
 * //from  w w  w  .  j  av a2 s.c  o  m
 * @return an empty list signals no problems, <code>null</code> signals that
 *         the type wasn't found.
 */
public List<CategorizedProblem> getErrors(String typeName) {
    CompilationResult result = results.get(typeName);
    if (result == null) {
        return null;
    }

    ArrayList<CategorizedProblem> problems = new ArrayList<CategorizedProblem>();
    addAllProblems(result.getErrors(), problems);
    return problems;
}

From source file:org.conqat.engine.java.ecj.ErrorAwareCompilerRequestor.java

License:Apache License

/** {@inheritDoc} */
@Override//from  ww w  .  j  ava 2 s.  c  om
public void acceptResult(CompilationResult result) {
    if (String.valueOf(result.getFileName()).equals(path)) {
        EcjUtils.addAllProblems(result.getErrors(), errors);
    }
}

From source file:org.eclipse.ajdt.core.tests.javaelements.AspectsConvertingParserTest2.java

License:Open Source License

private void assertConvertingParse(String testContentStr) {
    char[] testContent = testContentStr.toCharArray();
    final AspectsConvertingParser convertingParser = new AspectsConvertingParser(testContent);
    convertingParser.content = testContent;
    convertingParser.convert(ConversionOptions.CONSTANT_SIZE);

    ICompilationUnit unit = new ICompilationUnit() {

        public char[] getFileName() {
            return "Test.java".toCharArray();
        }/*from   w  w  w .j a va 2  s  . c  o  m*/

        public char[][] getPackageName() {
            return new char[0][];
        }

        public char[] getMainTypeName() {
            return "Test".toCharArray();
        }

        public char[] getContents() {
            return convertingParser.content;
        }

        public boolean ignoreOptionalProblems() {
            return false;
        }
    };
    CompilerOptions options = new CompilerOptions();
    options.sourceLevel = ClassFileConstants.JDK1_5;
    options.targetJDK = ClassFileConstants.JDK1_5;
    Parser parser = new Parser(new ProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(),
            options, new DefaultProblemFactory()), true);
    CompilationResult result = new CompilationResult(unit, 0, 1, 100);
    CompilationUnitDeclaration decl = parser.parse(unit, result);
    if (result.hasErrors()) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < result.getErrors().length; i++) {
            sb.append("\n\t" + result.getErrors()[i].getMessage());
        }
        sb.append("\n============\nOriginal text:\n" + testContentStr);
        sb.append("\n============\nConverted text:\n" + String.valueOf(convertingParser.content));
        fail("Converted unit has errors:" + sb.toString());
    }
}