Java Code Examples for org.eclipse.core.resources.IMarker#getResource()

The following examples show how to use org.eclipse.core.resources.IMarker#getResource() . 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: N4JSMarkerResolutionGenerator.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Same as {@link #isMarkerStillValid(IMarker, IAnnotationModel)}, but obtains the annotation model from the
 * marker's editor.
 */
@SuppressWarnings("deprecation")
private boolean isMarkerStillValid(IMarker marker) {
	if (marker == null)
		return false;
	if (marker.getResource() instanceof IProject) {
		// This happens with IssueCodes.NODE_MODULES_OUT_OF_SYNC
		return true;
	}

	final XtextEditor editor = getEditor(marker.getResource());
	if (editor == null)
		return false;
	final IAnnotationModel annotationModel = editor.getDocumentProvider().getAnnotationModel(
			editor.getEditorInput());
	if (annotationModel == null)
		return false;
	return isMarkerStillValid(marker, annotationModel);
}
 
Example 2
Source File: XsltQuickFix.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to edit the {@link IDocument} in the open editor. If the editor is not open,
 * reads the file from memory and transforms in place.
 */
@Override
public void run(IMarker marker) {
  try {
    IFile file = (IFile) marker.getResource();
    IDocument document = getCurrentDocument(file);
    URL xslPath = XsltQuickFix.class.getResource(xsltPath);
    if (document != null) {
      String currentContents = document.get();
      try (Reader documentReader = new StringReader(currentContents);
          InputStream stylesheet = xslPath.openStream();
          InputStream transformed = Xslt.applyXslt(documentReader, stylesheet)) {
        String encoding = file.getCharset();
        String newDoc = ValidationUtils.convertStreamToString(transformed, encoding);
        document.set(newDoc);
      }
    } else {
      Xslt.transformInPlace(file, xslPath);
    }
  } catch (IOException | TransformerException | CoreException ex) {
    logger.log(Level.SEVERE, ex.getMessage());
  }
}
 
Example 3
Source File: BuildWorkspaceHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static String convertMarker(IMarker marker) {
	StringBuilder builder = new StringBuilder();
	String message = marker.getAttribute(IMarker.MESSAGE, "<no message>");
	String code = String.valueOf(marker.getAttribute(IJavaModelMarker.ID, 0));
	builder.append(" message: ").append(message).append(";");
	builder.append(" code: ").append(code).append(";");
	IResource resource = marker.getResource();
	if (resource != null) {
		builder.append(" resource: ").append(resource.getLocation()).append(";");
	}
	int line = marker.getAttribute(IMarker.LINE_NUMBER, -1);
	if (line > 0) {
		builder.append(" line: ").append(line);
	}
	return builder.toString();
}
 
Example 4
Source File: PyBreakpoint.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @return the file to be debugged or null if it cannot be determined.
 */
