org.eclipse.xtext.ui.MarkerTypes Java Examples

The following examples show how to use org.eclipse.xtext.ui.MarkerTypes. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ProjectTestsUtils.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Asserts that the given resource (usually an N4JS file) contains issues with the given messages and no other
 * issues. Each message given should be prefixed with the line numer where the issues occurs, e.g.:
 *
 * <pre>
 * line 5: Couldn't resolve reference to identifiable element 'unknown'.
 * </pre>
 *
 * Column information is not provided, so this method is not intended for several issues within a single line.
 *
 * @param msg
 *            human-readable, informative message prepended to the standard message in case of assertion failure.
 * @param resource
 *            resource to be validated.
 * @param expectedMessages
 *            expected issues messages to check or empty array to assert no issues.
 * @throws CoreException
 *             in case of mishap.
 */
public static void assertIssues(String msg, final IResource resource, String... expectedMessages)
		throws CoreException {
	waitForAutoBuild();

	final IMarker[] markers = resource.findMarkers(MarkerTypes.ANY_VALIDATION, true, IResource.DEPTH_INFINITE);
	final String[] actualMessages = new String[markers.length];
	for (int i = 0; i < markers.length; i++) {
		final IMarker m = markers[i];
		actualMessages[i] = "line " + MarkerUtilities.getLineNumber(m) + ": " + m.getAttribute(IMarker.MESSAGE);
	}
	Set<String> actual = new TreeSet<>(Arrays.asList(actualMessages));
	Set<String> expected = new TreeSet<>(Arrays.asList(expectedMessages));

	if (!actual.equals(expected)) {
		StringBuilder message = new StringBuilder(msg != null ? msg : "");
		message.append("\nexpected:\n");
		message.append(expectedMessages.length > 0 ? Joiner.on('\n').join(expectedMessages) : "<none>");
		message.append("\nactual:\n");
		message.append(actualMessages.length > 0 ? Joiner.on('\n').join(actualMessages) : "<none>");
		Assert.fail(message.toString());
	}
}
 
Example #2
Source File: ListBasePluginTest.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings("javadoc")
@Test
public void testListBase() throws Exception {
	IProject project = ProjectTestsUtils.importProject(new File("probands"), new N4JSProjectName("ListBase"));
	IResourcesSetupUtil.waitForBuild();
	IFile underscore_js = project.getFile("src/underscore/underscore.n4js");
	assertTrue(underscore_js.exists());
	assertMarkers(underscore_js + " should have no errors", underscore_js, 0);

	IFile listbase_js = project.getFile("src/n4/lang/ListBase.n4js");

	assertTrue(listbase_js.exists());

	final Collection<IMarker> allMarkers = newHashSet(listbase_js.findMarkers(MarkerTypes.ANY_VALIDATION, true,
			IResource.DEPTH_INFINITE));
	assertTrue(format(EXPECTED_NUMBER_OF_ISSUE_TEMPLATE, allMarkers.size()),
			NUMBER_OF_EXPECTED_ISSUES == allMarkers.size());

	long unexpectedMarkerCount = allMarkers.stream()
			.filter(EXPECTED_VALIDATION_PREDICATE.negate())
			.count();

	assertTrue("Unexpected validation issues were found. " + toString(allMarkers), unexpectedMarkerCount == 0);
}
 
Example #3
Source File: ValidMarkerUpdateJob.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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);
  }
}
 
Example #4
Source File: ProblemHoverTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void setUp() throws Exception {
	super.setUp();
	modelAsText = "stuff mystuff\nstuff yourstuff refs _mystuff stuff hisstuff refs _yourstuff// Comment";
	IFile file = IResourcesSetupUtil.createFile("test/test.testlanguage", modelAsText);
	editor = openEditor(file);
	document = editor.getDocument();
	hover = TestsActivator.getInstance().getInjector(getEditorId()).getInstance(ProblemAnnotationHover.class);
	hover.setSourceViewer(editor.getInternalSourceViewer());
	List<Issue> issues = document.readOnly(new IUnitOfWork<List<Issue>, XtextResource>() {
		@Override
		public List<Issue> exec(XtextResource state) throws Exception {
			return state.getResourceServiceProvider().getResourceValidator().validate(state, CheckMode.ALL, null);
		}	
	});
	MarkerCreator markerCreator =  TestsActivator.getInstance().getInjector(getEditorId()).getInstance(MarkerCreator.class);
	for (Issue issue : issues) {
		markerCreator.createMarker(issue, file, MarkerTypes.forCheckType(issue.getType()));
	}
}
 
