Search in sources :

Example 6 with Diagnostic

use of org.eclipse.emf.ecore.resource.Resource.Diagnostic in project smarthome by eclipse.

the class ModelRepositoryImpl method validateModel.

/**
 * Validates the given model.
 *
 * There are two "layers" of validation
 * <ol>
 * <li>
 * errors when loading the resource. Usually these are syntax violations which irritate the parser. They will be
 * returned as a String.
 * <li>
 * all kinds of other errors (i.e. violations of validation checks) will only be logged, but not included in the
 * return value.
 * </ol>
 * <p>
 * Validation will be done on a separate resource, in order to keep the original one intact in case its content
 * needs to be removed because of syntactical errors.
 *
 * @param name
 * @param inputStream
 * @return error messages as a String if any syntactical error were found, <code>null</code> otherwise
 * @throws IOException if there was an error with the given {@link InputStream}, loading the resource from there
 */
private String validateModel(String name, InputStream inputStream) throws IOException {
    // use another resource for validation in order to keep the original one for emergency-removal in case of errors
    Resource resource = resourceSet.createResource(URI.createURI("tmp_" + name));
    try {
        resource.load(inputStream, Collections.EMPTY_MAP);
        StringBuilder criticalErrors = new StringBuilder();
        List<String> warnings = new LinkedList<>();
        if (resource != null && !resource.getContents().isEmpty()) {
            // Check for syntactical errors
            for (Diagnostic diagnostic : resource.getErrors()) {
                criticalErrors.append(MessageFormat.format("[{0},{1}]: {2}\n", Integer.toString(diagnostic.getLine()), Integer.toString(diagnostic.getColumn()), diagnostic.getMessage()));
            }
            if (criticalErrors.length() > 0) {
                return criticalErrors.toString();
            }
            // Check for validation errors, but log them only
            try {
                org.eclipse.emf.common.util.Diagnostic diagnostic = Diagnostician.INSTANCE.validate(resource.getContents().get(0));
                for (org.eclipse.emf.common.util.Diagnostic d : diagnostic.getChildren()) {
                    warnings.add(d.getMessage());
                }
                if (warnings.size() > 0) {
                    logger.info("Validation issues found in configuration model '{}', using it anyway:\n{}", name, StringUtils.join(warnings, "\n"));
                }
            } catch (NullPointerException e) {
                // see https://github.com/eclipse/smarthome/issues/3335
                logger.debug("Validation of '{}' skipped due to internal errors.", name);
            }
        }
    } finally {
        resourceSet.getResources().remove(resource);
    }
    return null;
}
Also used : XtextResource(org.eclipse.xtext.resource.XtextResource) Resource(org.eclipse.emf.ecore.resource.Resource) Diagnostic(org.eclipse.emf.ecore.resource.Resource.Diagnostic) LinkedList(java.util.LinkedList)

Example 7 with Diagnostic

use of org.eclipse.emf.ecore.resource.Resource.Diagnostic in project n4js by eclipse.

the class ExceptionAnalyser method getScriptErrors.

@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;
}
Also used : Expression(org.eclipse.n4js.n4JS.Expression) TypeRef(org.eclipse.n4js.ts.typeRefs.TypeRef) ExceptionDiagnostic(org.eclipse.xtext.diagnostics.ExceptionDiagnostic) Diagnostic(org.eclipse.emf.ecore.resource.Resource.Diagnostic) ExceptionDiagnostic(org.eclipse.xtext.diagnostics.ExceptionDiagnostic) RuleEnvironment(org.eclipse.xsemantics.runtime.RuleEnvironment) RuleFailedException(org.eclipse.xsemantics.runtime.RuleFailedException) RuleFailedException(org.eclipse.xsemantics.runtime.RuleFailedException)

Example 8 with Diagnostic

use of org.eclipse.emf.ecore.resource.Resource.Diagnostic in project n4js by eclipse.

the class XcoreReader method invokeInternal.

@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);
}
Also used : IAllContainersState(org.eclipse.xtext.resource.containers.IAllContainersState) Resource(org.eclipse.emf.ecore.resource.Resource) ArrayList(java.util.ArrayList) Diagnostic(org.eclipse.emf.ecore.resource.Resource.Diagnostic) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) URI(org.eclipse.emf.common.util.URI)

Example 9 with Diagnostic

use of org.eclipse.emf.ecore.resource.Resource.Diagnostic in project n4js by eclipse.

the class BuiltInTypeScopeTest method testLoadingBuiltInTypes.

