Java Code Examples for org.eclipse.core.resources.IResource#findMarkers()

The following examples show how to use org.eclipse.core.resources.IResource#findMarkers() . 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: ImportedProjectNamePluginTest.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Asserts that the given {@code resource} has at least one marker with the given {@code issueCode}.
 */
private static void assertHasMarker(IResource resource, String issueCode) throws CoreException {
	final IMarker[] markers = resource.findMarkers(null, true, IResource.DEPTH_INFINITE);
	final StringBuilder allMarkersDescription = new StringBuilder();
	for (IMarker marker : markers) {
		final String markerIssueCode = marker.getAttribute(Issue.CODE_KEY, "");
		if (issueCode.equals(markerIssueCode)) {
			// assertion fulfilled
			return;
		}
		allMarkersDescription.append("\n");
		allMarkersDescription.append("line " + MarkerUtilities.getLineNumber(marker) + ": ");
		allMarkersDescription.append(marker.getAttribute(IMarker.MESSAGE, "<no message>"));
	}
	Assert.fail("Expected resource " + resource.getFullPath() + " to have at least one marker with issue code " +
			issueCode + " but was " + allMarkersDescription.toString());
}
 
Example 3
Source File: ProjectUtils.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
/**
 * Wait until the project has finished building and markers have disappeared.
 * 
 * @throws AssertionError if markers are still present
 */
public static IMarker[] waitUntilNoMarkersFound(IResource resource, String markerType,
    boolean includeSubtypes, int depth) throws CoreException {
  Stopwatch elapsed = Stopwatch.createStarted();
  IMarker[] markers;
  do {
    ProjectUtils.waitForProjects(resource.getProject());
    markers = resource.findMarkers(markerType, includeSubtypes, depth);
    if (markers.length > 0) {
      System.err.printf("[WARNING][TESTS] %s: %d markers found of type %s\n", elapsed,
          markers.length, markerType);
      ThreadDumpingWatchdog.report("Expected no markers of type " + markerType, elapsed);
    }
  } while (elapsed.elapsed(TimeUnit.SECONDS) < 300 && markers.length > 0);

  ArrayAssertions.assertIsEmpty(markers, ProjectUtils::formatProblem);
  return markers;
}
 
Example 4
Source File: ClearMarkersOperation.java    From goclipse with Eclipse Public License 1.0 6 votes vote down vote up
protected boolean doDeleteProjectMarkers(String markerType, IOperationMonitor parentOM) 
		throws OperationCancellation {
	
	try(IOperationSubMonitor om = parentOM.enterSubTask(LangCoreMessages.BUILD_ClearingProblemMarkers)) {
		
		ArrayList2<IResource> resources = ResourceUtils.getResourcesAt(location);
		for (IResource container : resources) {
		try {
			IMarker[] findMarkers = container.findMarkers(markerType, true, IResource.DEPTH_INFINITE);
			parentOM.checkCancellation();
			if(findMarkers.length != 0) {
				container.deleteMarkers(markerType, true, IResource.DEPTH_INFINITE);
				return true;
			}
		} catch (CoreException ce) {
			EclipseCore.logStatus(ce);
		}
		}
	}
	return false;
}
 
Example 5
Source File: CommitAction.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
public int getHighestProblemSeverity(IResource[] resources) {
 	int mostSeriousSeverity = -1;
 	
 	for (int i = 0; i < resources.length; i++) {
 		IResource resource = resources[i];
 		try {
	IMarker[] problems = resource.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_ZERO);
	for (int j = 0; j < problems.length; j++) {
		IMarker problem = problems[j];
		int severity = problem.getAttribute(IMarker.SEVERITY, 0);
		if (severity > mostSeriousSeverity) {
			mostSeriousSeverity = severity;
		}
	}
} catch (CoreException e) {
}
 	}
 	
 	return mostSeriousSeverity;
 }
 