Example #5
Source File: AbstractProblemHoverTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void setUp() throws Exception {
	super.setUp();
	modelAsText = "stuff mystuff\nstuff yourstuff refs _mystuff// Comment";
	file = IResourcesSetupUtil.createFile("test/test.testlanguage", modelAsText);
	editor = openEditor(file);
	document = editor.getDocument();
	hover = TestsActivator.getInstance().getInjector(getEditorId()).getInstance(MockHover.class);
	hover.setSourceViewer(editor.getInternalSourceViewer());
	List<Issue> issues = document.readOnly(new IUnitOfWork<List<Issue>, XtextResource>() {
		@Override
		public List<Issue> exec(XtextResource state) throws Exception {
			return state.getResourceServiceProvider().getResourceValidator().validate(state, CheckMode.ALL, null);
		}	
	});
	MarkerCreator markerCreator =  TestsActivator.getInstance().getInjector(getEditorId()).getInstance(MarkerCreator.class);
	for (Issue issue : issues) {
		markerCreator.createMarker(issue, file, MarkerTypes.forCheckType(issue.getType()));
	}
}
 
Example #6
Source File: XtextNature.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void deconfigure() throws CoreException {
	IProjectDescription description = getProject().getDescription();
	ICommand[] commands = description.getBuildSpec();
	for (int i = 0; i < commands.length; ++i) {
		if (commands[i].getBuilderName().equals(XtextBuilder.BUILDER_ID)) {
			ICommand[] newCommands = new ICommand[commands.length - 1];
			System.arraycopy(commands, 0, newCommands, 0, i);
			System.arraycopy(commands, i + 1, newCommands, i,
					commands.length - i - 1);
			description.setBuildSpec(newCommands);
			project.setDescription(description, null);			
			project.deleteMarkers(MarkerTypes.ANY_VALIDATION, true, IResource.DEPTH_INFINITE);
			return;
		}
	}
}
 
Example #7
Source File: AbstractProblemHoverTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testAnnotationOnMultipleLines() throws Exception {
	IMarker warning = file.createMarker(MarkerTypes.NORMAL_VALIDATION);
	warning.setAttribute(IMarker.LOCATION, "line: 1 " + file.getFullPath().toString());
	warning.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
	warning.setAttribute(IMarker.CHAR_START, 0);
	warning.setAttribute(IMarker.CHAR_END, 43);
	warning.setAttribute(IMarker.LINE_NUMBER, 1);
	warning.setAttribute(IMarker.MESSAGE, "Foo");
	
	List<Annotation> annotations = hover.getAnnotations(1, 40);
	assertEquals(2, annotations.size());
	// The error is on the same line as the requested position, so it should be returned first
	assertEquals("org.eclipse.xtext.ui.editor.error", annotations.get(0).getType());
	assertEquals("org.eclipse.xtext.ui.editor.warning", annotations.get(1).getType());
	
	warning.delete();
}
 
Example #8
Source File: LanguageAwareMarkerTypeProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected void setMarkerTypes(String baseName) {
	MarkerTypesModel markerTypesModel = MarkerTypesModel.getInstance();
	String markerType = baseName + ".check.fast";
	if (markerTypesModel.getType(markerType) == null) {
		markerType = MarkerTypes.FAST_VALIDATION;
	}
	fastValidationMarker = markerType;
	markerType = baseName + ".check.normal";
	if (markerTypesModel.getType(markerType) == null) {
		markerType = MarkerTypes.NORMAL_VALIDATION;
	}
	normalValidationMarker = markerType;
	markerType = baseName + ".check.expensive";
	if (markerTypesModel.getType(markerType) == null) {
		markerType = MarkerTypes.EXPENSIVE_VALIDATION;
	}
	expensiveValidationMarker = markerType;
}
 
