Java 类org.eclipse.xtext.validation.Issue 实例源码

项目:dsl-devkit    文件:FormatQuickfixProvider.java   
/**
 * Semantic quickfix setting the override flag for a rule.
 *
 * @param issue
 *          the issue
 * @param acceptor
 *          the acceptor
 */
@Fix(FormatJavaValidator.OVERRIDE_MISSING_CODE)
public void setOverride(final Issue issue, final IssueResolutionAcceptor acceptor) {
  acceptor.accept(issue, "Set override", "Set override flag.", null, new IModification() {
    @Override
    public void apply(final IModificationContext context) throws BadLocationException {
      context.getXtextDocument().modify(new IUnitOfWork<Void, XtextResource>() {
        @Override
        public java.lang.Void exec(final XtextResource state) {
          Rule rule = (Rule) state.getEObject(issue.getUriToProblem().fragment());
          rule.setOverride(true);
          return null;
        }
      });
    }
  });
}
项目:dsl-devkit    文件:CheckConfigurationStoreService.java   
/**
 * Gets the language for the given object.
 *
 * @param context
 *          object
 * @return the language the corresponding resource was parsed from, may be {@code null}
 */
private String getLanguage(final Object context) {
  if (context instanceof EObject) {
    Resource resource = ((EObject) context).eResource();
    if (resource instanceof LazyLinkingResource) {
      return ((LazyLinkingResource) resource).getLanguageName();
    }
  } else if (context instanceof Issue) {
    URI uri = ((Issue) context).getUriToProblem();
    if (uri != null) {
      Registry registry = IResourceServiceProvider.Registry.INSTANCE;
      IResourceServiceProvider resourceServiceProvider = registry.getResourceServiceProvider(uri);
      if (resourceServiceProvider != null) {
        return resourceServiceProvider.get(Injector.class).getInstance(Key.get(String.class, Names.named(Constants.LANGUAGE_NAME)));
      } else {
        LOGGER.error("Could not fetch a ResourceServiceProvider for URI: " + uri); //$NON-NLS-1$
      }
    } else {
      LOGGER.warn("Could not fetch eResource from issue: URI to problem is null"); //$NON-NLS-1$
    }
  }

  return null;
}
项目:dsl-devkit    文件:AbstractQuickFixTest.java   
/**
 * Finds all resolutions for issues with a specific issue code.
 *
 * @param issueCode
 *          to find resolutions for, may be {@code null}
 * @param quickfixLabel
 *          to find resolutions for, may be {@code null}
 * @return {@link List} of resolutions for issues with a specific code
 */
private List<IssueResolution> resolutionsFor(final String issueCode, final String quickfixLabel) {
  final List<IssueResolution> resolutions = new ArrayList<IssueResolution>();

  for (final Issue issue : issuesWith(issueCode)) {
    UiThreadDispatcher.dispatchAndWait(new Runnable() {
      @Override
      public void run() {
        if (quickfixLabel == null) {
          resolutions.addAll(getIssueResolutionProvider().getResolutions(issue));
        } else {
          for (IssueResolution r : getIssueResolutionProvider().getResolutions(issue)) {
            if (quickfixLabel.equals(r.getLabel())) {
              resolutions.add(r);
            }
          }
        }
      }
    });
  }

  return resolutions;
}
项目:n4js    文件:URIPropertyMatcher.java   
@Override
public boolean matches(Issue issue) {
    URI actualValue = getActualValue.apply(issue);
    if (actualValue == null)
        return false;

    List<String> actualSegments = actualValue.segmentsList();
    List<String> expectedSegments = expectedPattern.segmentsList();

    switch (mode) {
    case StartsWith:
        return Collections.indexOfSubList(actualSegments, expectedSegments) == 0;
    case EndsWith:
        return Collections.lastIndexOfSubList(actualSegments, expectedSegments) == actualSegments.size()
                - expectedSegments.size();
    case Equals:
        return actualSegments.equals(expectedSegments);
    }

    throw new IllegalStateException("Unknown URI property matching mode: " + mode);
}
项目:n4js    文件:URIPropertyMatcher.java   
@Override
protected String explainMismatch(Issue issue) {
    URI actualValue = getActualValue.apply(issue);
    if (actualValue == null)
        return "Actual value is null";

    switch (mode) {
    case StartsWith:
        return "'" + expectedPattern + "' is not a prefix of value '" + actualValue + "'";
    case EndsWith:
        return "'" + expectedPattern + "' is not a suffix of value '" + actualValue + "'";
    case Equals:
        return "Value '" + actualValue + "' is not equal to expected value'"
                + expectedPattern + "'";
    }

    throw new IllegalStateException("Unknown URI property matching mode: " + mode);
}
项目:n4js    文件:IssueExpectations.java   
/**
 * Matches the expectations in the added issues matchers against the given issues.
 *
 * @param issues
 *            the issues to match the expectations against
 * @param messages
 *            if this parameter is not <code>null</code>, this method will add an explanatory message for each
 *            mismatch
 * @return <code>true</code> if and only if every expectation was matched against an issue and every issue in the
 *         given collection was matched by an expectation
 */
