Java 类org.eclipse.emf.ecore.resource.Resource.Diagnostic 实例源码

项目:n4js    文件:NegativeAnalyser.java   
@Override
public void analyse(Script script, String codeName, String code) {
    List<Diagnostic> errors = super.getScriptErrors(script);
    if (errors.isEmpty()) {
        String msg = "expected errors in " + codeName + " but there was not a single one";
        if (this.logger.isDebugEnabled()) {
            StringBuilder sb = new StringBuilder(msg).append("\n");
            sb.append("========== " + codeName + " ==========\n");
            if (this.logCode) {
                sb.append(code).append("\n");
            }
            sb.append("========================================").append("\n");
            this.logger.debug(sb);
        }
        assertEquals(msg, code, codeName);
    }
}
项目:n4js    文件:ExceptionAnalyser.java   
@Override
protected List<Diagnostic> getScriptErrors(Script script) {
    EcoreUtil.resolveAll(script.eResource());
    List<Diagnostic> diagnostics = super.getScriptErrors(script);
    Iterator<Expression> expressions = Iterators.filter(EcoreUtil2.eAll(script), Expression.class);
    List<Diagnostic> result = Lists.<Diagnostic> newArrayList(Iterables.filter(diagnostics,
            ExceptionDiagnostic.class));
    while (expressions.hasNext()) {
        Expression expression = expressions.next();
        RuleEnvironment ruleEnvironment = RuleEnvironmentExtensions.newRuleEnvironment(expression);
        Result<TypeRef> type = typeSystem.type(ruleEnvironment, expression);
        if (type.getRuleFailedException() != null) {
            Throwable cause = Throwables.getRootCause(type.getRuleFailedException());
            if (!(cause instanceof RuleFailedException)) {
                if (cause instanceof Exception) {
                    result.add(new ExceptionDiagnostic((Exception) cause));
                } else {
                    throw new RuntimeException(cause);
                }
            }
        }
    }
    validator.validate(script.eResource(), CheckMode.ALL, CancelIndicator.NullImpl);
    return result;
}
项目:n4js    文件:BuiltInTypeScopeTest.java   
@SuppressWarnings("javadoc")
@Test
public void testLoadingBuiltInTypes() {
    BuiltInTypeScope scope = BuiltInTypeScope.get(resourceSet);
    IEObjectDescription anyType = scope.getSingleElement(QualifiedName.create("any"));
    Assert.assertNotNull(anyType);
    String s = "";
    for (Resource resource : resourceSet.getResources()) {
        if (resource.getErrors().size() > 0) {
            for (Diagnostic d : resource.getErrors()) {
                s += "\n  " + d.getMessage() + " at " + resource.getURI() + ":" + d.getLine();
            }
        }
    }

    Assert.assertEquals("Resources definine built-in types must have no error."
            , "", s);
}
项目:xtext-extras    文件:AbstractUnresolvableReferenceWithNode.java   
@Override
public void applyToModel(IResolvedTypes resolvedTypes) {
    Resource resource = getExpression().eResource();
    if (resource instanceof LazyLinkingResource) {
        LazyLinkingResource lazyLinkingResource = (LazyLinkingResource) resource;

        TypeAwareLinkingDiagnosticContext context = new TypeAwareLinkingDiagnosticContext(this, resolvedTypes);
        DiagnosticMessage message = lazyLinkingResource.getDiagnosticMessageProvider()
                .getUnresolvedProxyMessage(context);
        if (message != null) {
            List<Resource.Diagnostic> diagnostics = getDiagnosticList(lazyLinkingResource, message);
            Diagnostic diagnostic = createDiagnostic(message);
            diagnostics.add(diagnostic);
        }
        EObject referenced = (InternalEObject) getExpression().eGet(getReference(), false);
        lazyLinkingResource.markUnresolvable(referenced);
    }
}
项目:xtext-extras    文件:AbstractXtextTests.java   
public final XtextResource getResourceAndExpect(InputStream in, URI uri, int expectedErrors) throws Exception {
    XtextResource resource = doGetResource(in, uri);
    checkNodeModel(resource);
    if (expectedErrors != UNKNOWN_EXPECTATION) {
        if (expectedErrors == EXPECT_ERRORS)
            assertFalse(Joiner.on('\n').join(resource.getErrors()), resource.getErrors().isEmpty());
        else
            assertEquals(Joiner.on('\n').join(resource.getErrors()), expectedErrors, resource.getErrors().size());
    }
    for(Diagnostic d: resource.getErrors()) {
        if (d instanceof ExceptionDiagnostic)
            fail(d.getMessage());
    }
    if (expectedErrors == 0 && resource.getContents().size() > 0 && shouldTestSerializer(resource)) {
        SerializerTestHelper tester = get(SerializerTestHelper.class);
        EObject obj = resource.getContents().get(0);
        tester.assertSerializeWithNodeModel(obj);
        tester.assertSerializeWithoutNodeModel(obj);
    }
    return resource;
}
项目:xtext-core    文件:DiagnosticConverterImpl.java   
@Override
public void convertResourceDiagnostic(Diagnostic diagnostic, Severity severity, IAcceptor<Issue> acceptor) {
    IssueImpl issue = new Issue.IssueImpl();
    issue.setSyntaxError(diagnostic instanceof XtextSyntaxDiagnostic);
    issue.setSeverity(severity);
    issue.setLineNumber(diagnostic.getLine());
    issue.setColumn(diagnostic.getColumn());
    issue.setMessage(diagnostic.getMessage());

    if (diagnostic instanceof org.eclipse.xtext.diagnostics.Diagnostic) {
        org.eclipse.xtext.diagnostics.Diagnostic xtextDiagnostic = (org.eclipse.xtext.diagnostics.Diagnostic) diagnostic;
        issue.setOffset(xtextDiagnostic.getOffset());
        issue.setLength(xtextDiagnostic.getLength());
    }
    if (diagnostic instanceof AbstractDiagnostic) {
        AbstractDiagnostic castedDiagnostic = (AbstractDiagnostic)diagnostic;
        issue.setUriToProblem(castedDiagnostic.getUriToProblem());
        issue.setCode(castedDiagnostic.getCode());
        issue.setData(castedDiagnostic.getData());
    }
    issue.setType(CheckType.FAST);
    acceptor.accept(issue);
}
项目:xtext-core    文件:DiagnosticConverterImpl.java   
/**
 * @since 2.4
 */