Example #9
Source File: AbstractMultiQuickfixTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected IMarker[] getMarkers(IFile file) {
	IResourcesSetupUtil.waitForBuild();
	try {
		return file.findMarkers(MarkerTypes.FAST_VALIDATION, true, IResource.DEPTH_INFINITE);
	} catch (CoreException e) {
		Exceptions.sneakyThrow(e);
		return null;
	}
}
 
Example #10
Source File: IssueUtil.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @deprecated As we are using IMarker.getAttributes() in {@link #createIssue(IMarker)}, we do not call this method any more
 * @since 2.3
 */
@Deprecated
protected CheckType getCheckType(IMarker marker) {
	String markerType = MarkerUtilities.getMarkerType(marker);
	if (markerTypeProvider != null)
		return markerTypeProvider.getCheckType(markerType);
	return MarkerTypes.toCheckType(markerType);
}
 
Example #11
Source File: AnnotationIssueProcessor.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void updateMarkerAnnotations(IProgressMonitor monitor) {
	if (monitor.isCanceled()) {
		return;
	}

	Iterator<MarkerAnnotation> annotationIterator = Iterators.filter(annotationModel.getAnnotationIterator(),
			MarkerAnnotation.class);

	// every markerAnnotation produced by fast validation can be marked as deleted.
	// If its predicate still holds, the validation annotation will be covered anyway.
	while (annotationIterator.hasNext() && !monitor.isCanceled()) {
		final MarkerAnnotation annotation = annotationIterator.next();
		if (!annotation.isMarkedDeleted())
			try {
				if (isRelevantAnnotationType(annotation.getType())) {
					boolean markAsDeleted = annotation.getMarker().isSubtypeOf(MarkerTypes.FAST_VALIDATION);
					if (markAsDeleted) {
						annotation.markDeleted(true);
						queueOrFireAnnotationChangedEvent(annotation);
					}
				}
			} catch (CoreException e) {
				// marker type cannot be resolved - keep state of annotation
			}
	}
	fireQueuedEvents();
}
 
Example #12
Source File: MarkerResolutionGenerator.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public IMarkerResolution[] getResolutions(IMarker marker) {
	final IMarkerResolution[] emptyResult = new IMarkerResolution[0];
	try {
		if (!marker.isSubtypeOf(MarkerTypes.ANY_VALIDATION))
			return emptyResult;
	} catch (CoreException e) {
		return emptyResult;
	}
	if (!languageResourceHelper.isLanguageResource(marker.getResource())) {
		return emptyResult;
	}
	XtextEditor editor = findEditor(marker.getResource());
	if (editor != null) {
		IAnnotationModel annotationModel = editor.getDocumentProvider().getAnnotationModel(editor.getEditorInput());
		if (annotationModel != null && !isMarkerStillValid(marker, annotationModel))
			return emptyResult;
	}
	Issue issue = getIssueUtil().createIssue(marker);
	if (issue == null)
		return emptyResult;

	List<IssueResolution> resolutions = getResolutionProvider().getResolutions(issue);
	List<IMarkerResolution> result = Lists.newArrayList();
	List<IssueResolution> remaining = Lists.newArrayList();
	for (IssueResolution resolution : resolutions) {
		if (resolution.getModification() instanceof IBatchableModification) {
			result.add(adapterFactory.create(marker, resolution));
		} else if (resolution.getModification() instanceof ITextualMultiModification) {
			result.add(textualMultiModificationAdapterFactory.create(marker, resolution));
		} else {
			remaining.add(resolution);
		}
	}
	result.addAll(Lists.newArrayList(getAdaptedResolutions(remaining)));
	return result.toArray(new IMarkerResolution[result.size()]);
}
 
Example #13
Source File: DerivedResourceMarkerCopier.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @return <code>true</code> if srcFile contains none-derived problem marker >= <code>maxSeverity</code>
 */
private boolean hasPlainXtextProblemMarker(IFile srcFile, int maxSeverity) throws CoreException {
	for (IMarker iMarker : srcFile.findMarkers(MarkerTypes.ANY_VALIDATION, true, IResource.DEPTH_ZERO)) {
		if (MarkerUtilities.getSeverity(iMarker) >= maxSeverity && iMarker.getAttribute(COPIED_FROM_FILE) == null) {
			return true;
		}
	}
	return false;
}
 
Example #14
Source File: DerivedResourceMarkerCopier.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private void cleanUpCreatedMarkers(IFile javaFile, IResource srcFile) throws CoreException {
	for (IMarker iMarker : srcFile.findMarkers(MarkerTypes.ANY_VALIDATION, true, IResource.DEPTH_ZERO)) {
		if (javaFile.getFullPath().toString().equals(iMarker.getAttribute(COPIED_FROM_FILE, ""))) {
			iMarker.delete();
		}
	}
}
 
Example #15
Source File: ProjectTestsUtils.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Asserts that there are no errors. However, warnings may still exist.
 */
public static void assertNoErrors() throws CoreException {
	waitForAutoBuild();

	IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
	final IMarker[] markers = root.findMarkers(MarkerTypes.ANY_VALIDATION, true, IResource.DEPTH_INFINITE);
	for (int i = 0; i < markers.length; i++) {
		IMarker m = markers[i];
		int severity = m.getAttribute(IMarker.SEVERITY, -1);
		assertNotEquals("Expected no errors but found:\n" + m.toString(), IMarker.SEVERITY_ERROR, severity);
	}
}
 
Example #16
Source File: WorkbenchResolutionAdaptorRunTest.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
private void mockMarkerResource(final URI uri) throws CoreException {
  // Resource is a file and so gets processed
  when(mockMarker.getResource()).thenReturn(mockFile);
  when(mockFile.getName()).thenReturn(uri.lastSegment());
  when(mockFile.findMarkers(anyString(), anyBoolean(), anyInt())).thenReturn(new IMarker[] {});
  when(mockMarker.getAttribute(eq(Issue.URI_KEY), anyString())).thenReturn(uri.toString());
  when(mockMarker.isSubtypeOf(eq(MarkerTypes.ANY_VALIDATION))).thenReturn(true);
  when(mockStorage2UriMapper.getUri(eq(mockFile))).thenReturn(uri);
  @SuppressWarnings("unchecked")
  Iterable<Pair<IStorage, IProject>> storages = Lists.newArrayList(Tuples.create((IStorage) mockFile, mock(IProject.class)));
  when(mockStorage2UriMapper.getStorages(eq(uri))).thenReturn(storages);
  when(mockLanguageResourceHelper.isLanguageResource(eq(mockFile))).thenReturn(true);
}
 
Example #17
Source File: CheckMarkerUpdateJob.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates the marker on a given file based on the collection of issues.
 *
 * @param markerCreator
 *          the marker creator, may be {@code null}
 * @param file
 *          the EFS file, must not be {@code null}
 * @param issues
 *          the collection of issues, must not be {@code null}
 * @throws CoreException
 */
private void createMarkers(final MarkerCreator markerCreator, final IFile file, final Collection<Issue> issues) throws CoreException {
  file.deleteMarkers(MarkerTypes.FAST_VALIDATION, true, IResource.DEPTH_ZERO);
  file.deleteMarkers(MarkerTypes.NORMAL_VALIDATION, true, IResource.DEPTH_ZERO);
  file.deleteMarkers(MarkerTypes.EXPENSIVE_VALIDATION, true, IResource.DEPTH_ZERO);
  if (markerCreator != null) {
    for (final Issue issue : issues) {
      markerCreator.createMarker(issue, file, MarkerTypes.forCheckType(issue.getType()));
    }
  } else {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.error("Could not create markers. The marker creator is null."); //$NON-NLS-1$
    }
  }
}
 
