Search in sources :

Example 21 with ISourceRange

use of org.eclipse.jdt.core.ISourceRange in project eclipse.jdt.ls by eclipse.

the class AssociativeInfixExpressionFragment method getRangeOfOperands.

private static ISourceRange getRangeOfOperands(List<Expression> operands) {
    Expression first = operands.get(0);
    Expression last = operands.get(operands.size() - 1);
    return new SourceRange(first.getStartPosition(), last.getStartPosition() + last.getLength() - first.getStartPosition());
}
Also used : InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) Expression(org.eclipse.jdt.core.dom.Expression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) ISourceRange(org.eclipse.jdt.core.ISourceRange) SourceRange(org.eclipse.jdt.core.SourceRange)

Example 22 with ISourceRange

use of org.eclipse.jdt.core.ISourceRange in project xtext-eclipse by eclipse.

the class JvmOutlineNodeElementOpener method openEObject.

@Override
protected void openEObject(EObject state) {
    try {
        if (state instanceof JvmIdentifiableElement && state.eResource() instanceof TypeResource) {
            IJavaElement javaElement = javaElementFinder.findElementFor((JvmIdentifiableElement) state);
            if (javaElement instanceof IMember) {
                IResource resource = javaElement.getResource();
                if (resource instanceof IStorage) {
                    ITrace traceToSource = traceInformation.getTraceToSource((IStorage) resource);
                    if (traceToSource != null) {
                        ISourceRange sourceRange = ((IMember) javaElement).getSourceRange();
                        ILocationInResource sourceInformation = traceToSource.getBestAssociatedLocation(new TextRegion(sourceRange.getOffset(), sourceRange.getLength()));
                        if (sourceInformation != null) {
                            globalURIEditorOpener.open(sourceInformation.getAbsoluteResourceURI().getURI(), javaElement, true);
                            return;
                        }
                    }
                }
                globalURIEditorOpener.open(null, javaElement, true);
                return;
            }
        }
    } catch (Exception exc) {
        LOG.error("Error opening java editor", exc);
    }
    super.openEObject(state);
}
Also used : IJavaElement(org.eclipse.jdt.core.IJavaElement) TypeResource(org.eclipse.xtext.common.types.access.TypeResource) JvmIdentifiableElement(org.eclipse.xtext.common.types.JvmIdentifiableElement) TextRegion(org.eclipse.xtext.util.TextRegion) ITrace(org.eclipse.xtext.generator.trace.ITrace) IStorage(org.eclipse.core.resources.IStorage) IMember(org.eclipse.jdt.core.IMember) IResource(org.eclipse.core.resources.IResource) ILocationInResource(org.eclipse.xtext.generator.trace.ILocationInResource) ISourceRange(org.eclipse.jdt.core.ISourceRange)

Example 23 with ISourceRange

use of org.eclipse.jdt.core.ISourceRange in project xtext-eclipse by eclipse.

the class JvmImplementationOpener method openImplementations.

/**
 * Main parts of the logic is taken from {@link org.eclipse.jdt.internal.ui.javaeditor.JavaElementImplementationHyperlink}
 *
 * @param element - Element to show implementations for
 * @param textviewer - Viewer to show hierarchy view on
 * @param region - Region where to show hierarchy view
 */