protected String[] getIssueData(org.eclipse.emf.common.util.Diagnostic diagnostic) {
    if (diagnostic instanceof AbstractValidationDiagnostic) {
        AbstractValidationDiagnostic diagnosticImpl = (AbstractValidationDiagnostic) diagnostic;
        return diagnosticImpl.getIssueData();
    } else {
        // replace any EObjects by their URIs
        EObject causer = getCauser(diagnostic);
        List<String> issueData = newArrayList();
        for (Object object : diagnostic.getData()) {
            if (object != causer && object instanceof EObject) {
                EObject eObject = (EObject)object;
                issueData.add(EcoreUtil.getURI(eObject).toString());
            } else if (object instanceof String) {
                issueData.add( (String) object);
            }
        }
        return issueData.toArray(new String[issueData.size()]);
    }
}
项目:xtext-core    文件:ToEcoreTrafoTest.java   
@Test public void testAbstractLanguageToMetamodel() throws Exception {
    XtextResource r = getResource("classpath:/" + AbstractTestLanguage.class.getName().replace('.', '/') + ".xtext");
    Grammar element = (Grammar) r.getParseResult().getRootASTElement();
    if (!r.getErrors().isEmpty()) {
        EList<Diagnostic> errors = r.getErrors();
        for (Diagnostic syntaxError : errors) {
            logger.debug(syntaxError.getMessage() + " - " + syntaxError.getLine());
        }
        fail(errors.toString());
    }
    List<TerminalRule> lexerRules = GrammarUtil.allTerminalRules(element);
    assertEquals(8, lexerRules.size());

    List<EPackage> list = Xtext2EcoreTransformer.doGetGeneratedPackages(element);
    assertNotNull(list);
    assertEquals(0, list.size());
}
项目:xtext-core    文件:AbstractXtextTests.java   
public final XtextResource getResourceAndExpect(InputStream in, URI uri, int expectedErrors) throws Exception {
    XtextResource resource = doGetResource(in, uri);
    checkNodeModel(resource);
    if (expectedErrors != UNKNOWN_EXPECTATION) {
        if (expectedErrors == EXPECT_ERRORS)
            assertFalse(Joiner.on('\n').join(resource.getErrors()), resource.getErrors().isEmpty());
        else
            assertEquals(Joiner.on('\n').join(resource.getErrors()), expectedErrors, resource.getErrors().size());
    }
    for(Diagnostic d: resource.getErrors()) {
        if (d instanceof ExceptionDiagnostic)
            fail(d.getMessage());
    }
    if (expectedErrors == 0 && resource.getContents().size() > 0 && shouldTestSerializer(resource)) {
        SerializerTestHelper tester = get(SerializerTestHelper.class);
        EObject obj = resource.getContents().get(0);
        tester.assertSerializeWithNodeModel(obj);
        tester.assertSerializeWithoutNodeModel(obj);
    }
    return resource;
}
项目:openhab-hdl    文件:ScriptEngineImpl.java   
private XExpression parseScriptIntoXTextEObject(String scriptAsString) throws ScriptParsingException {
    Resource resource = resourceSet.createResource(computeUnusedUri(resourceSet)); // IS-A XtextResource
    try {
        resource.load(new StringInputStream(scriptAsString), resourceSet.getLoadOptions());
    } catch (IOException e) {
        throw new ScriptParsingException("Unexpected IOException; from close() of a String-based ByteArrayInputStream, no real I/O; how is that possible???", scriptAsString, e);
    }

    List<Diagnostic> errors = resource.getErrors();
    if (errors.size() != 0) {
        throw new ScriptParsingException("Failed to parse expression (due to managed SyntaxError/s)", scriptAsString).addDiagnosticErrors(errors);
    }

    EList<EObject> contents = resource.getContents();

    if (!contents.isEmpty()) {
        Iterable<Issue> validationErrors = getValidationErrors(contents.get(0));
        if(!validationErrors.iterator().hasNext()) {
            return (XExpression) contents.get(0);
        } else {
            throw new ScriptParsingException("Failed to parse expression (due to managed ValidationError/s)", scriptAsString).addValidationIssues(validationErrors);
        }
    } else {
        return null;
    }
}
项目:CooperateModelingEnvironment    文件:AreaErrorIndicator.java   
@Override
public void doSignal(List<Diagnostic> errors, int cursorColumn, int cursorLine) {
    for (Diagnostic e : errors) {
        if (e instanceof AbstractDiagnostic) {
            AbstractDiagnostic error = (AbstractDiagnostic) e;

            int errorLine = error.getLine();
            int errorBegin = error.getColumn();
            int errorLength = error.getLength();

            if (errorLine != cursorLine) {
                return;
            }
            doSignal(cursorColumn, cursorLine, errorBegin, errorLength);
        }
    }
    oldColumn = cursorColumn;
    oldLine = cursorLine;
}
项目:CooperateModelingEnvironment    文件:CooperateCDOXtextEditor.java   
@Override
protected void handleCursorPositionChanged() {
    super.handleCursorPositionChanged();
    IXtextDocument document = getDocument();
    CooperateXtextDocument cooperateXtextDocument = document.getAdapter(CooperateXtextDocument.class);
    if (cooperateXtextDocument.getResource() == null) {
        return;
    }
    EList<Diagnostic> errors = cooperateXtextDocument.getResource().getErrors();

    if (ErrorIndicatorPreferenceHandler.INSTANCE.getErrorAreaIndicatorSetting()) {
        areaErrorIndicator.doSignal(errors, getCursorPosition());
    }
    if (ErrorIndicatorPreferenceHandler.INSTANCE.getErrorLineIndicatorSetting()) {
        lineErrorIndicator.doSignal(errors, getCursorPosition());
    }
}
项目:anatlyzer    文件:ATLModel.java   
public ATLModel(Resource original, String fileLocation, boolean keepCopier) { 
    DynamicToStaticCopier copier = new DynamicToStaticCopier(fileLocation);
    ResourceSet rs = original.getResourceSet();
    if ( rs == null ) {
        rs = new ResourceSetImpl();
    }
    resource = rs.createResource(URI.createURI("trafo.ext"));       
    copier.copyResource(original, resource);

    if ( keepCopier ) {
        this.copierTrace = new ATLModelTrace(copier);
    }

    mainFileLocation = fileLocation;
    fileLocations.add(fileLocation);

    errors = new ErrorModel(resource);
    typing = new TypingModel(resource);

    hasSyntaxErrors = original.getErrors().size() > 0;
    if ( hasSyntaxErrors ) {
        for (Diagnostic diagnostic : original.getErrors()) {
            errors.signalParseError(diagnostic.getLocation(), diagnostic.getMessage(), diagnostic.getLine() + ":" + diagnostic.getColumn());
        }
    }
}
项目:anatlyzer    文件:AnalyserUtils.java   
public static void extendWithPreconditions(ATLModel atlModel, List<String> preconditions, IAtlFileLoader loader) throws PreconditionParseError {
    if ( preconditions.size() > 0 ) {
        String text = "library preconditions;";
        int idx = 0;
        for (String pre : preconditions) {
            text = text + "\n-- @precondition \n" + "helper def: precondition_" + idx + " : Boolean = " + pre + ";"; 
            idx++;
        }

        Resource r = loader.load(text);
        String[] messages = new String[r.getErrors().size()];
        int i = 0;
        for (Diagnostic diagnostic : r.getErrors()) {
            messages[i] = diagnostic.toString();
            i++;
        }

        if ( r.getErrors().size() > 0 )
            throw new PreconditionParseError(messages);

        atlModel.extendWithPreconditions(r);
    }
}
项目:emfstore-rest    文件:EmfStoreValidator.java   
private void removeAcceptedErrors(EList<Diagnostic> errors) {
    Iterator<Diagnostic> iterator = errors.iterator();
    while (iterator.hasNext()) {
        Resource.Diagnostic diagnostic = iterator.next();

        // removes errors for projectState and changePackage references in versions.
        if (diagnostic instanceof FeatureNotFoundException) {
            FeatureNotFoundException featureNotFoundException = (FeatureNotFoundException) diagnostic;
            if (featureNotFoundException.getObject() instanceof Version) {
                if (featureNotFoundException.getName().equals("projectState")
                    || featureNotFoundException.getName().equals("changes")) {
                    iterator.remove();
                }
            }
        }
    }
}
项目:eclectic    文件:ParseApiDesc.java   
public void showErrors(XtextResource resource) {
    String error = "";
    if (! resource.getErrors().isEmpty()) {
        error += "### Parse: \n";
        for (Diagnostic d : resource.getErrors()) {
            error += d.getMessage() + " in " + d.getLine()  + "\n";

        }
    }
    if ( error.length() == 0 ) {
        System.out.println("Ok : " + resource.getContents());
    } else {
        System.out.println(error);
    }

}
项目:eclectic    文件:ApiDescriptionLanguageLoader.java   
public void showErrors(XtextResource resource) {
    String error = "";
    if (! resource.getErrors().isEmpty()) {
        error += "### Parse: \n";
        for (Diagnostic d : resource.getErrors()) {
            error += d.getMessage() + " in " + d.getLine()  + "\n";

        }
    }
    if ( error.length() == 0 ) {
        System.out.println("Ok : " + resource.getContents());
    } else {
        System.out.println(error);
    }

}
项目:eclectic    文件:AbstractParserUtil.java   
public void showErrors(XtextResource resource) {
    String error = "";
    if (! resource.getErrors().isEmpty()) {
        error += "### Parse: \n";
        for (Diagnostic d : resource.getErrors()) {
            error += d.getMessage() + " in " + d.getLine()  + "\n";

        }
    }
    if ( error.length() == 0 ) {
        System.out.println("Ok : " + resource.getContents());
    } else {
        System.out.println(error);
    }

}
项目:eclectic    文件:TaoFrontend.java   
@Override
public R compile(String path) throws EclecticException, IOException {
    XtextResource r = parse(path, new FileInputStream(path));
    TaoTransformation t = (TaoTransformation) r.getContents().get(0);

    // TODO: DUPLICATED WITH KOANFRONTEND: MERGE
    if ( r.getErrors().size() > 0 ) {
        String str = "";
        EList<Diagnostic> errors = r.getErrors();
        for (Diagnostic diagnostic : errors) {
            str = str + diagnostic.toString() + "\n";
        }
        throw new EclecticException("Syntax errors: " + str);
    }

    FrontendUtil.setFilePathToElements(path, t);

    return next.compile(t);
}
项目:eclectic    文件:MappingsFrontend.java   
@Override
public R compile(String path) throws EclecticException, IOException {
    XtextResource r = parse(path, new FileInputStream(path));
    MappingTransformation t = (MappingTransformation) r.getContents().get(0);

    // TODO: DUPLICATED WITH KOANFRONTEND: MERGE
    if ( r.getErrors().size() > 0 ) {
        String str = "";
        EList<Diagnostic> errors = r.getErrors();
        for (Diagnostic diagnostic : errors) {
            str = str + diagnostic.toString() + "\n";
        }
        throw new EclecticException("Syntax errors: " + str);
    }

    FrontendUtil.setFilePathToElements(path, t);

    return next.compile(t);
}
项目:eclectic    文件:AttributionFrontend.java   
@Override
public R compile(String path) throws EclecticException {
    XtextResource r = parse(path, null);
    AttributionTransformation t = (AttributionTransformation) r.getContents().get(0);

    // TODO: DUPLICATED WITH KOANFRONTEND: MERGE
    if ( r.getErrors().size() > 0 ) {
        String str = "";
        EList<Diagnostic> errors = r.getErrors();
        for (Diagnostic diagnostic : errors) {
            str = str + diagnostic.toString() + "\n";
        }
        throw new EclecticException("Syntax errors: " + str);
    }

    FrontendUtil.setFilePathToElements(path, t);

    return next.compile(t);
}
项目:eclectic    文件:ChainFrontend.java   
@Override
public R compile(String path) throws EclecticException, IOException {
    XtextResource r = parse(path, new FileInputStream(path));
    ChainTransformation t = (ChainTransformation) r.getContents().get(0);

    // TODO: DUPLICATED WITH KOANFRONTEND: MERGE
    if ( r.getErrors().size() > 0 ) {
        String str = "";
        EList<Diagnostic> errors = r.getErrors();
        for (Diagnostic diagnostic : errors) {
            str = str + diagnostic.toString() + "\n";
        }
        throw new EclecticException("Syntax errors: " + str);
    }

    FrontendUtil.setFilePathToElements(path, t);

    return next.compile(t);
}
项目:eclectic    文件:QoolFrontend.java   
public R compile(String path, InputStream qoolS) throws EclecticException {
    XtextResource r = parse(path, qoolS);
    QoolTransformation t = (QoolTransformation) r.getContents().get(0);

    // TODO: DUPLICATED WITH KOANFRONTEND: MERGE
    if ( r.getErrors().size() > 0 ) {
        String str = "";
        EList<Diagnostic> errors = r.getErrors();
        for (Diagnostic diagnostic : errors) {
            str = str + diagnostic.toString() + "\n";
        }
        throw new EclecticException("Syntax errors: " + str);
    }

    // Set the path. For the moment I traverse every element so as not
    // to implement a complicated getFile() method

    FrontendUtil.setFilePathToElements(path, t);

    return next.compile(t);
}
项目:eclectic    文件:StreamDescLanguageLoader.java   
public void showErrors(XtextResource resource) {
    String error = "";
    if (! resource.getErrors().isEmpty()) {
        error += "### Parse: \n";
        for (Diagnostic d : resource.getErrors()) {
            error += d.getMessage() + " in " + d.getLine()  + "\n";

        }
    }
    if ( error.length() == 0 ) {
        System.out.println("Ok : " + resource.getContents());
    } else {
        System.out.println(error);
    }

}
项目:xsemantics    文件:TypeSystemTest.java   
public void testConstant() throws IOException {
    StringConstant stringConstant = FjFactory.eINSTANCE.createStringConstant();
    stringConstant.setConstant("foobar");
    TypeResult typeResult = fixture.getType(stringConstant);
    assertTrue(typeResult.getBasicType() != null);
    assertEquals("String", AuxiliaryFunctions.getBasicType(typeResult.getType()).getBasic());

    IntConstant intConstant = FjFactory.eINSTANCE.createIntConstant();
    intConstant.setConstant(10);
    typeResult = fixture.getType(intConstant);
    assertTrue(typeResult.getBasicType() != null);
    assertEquals("int", AuxiliaryFunctions.getBasicType(typeResult.getType()).getBasic());

    BoolConstant boolConstant = FjFactory.eINSTANCE.createBoolConstant();
    boolConstant.setConstant("true");
    typeResult = fixture.getType(boolConstant);
    assertTrue(typeResult.getBasicType() != null);
    assertEquals("boolean", AuxiliaryFunctions.getBasicType(typeResult.getType()).getBasic());

    Resource resource = loadFromString
        ("class A { int m() { return 10; } boolean n() {return false;} String p() { return \"foo\";}}");
    EList<Diagnostic> errors = resource.getErrors();
    assertTrue(errors.size() == 0);
}
项目:joynr    文件:Executor.java   
public void generate() {
    ModelLoader modelLoader = prepareGeneratorEnvironment();
    for (Resource resource : modelLoader.getResources()) {
        if (resource.getErrors().size() > 0) {
            StringBuilder errorMsg = new StringBuilder();
            errorMsg.append("Error loading model " + resource.getURI().toString()
                    + ". The following errors occured: \n");
            for (Diagnostic error : resource.getErrors()) {
                errorMsg.append(error.getMessage());
            }
            logger.log(Level.SEVERE, errorMsg.toString());
            System.exit(-1);
        } else {
            generator.doGenerate(resource, outputFileSystem);
        }
    }
}
项目:n4js    文件:XcoreReader.java   
@Override
protected void invokeInternal(WorkflowContext ctx, ProgressMonitor monitor,
        Issues issues) {
    ResourceSet resourceSet = getResourceSet();

    // due to some Xcore peculiarity we have to access the IAllContainerState here
    // to trigger some lazy init logic
    IAllContainersState allContainerState = (IAllContainersState) EcoreUtil.getAdapter(resourceSet.eAdapters(),
            IAllContainersState.class);
    allContainerState.isEmpty("");

    Multimap<String, URI> uris = getPathTraverser().resolvePathes(pathes,
            new Predicate<URI>() {
        @Override
        public boolean apply(URI input) {
            return input.fileExtension().equals(XCORE_FILE_EXT);
        }
    });
    List<Resource> resources = new ArrayList<>();
    for (URI uri : uris.values()) {
        LOGGER.info(uri);
        try {
            resources.add(parse(uri, resourceSet));
        } catch (Exception e) {
            LOGGER.error("Problem during loading of resource @ " + uri, e);
        }
    }
    installIndex(resourceSet);
    for (Resource r : resources) {
        EcoreUtil.resolveAll(r);
        for (Diagnostic x : r.getErrors()) {
            issues.addError(x.getMessage(), x);
        }

    }
    ctx.set(slot, resources);
}
项目:n4js    文件:AbstractBuilderParticipantTest.java   
/**
 * Will only return parse errors, not validation errors!
 */