Example #18
Source File: WorkbenchMarkerResolutionGenerator.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * Note : this method is largely copied from the superclass, all we need to override is the call to
 * getAdaptedResolutions to provider the marker.
 */
@Override
public IMarkerResolution[] getResolutions(final IMarker marker) {
  final IMarkerResolution[] emptyResult = new IMarkerResolution[0];
  try {
    if (!marker.isSubtypeOf(MarkerTypes.ANY_VALIDATION)) {
      return emptyResult;
    }
  } catch (CoreException e) {
    return emptyResult;
  }
  if (!languageResourceHelper.isLanguageResource(marker.getResource())) {
    return emptyResult;
  }

  final XtextEditor editor = getEditor(marker.getResource());
  if (editor != null) {
    final IAnnotationModel annotationModel = editor.getDocumentProvider().getAnnotationModel(editor.getEditorInput());
    if (annotationModel != null && !isMarkerStillValid(marker, annotationModel)) {
      return emptyResult;
    }
  }

  final Iterable<IssueResolution> resolutions = getResolutionProvider().getResolutions(getIssueUtil().createIssue(marker));
  if (editor != null && editor.isEditorInputReadOnly()) {
    editor.close(false);
  }

  return getAdaptedResolutions(resolutions, marker);
}
 
Example #19
Source File: MarkerEraser.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Deletes {@link IFile}'s markers which type matches the given {@link CheckType}s represented by the
 * {@link CheckMode}.
 * 
 * @see CheckType
 * @see CheckMode#shouldCheck(CheckType)
 * @see MarkerTypes#forCheckType(CheckType)
 */