public void openImplementations(final IJavaElement element, ITextViewer textviewer, IRegion region) {
    if (element instanceof IMethod) {
        ITypeRoot typeRoot = ((IMethod) element).getTypeRoot();
        CompilationUnit ast = SharedASTProvider.getAST(typeRoot, SharedASTProvider.WAIT_YES, null);
        if (ast == null) {
            openQuickHierarchy(textviewer, element, region);
            return;
        }
        try {
            ISourceRange nameRange = ((IMethod) element).getNameRange();
            ASTNode node = NodeFinder.perform(ast, nameRange);
            ITypeBinding parentTypeBinding = null;
            if (node instanceof SimpleName) {
                ASTNode parent = node.getParent();
                if (parent instanceof MethodInvocation) {
                    Expression expression = ((MethodInvocation) parent).getExpression();
                    if (expression == null) {
                        parentTypeBinding = Bindings.getBindingOfParentType(node);
                    } else {
                        parentTypeBinding = expression.resolveTypeBinding();
                    }
                } else if (parent instanceof SuperMethodInvocation) {
                    // Directly go to the super method definition
                    openEditor(element);
                    return;
                } else if (parent instanceof MethodDeclaration) {
                    parentTypeBinding = Bindings.getBindingOfParentType(node);
                }
            }
            final IType type = parentTypeBinding != null ? (IType) parentTypeBinding.getJavaElement() : null;
            if (type == null) {
                openQuickHierarchy(textviewer, element, region);
                return;
            }
            final String earlyExitIndicator = "EarlyExitIndicator";
            final ArrayList<IJavaElement> links = Lists.newArrayList();
            IRunnableWithProgress runnable = new IRunnableWithProgress() {

                @Override
                public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                    if (monitor == null) {
                        monitor = new NullProgressMonitor();
                    }
                    try {
                        String methodLabel = JavaElementLabels.getElementLabel(element, JavaElementLabels.DEFAULT_QUALIFIED);
                        monitor.beginTask(Messages.format("Searching for implementors of  ''{0}''", methodLabel), 100);
                        SearchRequestor requestor = new SearchRequestor() {

                            @Override
                            public void acceptSearchMatch(SearchMatch match) throws CoreException {
                                if (match.getAccuracy() == SearchMatch.A_ACCURATE) {
                                    IJavaElement element = (IJavaElement) match.getElement();
                                    if (element instanceof IMethod && !JdtFlags.isAbstract((IMethod) element)) {
                                        links.add(element);
                                        if (links.size() > 1) {
                                            throw new OperationCanceledException(earlyExitIndicator);
                                        }
                                    }
                                }
                            }
                        };
                        int limitTo = IJavaSearchConstants.DECLARATIONS | IJavaSearchConstants.IGNORE_DECLARING_TYPE | IJavaSearchConstants.IGNORE_RETURN_TYPE;
                        SearchPattern pattern = SearchPattern.createPattern(element, limitTo);
                        Assert.isNotNull(pattern);
                        SearchParticipant[] participants = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
                        SearchEngine engine = new SearchEngine();
                        engine.search(pattern, participants, SearchEngine.createHierarchyScope(type), requestor, SubMonitor.convert(monitor, 100));
                        if (monitor.isCanceled()) {
                            throw new InterruptedException();
                        }
                    } catch (OperationCanceledException e) {
                        throw new InterruptedException(e.getMessage());
                    } catch (CoreException e) {
                        throw new InvocationTargetException(e);
                    } finally {
                        monitor.done();
                    }
                }
            };
            try {
                PlatformUI.getWorkbench().getProgressService().busyCursorWhile(runnable);
            } catch (InvocationTargetException e) {
                IStatus status = new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, Messages.format("An error occurred while searching for implementations of method ''{0}''. See error log for details.", element.getElementName()), e.getCause());
                JavaPlugin.log(status);
                ErrorDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Open Implementation", "Problems finding implementations.", status);
            } catch (InterruptedException e) {
                if (e.getMessage() != earlyExitIndicator) {
                    return;
                }
            }
            if (links.size() == 1) {
                openEditor(links.get(0));
            } else {
                openQuickHierarchy(textviewer, element, region);
            }
        } catch (JavaModelException e) {
            log.error("An error occurred while searching for implementations", e.getCause());
        } catch (PartInitException e) {
            log.error("An error occurred while searching for implementations", e.getCause());
        }
    }
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IStatus(org.eclipse.core.runtime.IStatus) JavaModelException(org.eclipse.jdt.core.JavaModelException) SimpleName(org.eclipse.jdt.core.dom.SimpleName) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) IType(org.eclipse.jdt.core.IType) IRunnableWithProgress(org.eclipse.jface.operation.IRunnableWithProgress) SearchParticipant(org.eclipse.jdt.core.search.SearchParticipant) SearchEngine(org.eclipse.jdt.core.search.SearchEngine) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) SearchPattern(org.eclipse.jdt.core.search.SearchPattern) IMethod(org.eclipse.jdt.core.IMethod) PartInitException(org.eclipse.ui.PartInitException) ISourceRange(org.eclipse.jdt.core.ISourceRange) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) IJavaElement(org.eclipse.jdt.core.IJavaElement) SearchMatch(org.eclipse.jdt.core.search.SearchMatch) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ITypeRoot(org.eclipse.jdt.core.ITypeRoot) InvocationTargetException(java.lang.reflect.InvocationTargetException) SearchRequestor(org.eclipse.jdt.core.search.SearchRequestor) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) CoreException(org.eclipse.core.runtime.CoreException) Expression(org.eclipse.jdt.core.dom.Expression)

Example 24 with ISourceRange

use of org.eclipse.jdt.core.ISourceRange in project bndtools by bndtools.

the class BaselineErrorHandler method generatePackageInfoMarkers.