public boolean matchesExactly(Collection<Issue> issues, List<String> messages) {
    Collection<Issue> issueCopy = new LinkedList<>(issues);
    Collection<IssueMatcher> matcherCopy = new LinkedList<>(issueMatchers);

    performMatching(issueCopy, matcherCopy, messages);
    if (inverted) {
        if (issueCopy.isEmpty() && matcherCopy.isEmpty()) {
            if (issueMatchers.isEmpty() && messages != null) {
                messages.add("Expected issues, but got nothing");
            } else {
                explainIssues(issues, messages, inverted);
                explainExpectations(issueMatchers, messages, inverted);
            }
            return false;
        }
    } else {
        if (!issueCopy.isEmpty() || !matcherCopy.isEmpty()) {
            explainIssues(issueCopy, messages, inverted);
            explainExpectations(matcherCopy, messages, inverted);
            return false;
        }
    }
    return true;
}
项目:n4js    文件:IssueExpectations.java   
/**
 * Matches the expectations in the added issues matchers against the given issues.
 *
 * @param issues
 *            the issues to match the expectations against
 * @param messages
 *            if this parameter is not <code>null</code>, this method will add an explanatory message for each
 *            mismatch
 * @return <code>true</code> if and only if every expectation was matched against an issue
 */
public boolean matchesAllExpectations(Collection<Issue> issues, List<String> messages) {
    Collection<Issue> issueCopy = new LinkedList<>(issues);
    Collection<IssueMatcher> matcherCopy = new LinkedList<>(issueMatchers);

    performMatching(issueCopy, matcherCopy, messages);
    if (inverted) {
        if (matcherCopy.isEmpty()) {
            explainExpectations(issueMatchers, messages, inverted);
            return false;
        }
    } else {
        if (!matcherCopy.isEmpty()) {
            explainExpectations(matcherCopy, messages, inverted);
            return false;
        }
    }
    return false;
}
项目:n4js    文件:IssueExpectations.java   
/**
 * Matches the expectations in the added issues matchers against the given issues.
 *
 * @param issues
 *            the issues to match the expectations against
 * @param messages
 *            if this parameter is not <code>null</code>, this method will add an explanatory message for each
 *            mismatch
 * @return <code>true</code> if and only if every issue in the given collection was matched by an expectation
 */
public boolean matchesAllIssues(Collection<Issue> issues, List<String> messages) {
    Collection<Issue> issueCopy = new LinkedList<>(issues);
    Collection<IssueMatcher> matcherCopy = new LinkedList<>(issueMatchers);

    performMatching(issueCopy, matcherCopy, messages);
    if (inverted) {
        if (issueCopy.isEmpty()) {
            explainIssues(issues, messages, inverted);
            return false;
        }
    } else {
        if (!issueCopy.isEmpty()) {
            explainIssues(issueCopy, messages, inverted);
            return false;
        }
    }
    return true;
}
项目:n4js    文件:IssueExpectations.java   
private void performMatching(Collection<Issue> issues, Collection<IssueMatcher> matchers, List<String> messages) {
    Iterator<Issue> issueIt = issues.iterator();
    while (issueIt.hasNext() && !matchers.isEmpty()) {
        Issue issue = issueIt.next();

        Iterator<IssueMatcher> matcherIt = matchers.iterator();
        while (matcherIt.hasNext()) {
            IssueMatcher matcher = matcherIt.next();
            if (matcher.matches(issue)) {
                issueIt.remove();
                matcherIt.remove();
                break;
            } else if (messages != null) {
                messages.addAll(matcher.explainMismatch(issue));
            }
        }
    }
}
项目:n4js    文件:StringPropertyMatcher.java   
@Override
protected String explainMismatch(Issue issue) {
    String actualValue = safeGetValue(getActualValue.apply(issue));
    switch (mode) {
    case StartsWith:
        return "'" + expectedPattern + "' is not a prefix of value '" + actualValue + "'";
    case EndsWith:
        return "'" + expectedPattern + "' is not a suffix of value '" + actualValue + "'";
    case Equals:
        return "Value '" + actualValue + "' is not equal to expected value'"
                + expectedPattern + "'";
    }

    // This should never happen lest we extended the enum without adding a case above!
    throw new IllegalStateException("Unknown string property matching mode: " + mode);
}
项目:n4js    文件:QuickFixXpectMethod.java   
/**
 * Example: {@code // XPECT quickFixList  at 'a.<|>method' --> 'import A','do other things' }
 *
 * @param expectation
 *            comma separated strings, which are proposed as quick fix
 * @param resource
 *            injected xtext-file
 * @param offset
 *            cursor position at '<|>'
 * @param checkType
 *            'display': verify list of provided proposals comparing their user-displayed strings.
 * @param selected
 *            which proposal to pick
 * @param mode
 *            modus of operation
 * @param offset2issue
 *            mapping of offset(!) to issues.
 * @throws Exception
 *             if failing
 */