public void deleteMarkers(final IFile file, final CheckMode checkMode, final IProgressMonitor monitor)
		throws CoreException {
	for (CheckType chkType : CheckType.values()) {
		if (checkMode.shouldCheck(chkType)) {
			String markerType = MarkerTypes.forCheckType(chkType);
			file.deleteMarkers(markerType, true, IResource.DEPTH_ZERO);
		}
	}
}
 
Example #20
Source File: XtextGrammarQuickfixProviderTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private void assertAndApplyAllResolutions(XtextEditor xtextEditor, String issueCode, int issueDataCount, int issueCount,
		String resolutionLabel) throws CoreException {
	InternalBuilderTest.setAutoBuild(true);
	if (xtextEditor.isDirty()) {
		xtextEditor.doSave(new NullProgressMonitor());
	}
	InternalBuilderTest.fullBuild();
	IXtextDocument document = xtextEditor.getDocument();
	validateInEditor(document);
	List<Issue> issues = getIssues(document);
	assertFalse("Document has no issues, but should.", issues.isEmpty());

	issues.iterator().forEachRemaining((issue) -> {
		assertEquals(issueCode, issue.getCode());
		assertNotNull(issue.getData());
		assertEquals(issueDataCount, issue.getData().length);
	});
	IResource resource = xtextEditor.getResource();
	IMarker[] problems = resource.findMarkers(MarkerTypes.FAST_VALIDATION, true, IResource.DEPTH_INFINITE);
	assertEquals("Resource should have " + issueCount + " error marker.", issueCount, problems.length);
	validateInEditor(document);
	MarkerResolutionGenerator instance = injector.getInstance(MarkerResolutionGenerator.class);
	List<IMarkerResolution> resolutions = Lists.newArrayList(instance.getResolutions(problems[0]));
	assertEquals(1, resolutions.size());
	IMarkerResolution resolution = resolutions.iterator().next();
	assertTrue(resolution instanceof WorkbenchMarkerResolution);
	WorkbenchMarkerResolution workbenchResolution = (WorkbenchMarkerResolution) resolution;
	IMarker primaryMarker = problems[0];
	List<IMarker> others = Lists.newArrayList(workbenchResolution.findOtherMarkers(problems));
	assertFalse(others.contains(primaryMarker));
	assertEquals(problems.length - 1, others.size());
	others.add(primaryMarker);
	workbenchResolution.run(others.toArray(new IMarker[others.size()]), new NullProgressMonitor());
	if (xtextEditor.isDirty()) {
		xtextEditor.doSave(null);
	}
	InternalBuilderTest.cleanBuild();
	problems = resource.findMarkers(MarkerTypes.FAST_VALIDATION, true, IResource.DEPTH_INFINITE);
	assertEquals("Resource should have no error marker.", 0, problems.length);
}
 