List<MarkerData> generatePackageInfoMarkers(Info baselineInfo, IJavaProject javaProject, String message) throws JavaModelException {
    List<MarkerData> markers = new LinkedList<>();
    for (IClasspathEntry entry : javaProject.getRawClasspath()) {
        if (IClasspathEntry.CPE_SOURCE == entry.getEntryKind()) {
            IPath entryPath = entry.getPath();
            IPath pkgPath = entryPath.append(baselineInfo.packageName.replace('.', '/'));
            // Find in packageinfo file
            IPath pkgInfoPath = pkgPath.append(PACKAGEINFO);
            IFile pkgInfoFile = javaProject.getProject().getWorkspace().getRoot().getFile(pkgInfoPath);
            if (pkgInfoFile != null && pkgInfoFile.exists()) {
                Map<String, Object> attribs = new HashMap<String, Object>();
                attribs.put(IMarker.MESSAGE, message.trim());
                attribs.put(PROP_SUGGESTED_VERSION, baselineInfo.suggestedVersion.toString());
                LineLocation lineLoc = findVersionLocation(pkgInfoFile.getLocation().toFile());
                if (lineLoc != null) {
                    attribs.put(IMarker.LINE_NUMBER, lineLoc.lineNum);
                    attribs.put(IMarker.CHAR_START, lineLoc.start);
                    attribs.put(IMarker.CHAR_END, lineLoc.end);
                }
                markers.add(new MarkerData(pkgInfoFile, attribs, true));
            }
            // Find in package-info.java
            IPackageFragment pkg = javaProject.findPackageFragment(pkgPath);
            if (pkg != null) {
                ICompilationUnit pkgInfoJava = pkg.getCompilationUnit(PACKAGEINFOJAVA);
                if (pkgInfoJava != null && pkgInfoJava.exists()) {
                    ISourceRange range = findPackageInfoJavaVersionLocation(baselineInfo.packageName, pkgInfoJava);
                    Map<String, Object> attribs = new HashMap<String, Object>();
                    attribs.put(IMarker.MESSAGE, message.trim());
                    attribs.put(IJavaModelMarker.ID, 8088);
                    attribs.put(PROP_SUGGESTED_VERSION, baselineInfo.suggestedVersion.toString());
                    if (range != null) {
                        attribs.put(IMarker.CHAR_START, range.getOffset());
                        attribs.put(IMarker.CHAR_END, range.getOffset() + range.getLength());
                        markers.add(new MarkerData(pkgInfoJava.getResource(), attribs, true, BndtoolsConstants.MARKER_JAVA_BASELINE));
                    }
                }
            }
        }
    }
    return markers;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) MarkerData(org.bndtools.build.api.MarkerData) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) IFile(org.eclipse.core.resources.IFile) IPath(org.eclipse.core.runtime.IPath) IClasspathEntry(org.eclipse.jdt.core.IClasspathEntry) HashMap(java.util.HashMap) LinkedList(java.util.LinkedList) ISourceRange(org.eclipse.jdt.core.ISourceRange)

Example 25 with ISourceRange

use of org.eclipse.jdt.core.ISourceRange in project flux by eclipse.

the class JavaDocService method getJavadocFromSourceElement.

public String getJavadocFromSourceElement(IMember member) {
    JavaDocCommentReader reader = null;
    try {
        IBuffer buffer = member.getOpenable().getBuffer();
        if (buffer == null) {
            return null;
        }
        ISourceRange javadocRange = member.getJavadocRange();
        if (javadocRange != null) {
            reader = new JavaDocCommentReader(buffer, javadocRange.getOffset(), javadocRange.getOffset() + javadocRange.getLength() - 1);
            StringBuffer buf = new StringBuffer();
            char[] charBuffer = new char[1024];
            int count;
            try {
                while ((count = reader.read(charBuffer)) != -1) buf.append(charBuffer, 0, count);
            } catch (IOException e) {
                return null;
            }
            return buf.toString();
        }
    } catch (JavaModelException e) {
        e.printStackTrace();
    } finally {
        if (reader != null)
            reader.close();
    }
    return null;
}
Also used : JavaModelException(org.eclipse.jdt.core.JavaModelException) IOException(java.io.IOException) IBuffer(org.eclipse.jdt.core.IBuffer) ISourceRange(org.eclipse.jdt.core.ISourceRange)

Aggregations

ISourceRange (org.eclipse.jdt.core.ISourceRange)53 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)18 IJavaElement (org.eclipse.jdt.core.IJavaElement)14 JavaModelException (org.eclipse.jdt.core.JavaModelException)13 ASTNode (org.eclipse.jdt.core.dom.ASTNode)12 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)10 ISourceReference (org.eclipse.jdt.core.ISourceReference)9 IType (org.eclipse.jdt.core.IType)8 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)7 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)6 SourceRange (org.eclipse.jdt.core.SourceRange)6 IBuffer (org.eclipse.jdt.core.IBuffer)5 IMethod (org.eclipse.jdt.core.IMethod)5 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)5 RefactoringStatus (org.eclipse.ltk.core.refactoring.RefactoringStatus)5 ArrayList (java.util.ArrayList)4 IField (org.eclipse.jdt.core.IField)4 IMember (org.eclipse.jdt.core.IMember)4 CoreException (org.eclipse.core.runtime.CoreException)3 IClassFile (org.eclipse.jdt.core.IClassFile)3