protected List<Resource.Diagnostic> getEditorErrors(XtextEditor fileXtextEditor) {
    return fileXtextEditor.getDocument().readOnly(new IUnitOfWork<List<Diagnostic>, XtextResource>() {

        @Override
        public List<Resource.Diagnostic> exec(XtextResource state) throws Exception {
            EcoreUtil.resolveAll(state);
            return state.getErrors();
        }
    });
}
项目:n4js    文件:PositiveAnalyser.java   
@Override
public void analyse(Script script, String codeName, String code) {
    List<Diagnostic> errors = null;
    try {
        errors = getScriptErrors(script);
        // if (serializerTester != null) {
        // serializerTester.assertSerializeWithNodeModel(script);
        // }
    } catch (Throwable t) {
        StringWriter writer = new StringWriter();
        t.printStackTrace(new PrintWriter(writer));
        assertEquals(code, writer.toString());
        return;
    }
    if (!errors.isEmpty()) {
        String msg = "expected no errors in " + codeName + " but I got : " + errors.size();
        if (this.logger.isDebugEnabled()) {
            StringBuilder sb = new StringBuilder(msg).append("\n");
            sb.append("========== " + codeName + " ==========\n");
            if (this.logCode) {
                sb.append(code).append("\n");
            }
            sb.append(">>>> errors: ").append("\n");
            sb.append(this.aggregateDiagnosticsToStringBuilder(codeName, errors));
            sb.append(">>>> warnings: ").append("\n");
            sb.append("<<<<").append("\n");
            sb.append("========================================").append("\n");
            this.logger.debug(sb);
        }
        assertEquals(msg, withLineNumbers(code),
                this.aggregateDiagnosticsToStringBuilder(codeName, errors).toString());
    }
}
项目:n4js    文件:BaseAnalyser.java   
/***/
// TODO after java update bring back null analysis
// protected StringBuilder agregateDiagnosticsToStringBuilder(@Nonnull final List<Diagnostic> issues) {
protected StringBuilder aggregateDiagnosticsToStringBuilder(String codeName, final List<Diagnostic> issues) {
    StringBuilder result = new StringBuilder(codeName).append('\n');
    for (Diagnostic diagnostic : issues) {
        if (diagnostic instanceof ExceptionDiagnostic) {
            ((ExceptionDiagnostic) diagnostic).getException().printStackTrace();
        }
        result.append(" - line: " + diagnostic.getLine() + ", message: " + diagnostic.getMessage() + "\n");
    }
    return result;
}
项目:n4js    文件:BaseAnalyser.java   
/***/
// TODO after java update bring back null analysis
// protected List<Diagnostic> getScriptErrors(final @Nonnull Script script) {
protected List<Diagnostic> getScriptErrors(final Script script) {
    // may throw NPE
    return script.eResource().getErrors();
}
项目:n4js    文件:ErrorAwareLinkingService.java   
/**
 * Add the error to the resource of the given {@code context} if it does support validation.
 *
 * @param context
 *            the context object that caused the error.
 * @param node
 *            the error location.
 * @param error
 *            the actual error description.
 */