Example 6
Source File: MarkerReporter.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void addMarker(MarkerParameter mp) throws CoreException {
    Map<String, Object> attributes = createMarkerAttributes(mp);
    if (attributes.isEmpty()) {
        collection.remove(mp.bug);
        return;
    }
    IResource markerTarget = mp.resource.getMarkerTarget();
    IMarker[] existingMarkers = markerTarget.findMarkers(mp.markerType, true, IResource.DEPTH_ZERO);

    // XXX Workaround for bug 2785257 (has to be solved better)
    // see
    // http://sourceforge.net/tracker/?func=detail&atid=614693&aid=2785257&group_id=96405
    // currently we can't run FB only on a subset of classes related to the
    // specific
    // source folder if source folders have same class output directory.
    // In this case the classes from BOTH source folders are examined by FB
    // and
    // new markers can be created for issues which are already reported.
    // Therefore here we check if a marker with SAME bug id is already
    // known,
    // and if yes, delete it (replacing with newer one)
    if (existingMarkers.length > 0) {
        IMarker oldMarker = findSameBug(attributes, existingMarkers);
        if (oldMarker != null) {
            oldMarker.delete();
        }
    }
    IMarker newMarker = markerTarget.createMarker(mp.markerType);
    newMarker.setAttributes(attributes);
}
 
Example 7
Source File: TLAMarkerHelper.java    From tlaplus with MIT License 5 votes vote down vote up
/**
 * Retrieves problem markers associated with given resource
 * @param resource
 * @param monitor
 * @return
 */
public static IMarker[] getProblemMarkers(final IResource resource, final IProgressMonitor monitor)
{
    IMarker[] problems = null;
    try
    {
        problems = resource.findMarkers(TLAMarkerHelper.TOOLBOX_MARKERS_ALL_MARKER_ID, true,
                IResource.DEPTH_INFINITE);
    } catch (CoreException e)
    {
        Activator.getDefault().logError("Error retrieving the problem markers", e);
        problems = new IMarker[0];
    }
    return problems;
}
 
Example 8
Source File: CodeHighlightDecorator.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private IMarker[] getMarkersOfResource(IResource resource, int depth) {
	try {
		return resource.findMarkers(SOURCE_CODE_HIGHLIGHT_MARKER_ID, true, depth);
	} catch (CoreException e) {
		return EMPTY_MARKER_ARRAY;
	}
}
 
Example 9
Source File: ProverHelper.java    From tlaplus with MIT License 5 votes vote down vote up
/**
 * Returns the SANY step marker on the module whose SANY location
 * has the same begin and end line as the location passed to this method.
 * Returns null if such a marker is not found.
 * 
 * See {@link ProverHelper#SANY_MARKER} for a description of
 * these markers.
 * 
 * @param location
 * @param module
 * @return
 */
public static IMarker findSANYMarker(IResource module, Location location)
{
    try
    {
        IMarker[] sanyMarkers = module.findMarkers(SANY_MARKER, false, IResource.DEPTH_ZERO);
        /*
         * Iterate through all markers. For each marker, retrieve
         * the SANY location. Return the marker if its SANY location
         * equals location.
         */
        for (int i = 0; i < sanyMarkers.length; i++)
        {
            String sanyLocString = sanyMarkers[i].getAttribute(SANY_LOC_ATR, "");
            if (!(sanyLocString.length() == 0))
            {
                Location sanyLoc = stringToLoc(sanyLocString);
                if (sanyLoc.beginLine() == location.beginLine()/* && sanyLoc.endLine() == location.endLine()*/)
                {
                    return sanyMarkers[i];
                }
            }
        }
    } catch (CoreException e)
    {
        ProverUIActivator.getDefault().logError("Error finding existing SANY marker for location " + location, e);
    }
    return null;
}
 
Example 10
Source File: JarFileExportOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Tells whether the given resource (or its children) have compile errors.
 * The method acts on the current build state and does not recompile.
 *
 * @param resource the resource to check for errors
 * @return <code>true</code> if the resource (and its children) are error free
 * @throws CoreException import org.eclipse.core.runtime.CoreException if there's a marker problem
 */