public String getFile() {
    IMarker marker = getMarker();
    IResource r = marker.getResource();
    if (r instanceof IFile) {
        IPath location = r.getLocation();
        if (location == null) {
            return null;
        }
        return location.toOSString();
    } else {
        //it's an external file...
        try {
            return (String) marker.getAttribute(PyBreakpoint.PY_BREAK_EXTERNAL_PATH_ID);
        } catch (CoreException e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example 5
Source File: TextDocumentMarkerResolution.java    From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 6 votes vote down vote up
public void run(IMarker marker) {
    try {
        IResource resource = marker.getResource();
        if (resource.getType() != IResource.FILE) {
            throw new CoreException(createStatus(null, "The editor is not a File: " + resource.getName()));
        }
        IFile file = (IFile) resource;
        ITextEditor editor = openTextEditor(file);
        IDocument document = editor.getDocumentProvider().getDocument(new FileEditorInput(file));
        if (document == null) {
            throw new CoreException(createStatus(null, "The document is null"));
        }
        IRegion region = processFix(document, marker);
        if (region != null) {
            editor.selectAndReveal(region.getOffset(), region.getLength());
        }
    } catch (CoreException e) {
        Activator.getDefault().getLog().log(e.getStatus());
    }
}
 
Example 6
Source File: GoSearchPageScoreComputer.java    From goclipse with Eclipse Public License 1.0 6 votes vote down vote up
private IResource getResource(Object input) {
  if (input instanceof IResource) {
    return (IResource) input;
  }

  if (input instanceof IAdaptable) {
    IAdaptable adapt = (IAdaptable) input;

    return (IResource) adapt.getAdapter(IResource.class);
  }

  if (input instanceof IMarker) {
    IMarker marker = (IMarker) input;

    return marker.getResource();
  }

  return null;
}
 
Example 7
Source File: ShowInPackageExplorerAction.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void selectionChanged(IAction action, ISelection selection) {
    if (!(selection instanceof IStructuredSelection)) {
        data = null;
        action.setEnabled(false);
        return;
    }
    IStructuredSelection ss = (IStructuredSelection) selection;
    if (ss.size() != 1) {
        data = null;
        action.setEnabled(false);
        return;
    }
    Object firstElement = ss.getFirstElement();
    if (firstElement instanceof IMarker) {
        IMarker marker = (IMarker) firstElement;
        data = marker.getResource();
        action.setEnabled(data != null);
        return;
    }
    if (!(firstElement instanceof BugGroup)) {
        data = null;
        action.setEnabled(false);
        return;
    }
    BugGroup group = (BugGroup) firstElement;
    if (group.getType() == GroupType.Class || group.getType() == GroupType.Package || group.getType() == GroupType.Project) {
        data = group.getData();
        action.setEnabled(data != null);
    } else {
        data = null;
        action.setEnabled(false);
    }
}
 
Example 8
Source File: PyBreakpoint.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
private IDocument getDocument() {
    IMarker marker = getMarker();
    IResource r = marker.getResource();
    if (r instanceof IFile) {
        return FileUtilsFileBuffer.getDocFromResource(r);
    } else {
        //it's an external file...
        try {
            return FileUtilsFileBuffer
                    .getDocFromFile(new File((String) marker.getAttribute(PyBreakpoint.PY_BREAK_EXTERNAL_PATH_ID)));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example 9
Source File: CorrectionMarkerResolutionGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static ICompilationUnit getCompilationUnit(IMarker marker) {
	IResource res= marker.getResource();
	if (res instanceof IFile && res.isAccessible()) {
		IJavaElement element= JavaCore.create((IFile) res);
		if (element instanceof ICompilationUnit)
			return (ICompilationUnit) element;
	}
	return null;
}
 
Example 10
Source File: ProblemHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static ICompilationUnit getCompilationUnit(IMarker marker) {
	IResource res= marker.getResource();
	if (res instanceof IFile && res.isAccessible()) {
		IJavaElement element= JavaCore.create((IFile) res);
		if (element instanceof ICompilationUnit)
			return (ICompilationUnit) element;
	}
	return null;
}
 
Example 11
Source File: JavaMarkerResolutionGenerator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private static ICompilationUnit getCompilationUnit(IMarker marker) {
  IResource res = marker.getResource();
  if (res instanceof IFile && res.isAccessible()) {
    IJavaElement element = JavaCore.create((IFile) res);
    if (element instanceof ICompilationUnit) {
      return (ICompilationUnit) element;
    }
  }
  return null;
}
 
Example 12
Source File: TestabilityResourceMarkerField.java    From testability-explorer with Apache License 2.0 5 votes vote down vote up
@Override
public String getValue(MarkerItem item) {
  IMarker marker = item.getMarker();
  if (marker != null) {
    IResource resource = marker.getResource();
    String name = resource.getName();
    return name;
  }
  return null;
}
 
Example 13
Source File: MarkerComparator.java    From tlaplus with MIT License 5 votes vote down vote up
public int compare(IMarker m1, IMarker m2) {
	int m1severity = m1.getAttribute(IMarker.SEVERITY,
			IMarker.SEVERITY_INFO);
	int m2severity = m2.getAttribute(IMarker.SEVERITY,
			IMarker.SEVERITY_INFO);

	if (m1severity == m2severity) {
		// same severity, look on the resource
		IResource r1 = m1.getResource();
		IResource r2 = m2.getResource();

		if (r2.equals(r1)) {
			// same resource, look on the line numbers
			int line1 = m1.getAttribute(TLAMarkerHelper.LOCATION_BEGINLINE,
					-1);
			int line2 = m2.getAttribute(TLAMarkerHelper.LOCATION_BEGINLINE,
					-1);

			return new Integer(line2).compareTo(new Integer(line1));

		} else {
			return r2.getName().compareTo(r1.getName());
		}

	} else {
		return new Integer(m2severity).compareTo(new Integer(m1severity));
	}
}
 
Example 14
Source File: AbstractASTResolution.java    From eclipse-cs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private ICompilationUnit getCompilationUnit(IMarker marker) {
  IResource res = marker.getResource();
  if (res instanceof IFile && res.isAccessible()) {
    IJavaElement element = JavaCore.create((IFile) res);
    if (element instanceof ICompilationUnit) {
      return (ICompilationUnit) element;
    }
  }
  return null;
}
 
Example 15
Source File: CopyMarkerDetailsAction.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private String getContent(Set<IMarker> markers) {
    StringBuilder fullText = new StringBuilder();
    for (IMarker marker : markers) {
        try {
            StringBuilder line = new StringBuilder();

            IResource resource = marker.getResource();
            if (resource != null) {
                IPath location = resource.getLocation();
                if (location != null) {
                    line.append(location.toPortableString());
                } else {
                    line.append(resource.getFullPath());
                }
            }
            Integer lineNumber = (Integer) marker.getAttribute(IMarker.LINE_NUMBER);
            line.append(":").append(lineNumber);
            String message = (String) marker.getAttribute(IMarker.MESSAGE);
            line.append(" ").append(message);

            line.append(System.getProperty("line.separator", "\n"));
            fullText.append(line.toString());
        } catch (CoreException e) {
            FindbugsPlugin.getDefault().logException(e, "Exception while parsing content of FindBugs markers.");
        }
    }
    return fullText.toString();
}
 
Example 16
Source File: BugResolution.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Get the compilation unit for the marker.
 *
 * @param marker
 *            not null
 * @return The compilation unit for the marker, or null if the file was not
 *         accessible or was not a Java file.
 */
@CheckForNull
protected ICompilationUnit getCompilationUnit(IMarker marker) {
    IResource res = marker.getResource();
    if (res instanceof IFile && res.isAccessible()) {
        IJavaElement element = JavaCore.create((IFile) res);
        if (element instanceof ICompilationUnit) {
            return (ICompilationUnit) element;
        }
    }
    return null;
}
 
Example 17
Source File: XBookmarkHandler.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Jumps to the xBookmark with the given number, if there is one.
 * When necessary an editor will be opened.
 * If there are multiple marks with the same number then the previous/next
 * one from the current selection will be jumped to (when exactly on
 * a xBookmark that mark isn't considered as a jump target).
 * If after any xBookmark with that number, the search toggles around
 * to the first one and vice versa.
 * 
 * @param markerNumber  the number of the mark to jump to
 * @param backward  true, if the previous mark should be jumped to instead
 *                  of the next one
 */
protected void gotoBookmark (int markerNumber) {
    IResource scope = XBookmarksUtils.getWorkspaceScope();
    if (scope == null) {
        return;
    }
    IMarker marker = XBookmarksUtils.fetchBookmark(scope, markerNumber);
    if (marker == null) {
        statusLine.showErrMessage(MessageFormat.format(Messages.BookmarkAction_BM_NotFound, markerNumber));
        return;
    }
    IResource resource = marker.getResource();
    if (! (resource instanceof IFile)) {
        statusLine.showErrMessage(MessageFormat.format(Messages.BookmarkAction_BM_HbzWhere, markerNumber));
        return;
    }
    IWorkbenchPage page = WorkbenchUtils.getActivePage();
    if (page == null) {
        statusLine.showErrMessage(MessageFormat.format(Messages.BookmarkAction_CantGoBM_NoActivePage, markerNumber));
        return;
    }
    // now try to jump and open the right editor, if necessary
    try {
        IDE.openEditor(page, marker, OpenStrategy.activateOnOpen());
        statusLine.showMessage(
                MessageFormat.format(Messages.BookmarkAction_OnBM, markerNumber),
                XBookmarksPlugin.IMGID_GOTO);
    }
    catch (PartInitException e) {
        XBookmarksUtils.logError(e);
        statusLine.showErrMessage(MessageFormat.format(Messages.BookmarkAction_CantGoBM, markerNumber));
    }
}
 
Example 18
Source File: WorkspaceDiagnosticsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private List<IMarker> getProblemMarkers(IProgressMonitor monitor) throws CoreException {
	IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
	List<IMarker> markers = new ArrayList<>();
	for (IProject project : projects) {
		if (monitor != null && monitor.isCanceled()) {
			throw new OperationCanceledException();
		}
		if (JavaLanguageServerPlugin.getProjectsManager().getDefaultProject().equals(project)) {
			continue;
		}
		IMarker[] allMarkers = project.findMarkers(null, true, IResource.DEPTH_INFINITE);
		for (IMarker marker : allMarkers) {
			if (!marker.exists() || CheckMissingNaturesListener.MARKER_TYPE.equals(marker.getType())) {
				continue;
			}
			if (IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER.equals(marker.getType()) || IJavaModelMarker.TASK_MARKER.equals(marker.getType())) {
				markers.add(marker);
				continue;
			}
			IResource resource = marker.getResource();
			if (project.equals(resource) || projectsManager.isBuildFile(resource)) {
				markers.add(marker);
			}
		}
	}
	return markers;
}
 
Example 19
Source File: N4JSMarkerResolutionGenerator.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public IMarkerResolution[] getResolutions(IMarker marker) {
	if (existsDirtyEditorFor(marker)) {
		showError_UnsavedChanges();
		return new IMarkerResolution[0];
	}
	if (marker.getResource() instanceof IProject) {
		// This happens with IssueCodes.NODE_MODULES_OUT_OF_SYNC
		Issue issue = getIssueUtil().createIssue(marker);
		Iterable<IssueResolution> result = resolutionProvider.getResolutions(issue);
		return getAdaptedResolutions(Lists.newArrayList(result));
	}
	return super.getResolutions(marker);
}
 
Example 20
Source File: MarkerUtil.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Find the BugCollectionAndInstance associated with given FindBugs marker.
 *
 * @param marker
 *            a FindBugs marker
 * @return the BugInstance associated with the marker, or null if we can't
 *         find the BugInstance
 */
public static @CheckForNull BugCollectionAndInstance findBugCollectionAndInstanceForMarker(IMarker marker) {

    IResource resource = marker.getResource();
    IProject project = resource.getProject();
    if (project == null) {
        // Also shouldn't happen.
        FindbugsPlugin.getDefault().logError("No project for warning marker");
        return null;
    }
    if (!isFindBugsMarker(marker)) {
        // log disabled because otherwise each selection in problems view
        // generates
        // 6 new errors (we need refactor all bug views to get rid of this).
        // FindbugsPlugin.getDefault().logError("Selected marker is not a FindBugs marker");
        // FindbugsPlugin.getDefault().logError(marker.getType());
        // FindbugsPlugin.getDefault().logError(FindBugsMarker.NAME);
        return null;
    }

    // We have a FindBugs marker. Get the corresponding BugInstance.
    String bugId = marker.getAttribute(FindBugsMarker.UNIQUE_ID, null);
    if (bugId == null) {
        FindbugsPlugin.getDefault().logError("Marker does not contain unique id for warning");
        return null;
    }

    try {
        BugCollection bugCollection = FindbugsPlugin.getBugCollection(project, null);
        if (bugCollection == null) {
            FindbugsPlugin.getDefault().logError("Could not get BugCollection for SpotBugs marker");
            return null;
        }

        String bugType = (String) marker.getAttribute(FindBugsMarker.BUG_TYPE);
        Integer primaryLineNumber = (Integer) marker.getAttribute(FindBugsMarker.PRIMARY_LINE);

        // compatibility
        if (primaryLineNumber == null) {
            primaryLineNumber = Integer.valueOf(getEditorLine(marker));
        }

        if (bugType == null) {
            FindbugsPlugin.getDefault().logError(
                    "Could not get find attributes for marker " + marker + ": (" + bugId + ", " + primaryLineNumber + ")");
            return null;
        }
        BugInstance bug = bugCollection.findBug(bugId, bugType, primaryLineNumber.intValue());
        if (bug == null) {
            FindbugsPlugin.getDefault().logError(
                    "Could not get find bug for marker on " + resource + ": (" + bugId + ", " + primaryLineNumber + ")");
            return null;
        }
        return new BugCollectionAndInstance(bugCollection, bug);
    } catch (CoreException e) {
        FindbugsPlugin.getDefault().logException(e, "Could not get BugInstance for SpotBugs marker");
        return null;
    }
}