protected void addError(EObject context, INode node, IEObjectDescriptionWithError error) {
    N4JSResource resource = (N4JSResource) context.eResource();
    if (resource.isValidationDisabled())
        return;

    List<Diagnostic> list = resource.getErrors();

    // Convert key value user data to String array
    String[] userData = null;
    if (error.getUserDataKeys() != null) {
        ArrayList<String> userDataList = new ArrayList<>(error.getUserDataKeys().length * 2);
        for (String userDataKey : error.getUserDataKeys()) {
            final String userDataValue = error.getUserData(userDataKey);
            if (userDataValue != null) {
                userDataList.add(userDataKey);
                userDataList.add(userDataValue);
            }
        }
        userData = userDataList.toArray(new String[userDataList.size()]);
    }

    Diagnostic diagnostic = new XtextLinkingDiagnostic(node, error.getMessage(), error.getIssueCode(), userData);

    if (!list.contains(diagnostic))
        list.add(diagnostic);
}
项目:xtext-extras    文件:AbstractUnresolvableReferenceWithNode.java   
protected Resource.Diagnostic createDiagnostic(DiagnosticMessage message) {
    Diagnostic diagnostic = new XtextLinkingDiagnostic(
            node, 
            message.getMessage(),
            message.getIssueCode(), message.getIssueData());
    return diagnostic;
}
项目:xtext-extras    文件:AbstractUnresolvableReferenceWithNode.java   
protected List<Diagnostic> getDiagnosticList(LazyLinkingResource resource, /* @Nullable */ DiagnosticMessage message) throws AssertionError {
    if (message != null) {
        switch (message.getSeverity()) {
            case ERROR:
                return resource.getErrors();
            case WARNING:
                return resource.getWarnings();
            default:
                throw new AssertionError("Unexpected severity: " + message.getSeverity());
        }
    }
    return Collections.emptyList();
}
项目:org.lovian.eaxmireader    文件:SysMLChecker.java   
/**
 * To detect if there is error in SysML file, and return a error list
 * 
 * @param file
 *            file is the SysML which is going to test
 * @param resourceSet
 *            resourceSet is the EMF resourceSet
 * @return errorList errorList: a list of errors
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws TransformerException
 */