@Xpect
@ParameterParser(syntax = "('at' (arg2=STRING (arg3=ID  (arg4=STRING)?  (arg5=ID)? )? )? )?")
@ConsumedIssues({ Severity.INFO, Severity.ERROR, Severity.WARNING })
public void quickFixList(
        @CommaSeparatedValuesExpectation(quoted = true, ordered = true) ICommaSeparatedValuesExpectation expectation, // arg0
        @ThisResource XtextResource resource, // arg1
        RegionWithCursor offset, // arg2
        String checkType, // arg3
        String selected, // arg4
        String mode, // arg5
        @IssuesByLine Multimap<Integer, Issue> offset2issue) throws Exception {

    List<IssueResolution> resolutions = collectAllResolutions(resource, offset, offset2issue);

    List<String> resolutionNames = Lists.newArrayList();
    for (IssueResolution resolution : resolutions) {
        resolutionNames.add(resolution.getLabel());
    }

    expectation.assertEquals(resolutionNames);
}
项目:n4js    文件:QuickFixXpectMethod.java   
/**
 * CollectAll resolutions under the cursor at offset.
 *
 */
List<IssueResolution> collectAllResolutions(XtextResource resource, RegionWithCursor offset,
        Multimap<Integer, Issue> offset2issue) {

    EObject script = resource.getContents().get(0);
    ICompositeNode scriptNode = NodeModelUtils.getNode(script);
    ILeafNode offsetNode = NodeModelUtils.findLeafNodeAtOffset(scriptNode, offset.getGlobalCursorOffset());
    int offStartLine = offsetNode.getTotalStartLine();
    List<Issue> allIssues = QuickFixTestHelper.extractAllIssuesInLine(offStartLine, offset2issue);

    List<IssueResolution> resolutions = Lists.newArrayList();

    for (Issue issue : allIssues) {
        if (issue.getLineNumber() == offsetNode.getStartLine()
                && issue.getLineNumber() <= offsetNode.getEndLine()) {
            Display.getDefault().syncExec(() -> resolutions.addAll(quickfixProvider.getResolutions(issue)));
        }
    }
    return resolutions;
}
项目:n4js    文件:XpectN4JSES5TranspilerHelper.java   
private boolean registerErrors(Resource dep, StringBuilder errorResult) {
    boolean hasErrors = false;
    List<Issue> issues = resourceValidator.validate(dep, CheckMode.ALL, CancelIndicator.NullImpl);
    List<Issue> errorIssues = new ArrayList<>();
    for (Issue issue : issues) {
        if (Severity.ERROR == issue.getSeverity()) {
            errorIssues.add(issue);
        }
    }
    hasErrors = !errorIssues.isEmpty();
    if (hasErrors) {
        errorResult.append("Couldn't compile resource " + dep.getURI() + " because it contains errors: ");
        for (Issue errorIssue : errorIssues) {
            errorResult
                    .append(nl + errorIssue.getMessage() + " at line " + errorIssue.getLineNumber());
        }
    }
    return hasErrors;
}
项目:n4js    文件:ResourceUIValidatorExtension.java   
private void addMarkers(IFile file, Resource resource, CheckMode mode, IProgressMonitor monitor)
        throws OperationCanceledException {
    try {
        List<Issue> list = getValidator(resource).validate(resource, mode, getCancelIndicator(monitor));
        if (monitor.isCanceled()) {
            throw new OperationCanceledException();
        }
        deleteMarkers(file, mode, monitor);
        if (monitor.isCanceled()) {
            throw new OperationCanceledException();
        }
        createMarkers(file, list, getMarkerCreator(resource), getMarkerTypeProvider(resource));
    } catch (OperationCanceledError error) {
        throw error.getWrapped();
    } catch (CoreException e) {
        LOGGER.error(e.getMessage(), e);
    }
}
项目:n4js    文件:N4JSResourceValidator.java   
/**
 * Don't validate the inferred module since all validation information should be available on the AST elements.
 */