Example #21
Source File: AbstractProblemHoverTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testMultipleAnnotationTypes() throws Exception {
	IMarker warning = file.createMarker(MarkerTypes.NORMAL_VALIDATION);
	warning.setAttribute(IMarker.LOCATION, "line: 2 " + file.getFullPath().toString());
	warning.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
	warning.setAttribute(IMarker.CHAR_START, 14);
	warning.setAttribute(IMarker.CHAR_END, 19);
	warning.setAttribute(IMarker.LINE_NUMBER, 2);
	warning.setAttribute(IMarker.MESSAGE, "Foo");
	
	IMarker info = file.createMarker(MarkerTypes.NORMAL_VALIDATION);
	info.setAttribute(IMarker.LOCATION, "line: 2 " + file.getFullPath().toString());
	info.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_INFO);
	info.setAttribute(IMarker.CHAR_START, 20);
	info.setAttribute(IMarker.CHAR_END, 29);
	info.setAttribute(IMarker.LINE_NUMBER, 2);
	info.setAttribute(IMarker.MESSAGE, "Bar");
	
	List<Annotation> annotations = hover.getAnnotations(1, -1);
	List<Annotation> sorted = hover.sortBySeverity(annotations);
	assertEquals(3, sorted.size());
	// First errors, then warnings, then the rest
	assertEquals("org.eclipse.xtext.ui.editor.error", sorted.get(0).getType());
	assertEquals("org.eclipse.xtext.ui.editor.warning", sorted.get(1).getType());
	assertEquals("org.eclipse.xtext.ui.editor.info", sorted.get(2).getType());
	
	warning.delete();
	info.delete();
}
 
Example #22
Source File: AnnotationWithQuickFixesHoverTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
	super.setUp();
	modelAsText = "stuff mystuff stuff yourstuff refs _mystuff stuff hisstuff refs _yourstuff";
	IFile file = IResourcesSetupUtil.createFile("test/test.testlanguage", modelAsText);
	editor = openEditor(file);
	document = editor.getDocument();
	hover = TestsActivator.getInstance().getInjector(getEditorId()).getInstance(AnnotationWithQuickFixesHover.class);
	hover.setSourceViewer(editor.getInternalSourceViewer());
	List<Issue> issues = document.readOnly(new IUnitOfWork<List<Issue>, XtextResource>() {
		@Override
		public List<Issue> exec(XtextResource state) throws Exception {
			return state.getResourceServiceProvider().getResourceValidator().validate(state, CheckMode.ALL, null);
		}
	});
	assertEquals(2, issues.size());
	MarkerCreator markerCreator = TestsActivator.getInstance().getInjector(getEditorId())
			.getInstance(MarkerCreator.class);
	for (Issue issue : issues) {
		markerCreator.createMarker(issue, file, MarkerTypes.forCheckType(issue.getType()));
	}

	if (Display.getCurrent().getActiveShell() != editor.getShell()) {
		System.out.println("Editor shell is not active. Active shell is: " + Display.getCurrent().getActiveShell());
		getWorkbenchWindow().getShell().forceActive();
		editor.getInternalSourceViewer().getTextWidget().forceFocus();
	}

}
 
Example #23
Source File: ValidateActionHandlerTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testExpensiveMarkerCreation() throws Exception {
	IFile iFile = createFile("foo/bar.testlanguage", "stuff foo");
	XtextEditor xtextEditor = openEditor(iFile);
	IHandlerService handlerService = xtextEditor.getSite().getService(IHandlerService.class);
	handlerService.executeCommand("org.eclipse.xtext.ui.tests.TestLanguage.validate", null);
	closeEditors();
	Job[] find = Job.getJobManager().find(ValidationJob.XTEXT_VALIDATION_FAMILY);
	for (Job job : find) {
		job.join();
	}
	IResource file = xtextEditor.getResource();
	IMarker[] markers = file.findMarkers(MarkerTypes.EXPENSIVE_VALIDATION, true, IResource.DEPTH_ZERO);
	assertEquals(1, markers.length);

}
 
Example #24
Source File: ProjectTestsUtils.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/***/
@SafeVarargs
public static IMarker[] assertMarkers(String assertMessage, final IResource resource, int count,
		final Predicate<IMarker>... markerPredicates) throws CoreException {

	return assertMarkers(assertMessage, resource, MarkerTypes.ANY_VALIDATION, count, markerPredicates);
}
 