public ArrayList<ErrorInfo> checkErrorAndGetErrorList(File file, ResourceSet resourceSet)
        throws IOException, ParserConfigurationException, SAXException, TransformerException {

    String method = "SysMLChecker_getErrorList(): ";
    long startTime = System.currentTimeMillis();
    MyLog.info(method + "start");

    URI uri = URI.createFileURI(file.getPath());
    ArrayList<ErrorInfo> errorLog = new ArrayList<ErrorInfo>();

    // load the resource into memory

    @SuppressWarnings("unused")
    Model umlModel = UML2Util.load(resourceSet, uri, UMLPackage.Literals.MODEL);
    // get all error list
    for (Resource umlResourceImpl : resourceSet.getResources()) {
        if (!umlResourceImpl.getErrors().isEmpty()) {
            for (Diagnostic error : umlResourceImpl.getErrors()) {
                ErrorInfo errorInfo = new ErrorInfo(error.getLine(), error.getColumn(), error.getMessage());
                if (!error.getMessage().contains("org.xml.sax.SAXParseException"))
                    // filter the sax exception errors
                    errorLog.add(errorInfo);
            }
        }
    }
    umlModel = null;

    MyLog.info(method + "end with " + (System.currentTimeMillis() - startTime) + " millisecond");
    MyLog.info();
    return errorLog;

}
项目:xtext-core    文件:DiagnosticConverterImpl.java   
@Override
public void convertValidatorDiagnostic(org.eclipse.emf.common.util.Diagnostic diagnostic,
        IAcceptor<Issue> acceptor) {
    Severity severity = getSeverity(diagnostic);
    if (severity == null)
        return;
    IssueImpl issue = new Issue.IssueImpl();
    issue.setSeverity(severity);

    IssueLocation locationData = getLocationData(diagnostic);
    if (locationData != null) {
        issue.setLineNumber(locationData.lineNumber);
        issue.setColumn(locationData.column);
        issue.setOffset(locationData.offset);
        issue.setLength(locationData.length);
    }
    final EObject causer = getCauser(diagnostic);
    if (causer != null)
        issue.setUriToProblem(EcoreUtil.getURI(causer));

    issue.setCode(getIssueCode(diagnostic));
    issue.setType(getIssueType(diagnostic));
    issue.setData(getIssueData(diagnostic));

    //      marker.put(IXtextResourceChecker.DIAGNOSTIC_KEY, diagnostic);
    issue.setMessage(diagnostic.getMessage());
    //      marker.put(IMarker.PRIORITY, Integer.valueOf(IMarker.PRIORITY_LOW));
    acceptor.accept(issue);
}
项目:xtext-core    文件:DiagnosticConverterImpl.java   
/**
 * @since 2.4
 */