@Override
protected void validate(Resource resource, CheckMode mode, CancelIndicator cancelIndicator,
        IAcceptor<Issue> acceptor) {
    operationCanceledManager.checkCanceled(cancelIndicator);
    if (n4jsCore.isNoValidate(resource.getURI())) {
        return;
    }
    List<EObject> contents = resource.getContents();
    if (!contents.isEmpty()) {
        EObject firstElement = contents.get(0);
        // // Mark the scoping as sealed. (No other usage-flags should be set for import-declarations.)
        // if (firstElement instanceof Script) {
        // ((Script) firstElement).setFlaggedBound(true);
        // }
        validate(resource, firstElement, mode, cancelIndicator, acceptor);

        // UtilN4.takeSnapshotInGraphView("post validation", resource);
    }
}
项目:n4js    文件:N4JSResourceValidator.java   
private Issue createPostProcessingFailedError(N4JSResource res, Throwable th) {
    final String thKind = th instanceof Error ? "error" : (th instanceof Exception ? "exception" : "throwable");
    final String thName = th.getClass().getSimpleName();
    final String trace = "\n" + Stream.of(th.getStackTrace())
            .map(ste -> ste.toString())
            .collect(Collectors.joining("\n")); // cannot add indentation, because Xtext would reformat the message
    final String msg = IssueCodes.getMessageForPOST_PROCESSING_FAILED(thKind, thName, th.getMessage() + trace);
    final Issue.IssueImpl issue = new Issue.IssueImpl();
    issue.setCode(IssueCodes.POST_PROCESSING_FAILED);
    issue.setSeverity(IssueCodes.getDefaultSeverity(IssueCodes.POST_PROCESSING_FAILED));
    issue.setMessage(msg);
    issue.setUriToProblem(EcoreUtil.getURI(res.getScript()));
    issue.setType(CheckType.FAST); // using CheckType.FAST is important to get proper marker update behavior in ...
    // ... the editor between persisted and dirty states!
    issue.setOffset(0);
    issue.setLength(0);
    issue.setLineNumber(0);
    issue.setColumn(0);
    return issue;
}
项目:DocIT    文件:Main.java   
protected void runGenerator(String string) {
    // load the resource
    ResourceSet set = resourceSetProvider.get();
    Resource resource = set.getResource(URI.createURI(string), true);

    // validate the resource
    List<Issue> list = validator.validate(resource, CheckMode.ALL, CancelIndicator.NullImpl);
    if (!list.isEmpty()) {
        for (Issue issue : list) {
            System.err.println(issue);
        }
        return;
    }

    // configure and start the generator
    fileAccess.setOutputPath("src-gen/");
    generator.doGenerate(resource, fileAccess);

    System.out.println("Code generation finished.");
}
项目:jason-eclipse-plugin    文件:Main.java   
protected void runGenerator(String string) {
    // load the resource
    ResourceSet set = resourceSetProvider.get();
    Resource resource = set.getResource(URI.createURI(string), true);

    // validate the resource
    List<Issue> list = validator.validate(resource, CheckMode.ALL, CancelIndicator.NullImpl);
    if (!list.isEmpty()) {
        for (Issue issue : list) {
            System.err.println(issue);
        }
        return;
    }

    // configure and start the generator
    fileAccess.setOutputPath("src-gen/");
    generator.doGenerate(resource, fileAccess);

    System.out.println("Code generation finished.");
}
项目:xtext-extras    文件:CompilationTestHelper.java   
protected void doValidation() {
    if (allErrorsAndWarnings == null) {
        doLinking();
        allErrorsAndWarnings = newArrayList();
        // validation
        for (Resource resource : sources) {
            if (resource instanceof XtextResource) {
                XtextResource xtextResource = (XtextResource) resource;
                List<Issue> issues = xtextResource.getResourceServiceProvider().getResourceValidator().validate(xtextResource, checkMode, CancelIndicator.NullImpl);
                for (Issue issue : issues) {
                    allErrorsAndWarnings.add(issue);
                }
            }
        }
    }
}
项目:xtext-extras    文件:ElementIssueProvider.java   
public void attachData(Resource resource) {
    if (findDataAdapter(resource) != null) {
        return;
    }
    List<Issue> issues = collectIssues(resource);
    Data adapter = new Data();
    for (Issue issue : issues) {
        URI uriToProblem = issue.getUriToProblem();
        if (uriToProblem != null && uriToProblem.trimFragment().equals(resource.getURI())) {
            EObject erroneousElement = resource.getEObject(uriToProblem.fragment());
            adapter.addIssue(erroneousElement, issue);
            for(EObject jvmElement: associations.getJvmElements(erroneousElement)) {
                adapter.addIssue(jvmElement, issue);
            }
        }
    }
    resource.eAdapters().add(adapter);
}
项目:xtext-extras    文件:ElementIssueProvider.java   
protected void synthesizeIssuesForFollowUpErrors(Resource resource, List<Issue> result) {
    List<EObject> contents = resource.getContents();
    if (!contents.isEmpty()) {
        IResolvedTypes resolvedTypes = typeResolver.resolveTypes(contents.get(0));
        for(ILinkingCandidate linkingCandidate: resolvedTypes.getFollowUpErrors()) {
            XExpression expression = linkingCandidate.getExpression();
            IssueImpl issue = new Issue.IssueImpl();
            issue.setUriToProblem(EcoreUtil.getURI(linkingCandidate.getExpression()));
            if (expression instanceof XAbstractFeatureCall)
                issue.setMessage(((XAbstractFeatureCall) expression).getConcreteSyntaxFeatureName() + " cannot be resolved");
            else {
                List<INode> nodes = NodeModelUtils.findNodesForFeature(expression, XbasePackage.Literals.XCONSTRUCTOR_CALL__CONSTRUCTOR);
                if (nodes.size() >= 1) {
                    issue.setMessage(nodes.get(0).getText() + " cannot be resolved");
                }
            }
            result.add(issue);
        }
    }
}
项目:xtext-core    文件:Validator.java   
protected void appendMessages(StringBuilder result, MWEDiagnostic[] diagnostics) {
    Multimap<URI, MWEDiagnostic> issuesPerURI = groupByURI(diagnostics);
    boolean first = true;
    for (URI uri : issuesPerURI.keySet()) {
        if (!first)
            result.append('\n');
        first = false;
        if (uri != null) {
            result.append('\t').append(uri.lastSegment()).append(" - ");
            if (uri.isFile())
                result.append(uri.toFileString());
            else
                result.append(uri);
        }
        for (MWEDiagnostic diagnostic : issuesPerURI.get(uri)) {
            Issue issue = (Issue) diagnostic.getElement();
            result.append("\n\t\t").append(issue.getLineNumber()).append(": ").append(diagnostic.getMessage());
        }
    }
}
项目:dsl-devkit    文件:CheckQuickfixProvider.java   
/**
 * Fixes an illegally set default severity. The default severity must be within given severity range.
 *
 * @param issue
 *          the issue
 * @param acceptor
 *          the acceptor
 */