Example #25
Source File: IssueUtil.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Creates an Issue out of a Marker.
 * setSyntaxError is unset since the current API does not allow fixing systax errors anyway.
 * 
 * @param marker The marker to create an issue from
 * @return an issue created out of the given marker or <code>null</code>
 */
public Issue createIssue(IMarker marker) {
	Issue.IssueImpl issue = new Issue.IssueImpl();
	try {
		Map<String, Object> attributes = marker.getAttributes();
		String markerType = marker.getType();
		Object message = attributes.get(IMarker.MESSAGE);
		issue.setMessage(message  instanceof String ? (String) message : null);
		Object lineNumber = attributes.get(IMarker.LINE_NUMBER);
		issue.setLineNumber(lineNumber instanceof Integer ? (Integer) lineNumber : null);
		Object column = attributes.get(Issue.COLUMN_KEY);
		issue.setColumn(column instanceof Integer ? (Integer) column : null);
		Object offset = attributes.get(IMarker.CHAR_START);
		Object endOffset = attributes.get(IMarker.CHAR_END);
		if(offset instanceof Integer && endOffset instanceof Integer) {
			issue.setOffset((Integer) offset);
			issue.setLength((Integer) endOffset - (Integer) offset); 
		} else {
			issue.setOffset(-1);
			issue.setLength(0);
		}
		Object code = attributes.get(Issue.CODE_KEY);
		issue.setCode(code instanceof String ? (String) code:null);
		Object data = attributes.get(Issue.DATA_KEY);
		issue.setData(data instanceof String ? Strings.unpack((String) data) : null);
		Object uri = attributes.get(Issue.URI_KEY);
		issue.setUriToProblem(uri instanceof String ? URI.createURI((String) uri) : null);
		Object severity = attributes.get(IMarker.SEVERITY);
		Severity translatedSeverity = translateSeverity(severity instanceof Integer ? (Integer) severity : 0);
		if(translatedSeverity == null)
			throw new IllegalArgumentException(marker.toString());
		issue.setSeverity(translatedSeverity);
		if(markerTypeProvider != null)
			issue.setType(markerTypeProvider.getCheckType(markerType));
		else
			issue.setType(MarkerTypes.toCheckType(markerType));
	} catch (CoreException e) {
		return null;
	}
	return issue;
}
 
Example #26
Source File: MarkerTypeProvider.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
public CheckType getCheckType(String markerType) {
	return MarkerTypes.toCheckType(markerType);
}
 
Example #27
Source File: MarkerTypeProvider.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
public String getMarkerType(Issue issue) {
	return MarkerTypes.forCheckType(issue.getType());
}
 