private boolean hasCompileWarnings(IResource resource) throws CoreException {
	IMarker[] problemMarkers= resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
	for (int i= 0; i < problemMarkers.length; i++) {
		if (problemMarkers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_WARNING)
			return true;
	}
	return false;
}
 
Example 11
Source File: MarkerUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Finds the first marker matching the given position and message.
 * 
 * @param start the start, or -1 if the marker does not contain this attribute
 * @param end the end, or -1 if the marker does not contain this attribute
 * @param message the message, or null if the marker does not contain this
 *          attribute
 */
public static IMarker findMarker(String markerId, int start, int end,
    IResource resource, String message, boolean includeSubtypes)
    throws CoreException {
  IMarker[] markers = resource.findMarkers(markerId, includeSubtypes,
      IResource.DEPTH_ZERO);
  for (IMarker marker : markers) {
    int curStart = marker.getAttribute(IMarker.CHAR_START, -1);
    if (curStart != start) {
      continue;
    }

    int curEnd = marker.getAttribute(IMarker.CHAR_END, -1);
    if (curEnd != end) {
      continue;
    }

    String curMsg = marker.getAttribute(IMarker.MESSAGE, null);
    if (curMsg == null || !message.equals(curMsg)) {
      continue;
    }

    return marker;
  }

  return null;
}
 
Example 12
Source File: JarFileExportOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Tells whether the given resource (or its children) have compile errors.
 * The method acts on the current build state and does not recompile.
 *
 * @param resource the resource to check for errors
 * @return <code>true</code> if the resource (and its children) are error free
 * @throws CoreException import org.eclipse.core.runtime.CoreException if there's a marker problem
 */
private boolean hasCompileErrors(IResource resource) throws CoreException {
	IMarker[] problemMarkers= resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
	for (int i= 0; i < problemMarkers.length; i++) {
		if (problemMarkers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_ERROR)
			return true;
	}
	return false;
}
 
Example 13
Source File: SCTBuilder.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
private boolean hasError(IResource resource) {
	IMarker[] findMarkers = null;
	try {
		findMarkers = resource.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE);
		for (IMarker iMarker : findMarkers) {
			Integer attribute = (Integer) iMarker.getAttribute(IMarker.SEVERITY);
			if (attribute.intValue() == IMarker.SEVERITY_ERROR) {
				return true;
			}
		}
	} catch (CoreException e) {
		e.printStackTrace();
	}
	return false;
}
 
Example 14
Source File: ProblemsLabelDecorator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private int getErrorTicksFromMarkers(IResource res, int depth, ISourceReference sourceElement) throws CoreException {
	if (res == null || !res.isAccessible()) {
		return 0;
	}
	int severity= 0;
	if (sourceElement == null) {
		if (res instanceof IProject) {
			severity= res.findMaxProblemSeverity(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, true, IResource.DEPTH_ZERO);
			if (severity == IMarker.SEVERITY_ERROR) {
				return ERRORTICK_BUILDPATH_ERROR;
			}
			severity= res.findMaxProblemSeverity(JavaRuntime.JRE_CONTAINER_MARKER, true, IResource.DEPTH_ZERO);
			if (severity == IMarker.SEVERITY_ERROR) {
				return ERRORTICK_BUILDPATH_ERROR;
			}
		}
		severity= res.findMaxProblemSeverity(IMarker.PROBLEM, true, depth);
	} else {
		IMarker[] markers= res.findMarkers(IMarker.PROBLEM, true, depth);
		if (markers != null && markers.length > 0) {
			for (int i= 0; i < markers.length && (severity != IMarker.SEVERITY_ERROR); i++) {
				IMarker curr= markers[i];
				if (isMarkerInRange(curr, sourceElement)) {
					int val= curr.getAttribute(IMarker.SEVERITY, -1);
					if (val == IMarker.SEVERITY_WARNING || val == IMarker.SEVERITY_ERROR) {
						severity= val;
					}
				}
			}
		}
	}
	if (severity == IMarker.SEVERITY_ERROR) {
		return ERRORTICK_ERROR;
	} else if (severity == IMarker.SEVERITY_WARNING) {
		return ERRORTICK_WARNING;
	}
	return 0;
}
 