@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);
}
Also used : Resource(org.eclipse.emf.ecore.resource.Resource) Diagnostic(org.eclipse.emf.ecore.resource.Resource.Diagnostic) BuiltInTypeScope(org.eclipse.n4js.ts.scoping.builtin.BuiltInTypeScope) IEObjectDescription(org.eclipse.xtext.resource.IEObjectDescription) Test(org.junit.Test)

Example 10 with Diagnostic

use of org.eclipse.emf.ecore.resource.Resource.Diagnostic in project statecharts by Yakindu.

the class STextExpressionParser method parseExpression.

public EObject parseExpression(String expression, String ruleName, String specification) {
    StextResource resource = getResource();
    resource.setURI(URI.createURI(getUri(), true));
    ParserRule parserRule = XtextFactory.eINSTANCE.createParserRule();
    parserRule.setName(ruleName);
    IParseResult result = parser.parse(parserRule, new StringReader(expression));
    EObject rootASTElement = result.getRootASTElement();
    resource.getContents().add(rootASTElement);
    ListBasedDiagnosticConsumer diagnosticsConsumer = new ListBasedDiagnosticConsumer();
    Statechart sc = SGraphFactory.eINSTANCE.createStatechart();
    sc.setDomainID(domainId);
    sc.setName("sc");
    if (specification != null) {
        sc.setSpecification(specification);
    }
    resource.getContents().add(sc);
    resource.getLinkingDiagnostics().clear();
    linker.linkModel(sc, diagnosticsConsumer);
    linker.linkModel(rootASTElement, diagnosticsConsumer);
    resource.resolveLazyCrossReferences(CancelIndicator.NullImpl);
    resource.resolveLazyCrossReferences(CancelIndicator.NullImpl);
    Multimap<SpecificationElement, Diagnostic> diagnostics = resource.getLinkingDiagnostics();
    if (diagnostics.size() > 0) {
        throw new LinkingException(diagnostics.toString());
    }
    if (result.hasSyntaxErrors()) {
        StringBuilder errorMessages = new StringBuilder();
        Iterable<INode> syntaxErrors = result.getSyntaxErrors();
        for (INode iNode : syntaxErrors) {
            errorMessages.append(iNode.getSyntaxErrorMessage());
            errorMessages.append("\n");
        }
        throw new SyntaxException("Could not parse expression, syntax errors: " + errorMessages);
    }
    if (diagnosticsConsumer.hasConsumedDiagnostics(Severity.ERROR)) {
        throw new LinkingException("Error during linking: " + diagnosticsConsumer.getResult(Severity.ERROR));
    }
    return rootASTElement;
}
Also used : ParserRule(org.eclipse.xtext.ParserRule) INode(org.eclipse.xtext.nodemodel.INode) StextResource(org.yakindu.sct.model.stext.resource.StextResource) SpecificationElement(org.yakindu.sct.model.sgraph.SpecificationElement) Diagnostic(org.eclipse.emf.ecore.resource.Resource.Diagnostic) EObject(org.eclipse.emf.ecore.EObject) StringReader(java.io.StringReader) ListBasedDiagnosticConsumer(org.eclipse.xtext.resource.impl.ListBasedDiagnosticConsumer) Statechart(org.yakindu.sct.model.sgraph.Statechart) IParseResult(org.eclipse.xtext.parser.IParseResult)

Aggregations

Diagnostic (org.eclipse.emf.ecore.resource.Resource.Diagnostic)32 Test (org.junit.Test)12 ExceptionDiagnostic (org.eclipse.xtext.diagnostics.ExceptionDiagnostic)10 Resource (org.eclipse.emf.ecore.resource.Resource)9 XtextResource (org.eclipse.xtext.resource.XtextResource)8 XtextLinkingDiagnostic (org.eclipse.xtext.linking.impl.XtextLinkingDiagnostic)7 BasicDiagnostic (org.eclipse.emf.common.util.BasicDiagnostic)6 Issue (org.eclipse.xtext.validation.Issue)6 List (java.util.List)5 EObject (org.eclipse.emf.ecore.EObject)5 Severity (org.eclipse.xtext.diagnostics.Severity)5 IDiagnosticConverter (org.eclipse.xtext.validation.IDiagnosticConverter)5 ResourceValidatorImpl (org.eclipse.xtext.validation.ResourceValidatorImpl)5 IOException (java.io.IOException)4 XtendFile (org.eclipse.xtend.core.xtend.XtendFile)3 XtendFunction (org.eclipse.xtend.core.xtend.XtendFunction)3 XBlockExpression (org.eclipse.xtext.xbase.XBlockExpression)3 ComparisonFailure (org.junit.ComparisonFailure)3 ArrayList (java.util.ArrayList)2 URI (org.eclipse.emf.common.util.URI)2