@Fix(IssueCodes.DEFAULT_SEVERITY_NOT_IN_RANGE)
public void fixIllegalDefaultSeverity(final Issue issue, final IssueResolutionAcceptor acceptor) {
  if (issue.getData() != null) {
    for (final String severityProposal : issue.getData()) {
      final String label = NLS.bind(Messages.CheckQuickfixProvider_DEFAULT_SEVERITY_FIX_LABEL, severityProposal);
      final String descn = NLS.bind(Messages.CheckQuickfixProvider_DEFAULT_SEVERITY_FIX_DESCN, severityProposal);

      acceptor.accept(issue, label, descn, NO_IMAGE, new IModification() {
        @Override
        public void apply(final IModificationContext context) throws BadLocationException {
          IXtextDocument xtextDocument = context.getXtextDocument();
          xtextDocument.replace(issue.getOffset(), issue.getLength(), severityProposal);
        }
      });
    }
  }
}
项目:chariot    文件:Main.java   
protected void runGenerator(String string) {
    // load the resource
    ResourceSet set = resourceSetProvider.get();
    Resource resource = set.getResource(URI.createURI(string), true);

    // validate the resource
    List<Issue> list = validator.validate(resource, CheckMode.ALL, CancelIndicator.NullImpl);
    if (!list.isEmpty()) {
        for (Issue issue : list) {
            System.err.println(issue);
        }
        return;
    }

    // configure and start the generator
    fileAccess.setOutputPath("src-gen/");
    generator.doGenerate(resource, fileAccess);

    System.out.println("Code generation finished.");
}
项目:xtext-core    文件:MultiProjectTest.java   
@Before
public void setup() {
  ServerModule _serverModule = new ServerModule();
  final Injector injector = Guice.createInjector(Modules2.mixin(_serverModule, new AbstractModule() {
    @Override
    protected void configure() {
      this.<IWorkspaceConfigFactory>bind(IWorkspaceConfigFactory.class).to(MultiProjectWorkspaceConfigFactory.class);
    }
  }));
  injector.injectMembers(this);
  final File workspaceRoot = this.getRoot("test-data");
  File _file = new File(workspaceRoot, "test-project0");
  this.project0 = _file;
  File _file_1 = new File(workspaceRoot, "test-project1");
  this.project1 = _file_1;
  this.project0.mkdir();
  this.project1.mkdir();
  final Procedure2<URI, Iterable<Issue>> _function = (URI $0, Iterable<Issue> $1) -> {
    this.diagnostics.put($0, IterableExtensions.<Issue>toList($1));
  };
  this.workspaceManager.initialize(URI.createFileURI(workspaceRoot.getAbsolutePath()), _function, null);
}
项目:xtext-core    文件:WorkspaceManagerTest.java   
@Before
public void setup() {
  try {
    ServerModule _serverModule = new ServerModule();
    final Injector injector = Guice.createInjector(_serverModule);
    injector.injectMembers(this);
    File _file = new File("./test-data/test-project");
    this.root = _file;
    boolean _mkdirs = this.root.mkdirs();
    boolean _not = (!_mkdirs);
    if (_not) {
      Files.cleanFolder(this.root, null, true, false);
    }
    this.root.deleteOnExit();
    final Procedure2<URI, Iterable<Issue>> _function = (URI $0, Iterable<Issue> $1) -> {
      this.diagnostics.put($0, IterableExtensions.<Issue>toList($1));
    };
    this.workspaceManger.initialize(this.uriExtensions.withEmptyAuthority(URI.createFileURI(this.root.getAbsolutePath())), _function, null);
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
项目:xtext-core    文件:ValidationTestHelper.java   
public void assertNoIssue(final Resource resource, final EClass objectType, final String issuecode) {
    final List<Issue> validate = validate(resource);
    Iterable<Issue> issues = filter(validate, new Predicate<Issue>() {
        @Override
        public boolean apply(Issue input) {
            if (issuecode.equals(input.getCode())) {
                EObject object = resource.getEObject(input.getUriToProblem().fragment());
                if (objectType.isInstance(object)) {
                    return true;
                }
            }
            return false;
        }
    });
    if (!isEmpty(issues)) {
        fail("Expected no error '" + issuecode + "' but got " + getIssuesAsString(resource, issues, new StringBuilder()));
    }
}
项目:xtext-core    文件:ValidationTestHelper.java   
protected Iterable<Issue> doMatchIssues(final Resource resource, final EClass objectType, final String code,
        final int offset, final int length, final Severity severity, final List<Issue> validate,
        final String... messageParts) {
    return Iterables.filter(validate, new Predicate<Issue>() {
        @Override
        public boolean apply(Issue input) {
            if (Strings.equal(input.getCode(), code) && input.getSeverity()==severity) {
                if ((offset < 0 || offset == input.getOffset()) && (length < 0 || length == input.getLength())) {
                    EObject object = resource.getResourceSet().getEObject(input.getUriToProblem(), true);
                    if (objectType.isInstance(object)) {
                        for (String messagePart : messageParts) {
                            if(!isValidationMessagePartMatches(input.getMessage(), messagePart)){
                                return false;
                            }
                        }
                        return true;
                    }
                }
            }
            return false;
        }
    });
}
项目:xtext-core    文件:ValidationTestHelper.java   
protected StringBuilder doGetIssuesAsString(Resource resource, final Iterable<Issue> issues, StringBuilder result) {
    for (Issue issue : issues) {
        URI uri = issue.getUriToProblem();
        result.append(issue.getSeverity());
        result.append(" (");
        result.append(issue.getCode());
        result.append(") '");
        result.append(issue.getMessage());
        result.append("'");
        if (uri != null) {
            EObject eObject = resource.getResourceSet().getEObject(uri, true);
            result.append(" on ");
            result.append(eObject.eClass().getName());
        }
        result.append(", offset " + issue.getOffset() + ", length " + issue.getLength());
        result.append("\n");
    }
    return result;
}
项目:dsl-devkit    文件:ValidMarkerUpdateJob.java   
/**
 * Validate the given resource and create the corresponding markers. The CheckMode is a constant calculated from the constructor
 * parameters.
 *
 * @param resourceValidator
 *          the resource validator (not null)
 * @param file
 *          the EFS file (not null)
 * @param resource
 *          the EMF resource (not null)
 * @param monitor
 *          the monitor (not null)
 */
protected void validate(final IResourceValidator resourceValidator, final IFile file, final Resource resource, final IProgressMonitor monitor) {
  try {
    monitor.subTask("validating " + file.getName()); //$NON-NLS-1$

    final List<Issue> list = resourceValidator.validate(resource, checkMode, getCancelIndicator(monitor));
    if (list != null) {
      // resourceValidator.validate returns null if canceled (and not an empty list)
      file.deleteMarkers(MarkerTypes.FAST_VALIDATION, true, IResource.DEPTH_ZERO);
      file.deleteMarkers(MarkerTypes.NORMAL_VALIDATION, true, IResource.DEPTH_ZERO);
      if (performExpensiveValidation) {
        file.deleteMarkers(MarkerTypes.EXPENSIVE_VALIDATION, true, IResource.DEPTH_ZERO);
      }
      for (final Issue issue : list) {
        markerCreator.createMarker(issue, file, MarkerTypes.forCheckType(issue.getType()));
      }
    }
  } catch (final CoreException e) {
    LOGGER.error(e.getMessage(), e);
  } finally {
    monitor.worked(1);
  }
}
项目:xtext-core    文件:XtextValidationTest.java   
@Test public void testRuleCalledSuper() throws Exception {
    XtextResource resource = getResourceFromString(
            "grammar com.acme.Bar with org.eclipse.xtext.common.Terminals\n" +
            "generate metamodel 'myURI'\n" +
            "Model: super=super;\n" + 
            "super: name=ID;");

    IResourceValidator validator = get(IResourceValidator.class);
    List<Issue> issues = validator.validate(resource, CheckMode.FAST_ONLY, CancelIndicator.NullImpl);
    assertEquals(issues.toString(), 1, issues.size());
    assertEquals("Discouraged rule name 'super'", issues.get(0).getMessage());
    Grammar grammar = (Grammar) resource.getContents().get(0);
    AbstractRule model = grammar.getRules().get(0);
    Assignment assignment = (Assignment) model.getAlternatives();
    RuleCall ruleCall = (RuleCall) assignment.getTerminal();
    assertSame(grammar.getRules().get(1), ruleCall.getRule());
}
项目:dsl-devkit    文件:FormatQuickfixProvider.java   
/**
 * Semantic quickfix removing the override flag for a rule.
 *
 * @param issue
 *          the issue
 * @param acceptor
 *          the acceptor
 */
@Fix(FormatJavaValidator.OVERRIDE_ILLEGAL_CODE)
public void removeOverride(final Issue issue, final IssueResolutionAcceptor acceptor) {
  acceptor.accept(issue, "Remove override", "Remove override.", null, new IModification() {
    @Override
    public void apply(final IModificationContext context) throws BadLocationException {
      context.getXtextDocument().modify(new IUnitOfWork<Void, XtextResource>() {
        @Override
        public java.lang.Void exec(final XtextResource state) {
          Rule rule = (Rule) state.getEObject(issue.getUriToProblem().fragment());
          rule.setOverride(false);
          return null;
        }
      });
    }
  });
}
项目:dsl-devkit    文件:CheckConfigurationStoreService.java   
/**
 * Sets the project if an associated instance can be found for given context object.
 * <p>
 * This is the default implementation. Only platform URI-based schemas are supported. Other implementations may overwrite {@link #getProject()}.
 * </p>
 *
 * @param context
 *          the context object, potentially contained by an IProject
 */
protected void setProject(final Object context) {
  if (context instanceof IProject) {
    this.project = (IProject) context;
  } else if (context instanceof IFile) {
    this.project = ((IFile) context).getProject();
  } else {
    URI uri = null;
    if (context instanceof EObject && ((EObject) context).eResource() != null) {
      uri = ((EObject) context).eResource().getURI();
    }
    if (context instanceof Issue) {
      uri = ((Issue) context).getUriToProblem();
    }
    if (uri != null && uri.isPlatform()) {
      final IFile file = (IFile) ResourcesPlugin.getWorkspace().getRoot().findMember(uri.toPlatformString(true));
      this.project = file.getProject();
    }
  }
}
项目:dsl-devkit    文件:CheckQuickfixProvider.java   
/**
 * Removes the guard statement occurring at offending position.
 *
 * @param issue
 *          the issue
 * @param acceptor
 *          the acceptor
 */
@Fix(IssueCodes.GUARDS_COME_FIRST)
@SuppressWarnings("unchecked")
public void removeGuardStatement(final Issue issue, final IssueResolutionAcceptor acceptor) {
  acceptor.accept(issue, Messages.CheckQuickfixProvider_REMOVE_GUARD_LABEL, Messages.CheckQuickfixProvider_REMOVE_GUARD_DESCN, NO_IMAGE, new ISemanticModification() {
    @Override
    public void apply(final EObject element, final IModificationContext context) {
      final XGuardExpression guard = EcoreUtil2.getContainerOfType(element, XGuardExpression.class);
      if (guard != null && guard.eContainingFeature().isMany()) {
        EList<? extends EObject> holder = (EList<? extends EObject>) guard.eContainer().eGet(guard.eContainingFeature());
        if (holder != null && holder.contains(guard)) {
          holder.remove(guard);
        }
      }
    }
  });
}
项目:dsl-devkit    文件:ModelValidator.java   
/**
 * Log issue.
 *
 * @param resource
 *          the resource
 * @param issue
 *          the issue
 * @param logger
 *          the logger
 */
private void logIssue(final Resource resource, final Issue issue, final Logger logger) {
  final String message = NLS.bind(MESSAGE_TEMPLATE, new Object[] {resource.getURI().lastSegment(), issue.getLineNumber(), issue.getMessage()});
  final Severity severity = issue.getSeverity();
  switch (severity) {
  case ERROR:
    logger.error(message);
    break;
  case WARNING:
    logger.warn(message);
    break;
  case INFO:
    if (logger.isInfoEnabled()) {
      logger.info(message);
    }
    break;

  default:
    break;
  }
}
项目:dsl-devkit    文件:CheckQuickfixProvider.java   
/**
 * Fixes the severity range order by setting the lower severity level kind first and the severity of higher severity level last.
 *
 * @param issue
 *          the issue
 * @param acceptor
 *          the acceptor
 */
@Fix(IssueCodes.ILLEGAL_SEVERITY_RANGE_ORDER)
public void fixSeverityRangeOrder(final Issue issue, final IssueResolutionAcceptor acceptor) {
  acceptor.accept(issue, Messages.CheckQuickfixProvider_FIX_SEVERITY_RANGE_ORDER_LABEL, Messages.CheckQuickfixProvider_FIX_SEVERITY_RANGE_ORDER_DESCN, NO_IMAGE, new ISemanticModification() {
    @Override
    public void apply(final EObject element, final IModificationContext context) {
      final Check check = EcoreUtil2.getContainerOfType(element, Check.class);
      if (check != null && check.getSeverityRange() != null) {
        final SeverityRange range = check.getSeverityRange();
        SeverityKind oldMinSeverity = range.getMinSeverity();
        range.setMinSeverity(range.getMaxSeverity());
        range.setMaxSeverity(oldMinSeverity);
      }
    }
  });
}
项目:n4js    文件:AbstractBuilderParticipantTest.java   
/**
 * Returns validation errors in given Xtext editor.
 */
protected List<Issue> getEditorValidationErrors(XtextEditor editor) {
    return editor.getDocument().readOnly(new IUnitOfWork<List<Issue>, XtextResource>() {
        @Override
        public List<Issue> exec(XtextResource state) throws Exception {
            final IResourceValidator validator = state.getResourceServiceProvider().getResourceValidator();
            return validator.validate(state, CheckMode.ALL, CancelIndicator.NullImpl);
        }
    });
}
项目:n4js    文件:N4JSValidationTestHelper.java   
/**
 * Asserts the given model to not have any issues except the ones specified by the exception issue codes parameter.
 *
 * @param model
 *            The model
 * @param exceptionIssueCodes
 *            Issue codes which should be ignored
 */
public void assertNoIssuesExcept(EObject model, String... exceptionIssueCodes) {
    Resource resource = model.eResource();
    final List<Issue> issues = validate(resource);

    if (removeIssuesWithCode(issues, exceptionIssueCodes).size() > 0) {
        fail("Expected no issues, but got :" + getIssuesAsString(resource, issues, new StringBuilder()));
    }
}
项目:n4js    文件:N4JSInjectorProviderWithIssueSuppression.java   
@Override
public void convertValidatorDiagnostic(Diagnostic diagnostic, IAcceptor<Issue> acceptor) {
    super.convertValidatorDiagnostic(diagnostic, new IAcceptor<Issue>() {
        @Override
        public void accept(Issue t) {
            if (!N4JSLanguageConstants.DEFAULT_SUPPRESSED_ISSUE_CODES_FOR_TESTS.contains(t.getCode())) {
                acceptor.accept(t);
            }
        }
    });
}
项目:n4js    文件:IssueMatcher.java   
/**
 * Matches this issue matcher against the given issue.
 *
 * @param issue
 *            the issue to match against
 * @return <code>true</code> if the expectations in this matcher match the given issue and <code>false</code>
 *         otherwise
 */
public boolean matches(Issue issue) {
    Objects.requireNonNull(issue);
    for (IssuePropertyMatcher propertyMatcher : propertyMatchers) {
        if (!propertyMatcher.matches(issue))
            return false;
    }
    return true;
}