Example 15
Source File: ResourceUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static List<IMarker> findMarkers(IResource resource, Integer... severities) throws CoreException {
	if (resource == null) {
		return null;
	}
	Set<Integer> targetSeverities = severities == null ? Collections.emptySet()
			: new HashSet<>(Arrays.asList(severities));
	IMarker[] allmarkers = resource.findMarkers(null /* all markers */, true /* subtypes */,
			IResource.DEPTH_INFINITE);
	List<IMarker> markers = Stream.of(allmarkers).filter(
			m -> targetSeverities.isEmpty() || targetSeverities.contains(m.getAttribute(IMarker.SEVERITY, 0)))
			.collect(Collectors.toList());
	return markers;
}
 
Example 16
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 17
Source File: ProblemReporter.java    From cppcheclipse with Apache License 2.0 4 votes vote down vote up
private void reportProblem(IResource resource, String message,
		int severity, int lineNumber, String id, File file,
		int originalLineNumber) throws CoreException {
	// TODO: open external file, see
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=151005 on how to
	// generate markers for external files

	// Do not put in duplicates
	IMarker[] cur = resource.findMarkers(CHECKER_MARKER_TYPE, false,
			IResource.DEPTH_ZERO);
	if (cur != null) {
		for (IMarker element : cur) {
			int oldLineNumber = element
					.getAttribute(IMarker.LINE_NUMBER, 0);
			if (lineNumber == oldLineNumber) {
				String oldMessage = element.getAttribute(IMarker.MESSAGE,
						""); //$NON-NLS-1$
				int oldSeverity = element.getAttribute(IMarker.SEVERITY,
						100);
				if (severity == oldSeverity && message.equals(oldMessage))
					return;
			}
		}
	}

	// see
	// http://wiki.eclipse.org/FAQ_Why_don%27t_my_markers_appear_in_the_editor%27s_vertical_ruler%3F
	Map<String, Object> attributes = new HashMap<String, Object>();
	if (lineNumber != 0) {
		MarkerUtilities.setLineNumber(attributes, lineNumber);
	}
	MarkerUtilities.setMessage(attributes, message);
	attributes.put(IMarker.SEVERITY, severity);
	// the following attributes are only used for the quick fixes
	attributes.put(ATTRIBUTE_ID, id);
	if (file != null) {
		attributes.put(ATTRIBUTE_FILE, file.toString());
	}
	attributes.put(ATTRIBUTE_ORIGINAL_LINE_NUMBER, originalLineNumber);
	MarkerUtilities.createMarker(resource, attributes, CHECKER_MARKER_TYPE);
}
 
Example 18
Source File: BaseTest.java    From codewind-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
protected IMarker[] getMarkers(IResource resource) throws Exception {
	return resource.findMarkers(MARKER_TYPE, false, IResource.DEPTH_ONE);
}
 
Example 19
Source File: ValidationMarkerContentProvider.java    From bonita-studio with GNU General Public License v2.0 4 votes vote down vote up
private Object[] processMarkers(final IResource resource) throws CoreException {
    if (resource != null && resource.exists()) {
        return resource.findMarkers(ProcessMarkerNavigationProvider.MARKER_TYPE, false, IResource.DEPTH_INFINITE);
    }
    return new Object[0];
}
 
Example 20
Source File: TodoTaskMarkerManager.java    From xds-ide with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Returns all markers of the specified type on this resource, and on its 
 * children. Returns an empty array if there are no matching markers.
 * 
 * @param resource a resource to operate on, must not be <tt>null</tt>
 * @throws CoreException 
 */    
public static IMarker[] findMarkers(IResource resource) throws CoreException 
{
    return resource.findMarkers(IMarker.TASK, true, IResource.DEPTH_INFINITE);
}