Example #28
Source File: IssueDataTest.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
@Test public void testIssueData() throws Exception {
	IFile dslFile = dslFile(getProjectName(), getFileName(), getFileExtension(), MODEL_WITH_LINKING_ERROR);
	XtextEditor xtextEditor = openEditor(dslFile);
	IXtextDocument document = xtextEditor.getDocument();
	IResource file = xtextEditor.getResource();
	List<Issue> issues = getAllValidationIssues(document);
	assertEquals(1, issues.size());
	Issue issue = issues.get(0);
	assertEquals(2, issue.getLineNumber().intValue());
	assertEquals(3, issue.getColumn().intValue());
	assertEquals(PREFIX.length(), issue.getOffset().intValue());
	assertEquals(QuickfixCrossrefTestLanguageValidator.TRIGGER_VALIDATION_ISSUE.length(), issue.getLength().intValue());
	String[] expectedIssueData = new String[]{ QuickfixCrossrefTestLanguageValidator.ISSUE_DATA_0,
		QuickfixCrossrefTestLanguageValidator.ISSUE_DATA_1};
	assertTrue(Arrays.equals(expectedIssueData, issue.getData()));
	Thread.sleep(1000);

	IAnnotationModel annotationModel = xtextEditor.getDocumentProvider().getAnnotationModel(
			xtextEditor.getEditorInput());
	AnnotationIssueProcessor annotationIssueProcessor = 
			new AnnotationIssueProcessor(document, annotationModel, new IssueResolutionProvider.NullImpl());
	annotationIssueProcessor.processIssues(issues, new NullProgressMonitor());
	Iterator<?> annotationIterator = annotationModel.getAnnotationIterator();
	// filter QuickDiffAnnotations
	List<Object> allAnnotations = Lists.newArrayList(annotationIterator);
	List<XtextAnnotation> annotations = newArrayList(filter(allAnnotations, XtextAnnotation.class));
	assertEquals(annotations.toString(), 1, annotations.size());
	XtextAnnotation annotation = annotations.get(0);
	assertTrue(Arrays.equals(expectedIssueData, annotation.getIssueData()));
	IssueUtil issueUtil = new IssueUtil();
	Issue issueFromAnnotation = issueUtil.getIssueFromAnnotation(annotation);
	assertTrue(Arrays.equals(expectedIssueData, issueFromAnnotation.getData()));

	new MarkerCreator().createMarker(issue, file, MarkerTypes.FAST_VALIDATION);
	IMarker[] markers = file.findMarkers(MarkerTypes.FAST_VALIDATION, true, IResource.DEPTH_ZERO);
	String errorMessage = new AnnotatedTextToString().withFile(dslFile).withMarkers(markers).toString().trim();
	assertEquals(errorMessage, 1, markers.length);
	String attribute = (String) markers[0].getAttribute(Issue.DATA_KEY);
	assertNotNull(attribute);
	assertTrue(Arrays.equals(expectedIssueData, Strings.unpack(attribute)));

	Issue issueFromMarker = issueUtil.createIssue(markers[0]);
	assertEquals(issue.getColumn(), issueFromMarker.getColumn());
	assertEquals(issue.getLineNumber(), issueFromMarker.getLineNumber());
	assertEquals(issue.getOffset(), issueFromMarker.getOffset());
	assertEquals(issue.getLength(), issueFromMarker.getLength());
	assertTrue(Arrays.equals(expectedIssueData, issueFromMarker.getData()));
}
 
Example #29
Source File: AnnotatedTextToString.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
public AnnotatedTextToString withMarkersFromFile() {
	return withMarkersFromFile(MarkerTypes.FAST_VALIDATION, IMarker.MESSAGE);
}
 
Example #30
Source File: N4JSIssue.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Issue createIssue(IMarker marker) {
	final N4JSIssue issue = new N4JSIssue();
	issue.setMarker(marker);

	// ---- BEGIN: copied from super class ----

	try {
		Map<String, Object> attributes = marker.getAttributes();
		String markerType = marker.getType();
		Object message = attributes.get(IMarker.MESSAGE);
		issue.setMessage(message instanceof String ? (String) message : null);
		Object lineNumber = attributes.get(IMarker.LINE_NUMBER);
		issue.setLineNumber(lineNumber instanceof Integer ? (Integer) lineNumber - 1 : null);
		Object offset = attributes.get(IMarker.CHAR_START);
		Object endOffset = attributes.get(IMarker.CHAR_END);
		if (offset instanceof Integer && endOffset instanceof Integer) {
			issue.setOffset((Integer) offset);
			issue.setLength((Integer) endOffset - (Integer) offset);
		} else {
			issue.setOffset(-1);
			issue.setLength(0);
		}
		Object code = attributes.get(Issue.CODE_KEY);
		issue.setCode(code instanceof String ? (String) code : null);
		Object data = attributes.get(Issue.DATA_KEY);
		issue.setData(data instanceof String ? Strings.unpack((String) data) : null);
		Object uri = attributes.get(Issue.URI_KEY);
		issue.setUriToProblem(uri instanceof String ? URI.createURI((String) uri) : null);
		Object severity = attributes.get(IMarker.SEVERITY);
		Severity translatedSeverity = translateSeverity(severity instanceof Integer ? (Integer) severity : 0);
		if (translatedSeverity == null)
			throw new IllegalArgumentException(marker.toString());
		issue.setSeverity(translatedSeverity);
		if (markerTypeProvider != null)
			issue.setType(markerTypeProvider.getCheckType(markerType));
		else
			issue.setType(MarkerTypes.toCheckType(markerType));
	} catch (CoreException e) {
		return null;
	}
	return issue;

	// ---- END: copied from super class ----
}