protected CheckType getIssueType(org.eclipse.emf.common.util.Diagnostic diagnostic) {
    if (diagnostic instanceof AbstractValidationDiagnostic) {
        AbstractValidationDiagnostic diagnosticImpl = (AbstractValidationDiagnostic) diagnostic;
        return diagnosticImpl.getCheckType();
    } else {
        // default to FAST
        return CheckType.FAST;
    }
}
项目:xtext-core    文件:DiagnosticConverterImpl.java   
/**
 * @since 2.4
 */
protected String getIssueCode(org.eclipse.emf.common.util.Diagnostic diagnostic) {
    if (diagnostic instanceof AbstractValidationDiagnostic) {
        AbstractValidationDiagnostic diagnosticImpl = (AbstractValidationDiagnostic) diagnostic;
        return diagnosticImpl.getIssueCode();
    } else {
        return diagnostic.getSource() + "." + diagnostic.getCode();
    }
}
项目:xtext-core    文件:DiagnosticConverterImpl.java   
/**
 * @since 2.4
 */
protected Severity getSeverity(org.eclipse.emf.common.util.Diagnostic diagnostic) {
    if (diagnostic.getSeverity() == org.eclipse.emf.common.util.Diagnostic.OK)
        return null;
    switch (diagnostic.getSeverity()) {
        case org.eclipse.emf.common.util.Diagnostic.WARNING:
            return Severity.WARNING;
        case org.eclipse.emf.common.util.Diagnostic.INFO:
            return Severity.INFO;
        default :
            return Severity.ERROR;
    }
}
项目:xtext-core    文件:DiagnosticConverterImpl.java   
protected EObject getCauser(org.eclipse.emf.common.util.Diagnostic diagnostic) {
    // causer is the first element see Diagnostician.getData
    if (diagnostic.getData().isEmpty())
        return null;
    Object causer = diagnostic.getData().get(0);
    return causer instanceof EObject ? (EObject) causer : null;
}