/** * Find methods calling method 'm' */ public static HashSet<IMethod> getCallersOf(IMethod m) { CallHierarchy callHierarchy = CallHierarchy.getDefault(); IMember[] members = { m }; MethodWrapper[] methodWrappers = callHierarchy.getCallerRoots(members); HashSet<IMethod> callers = new HashSet<IMethod>(); for (MethodWrapper mw : methodWrappers) { MethodWrapper[] mw2 = mw.getCalls(new NullProgressMonitor()); HashSet<IMethod> temp = getIMethods(mw2); callers.addAll(temp); } return callers; }
/** * Find calling sites for method 'm' */ public static HashSet<CallLocation> getCallLocationsOf(IMethod m) { CallHierarchy callHierarchy = CallHierarchy.getDefault(); IMember[] members = { m }; MethodWrapper[] methodWrappers = callHierarchy.getCallerRoots(members); HashSet<CallLocation> callers = new HashSet<CallLocation>(); for (MethodWrapper mw : methodWrappers) { MethodWrapper[] mw2 = mw.getCalls(new NullProgressMonitor()); HashSet<CallLocation> temp = getCallLocations(mw2); callers.addAll(temp); } return callers; }
private void processType(ITypeVisitor visitor, BinaryTypeName btn, IType type, IProgressMonitor monitor) throws JavaModelException { final String binaryname = btn.toString(); monitor.subTask(binaryname); visitor.visit(type, binaryname); for (final IJavaElement child : type.getChildren()) { if (monitor.isCanceled()) { break; } switch (child.getElementType()) { case IJavaElement.TYPE: IType nestedtype = (IType) child; processType(visitor, btn.nest(nestedtype), nestedtype, monitor); break; case IJavaElement.METHOD: case IJavaElement.INITIALIZER: case IJavaElement.FIELD: processAnonymousInnerTypes(visitor, btn, (IMember) child, monitor); break; } } }
private static ISourceRange getNameRange(IJavaElement element) throws JavaModelException { ISourceRange nameRange = null; if (element instanceof IMember) { IMember member = (IMember) element; nameRange = member.getNameRange(); if ( (!SourceRange.isAvailable(nameRange))) { nameRange = member.getSourceRange(); } } else if (element instanceof ITypeParameter || element instanceof ILocalVariable) { nameRange = ((ISourceReference) element).getNameRange(); } else if (element instanceof ISourceReference) { nameRange = ((ISourceReference) element).getSourceRange(); } if (!SourceRange.isAvailable(nameRange) && element.getParent() != null) { nameRange = getNameRange(element.getParent()); } return nameRange; }
/** * Evaluates the insertion position of a new node. * * @param listRewrite The list rewriter to which the new node will be added * @param sibling The Java element before which the new element should be added. * @return the AST node of the list to insert before or null to insert as last. * @throws JavaModelException thrown if accessing the Java element failed */ public static ASTNode getNodeToInsertBefore(ListRewrite listRewrite, IJavaElement sibling) throws JavaModelException { if (sibling instanceof IMember) { ISourceRange sourceRange= ((IMember) sibling).getSourceRange(); if (sourceRange == null) { return null; } int insertPos= sourceRange.getOffset(); List<? extends ASTNode> members= listRewrite.getOriginalList(); for (int i= 0; i < members.size(); i++) { ASTNode curr= members.get(i); if (curr.getStartPosition() >= insertPos) { return curr; } } } return null; }
private void uniteWithSupertypes(IType anchor, IType type) throws JavaModelException { IType[] supertypes = fHierarchy.getSupertypes(type); for (int i = 0; i < supertypes.length; i++) { IType supertype = supertypes[i]; IType superRep = fUnionFind.find(supertype); if (superRep == null) { //Type doesn't declare method, but maybe supertypes? uniteWithSupertypes(anchor, supertype); } else { //check whether method in supertype is really overridden: IMember superMethod = fTypeToMethod.get(supertype); if (JavaModelUtil.isVisibleInHierarchy(superMethod, anchor.getPackageFragment())) { IType rep = fUnionFind.find(anchor); fUnionFind.union(rep, superRep); // current type is no root anymore fRootTypes.remove(anchor); uniteWithSupertypes(supertype, supertype); } else { //Not overridden -> overriding chain ends here. } } } }
/** * Appends the styled label for a type parameter. * * @param typeParameter the element to render * @param flags the rendering flags. Flags with names starting with 'T_' are considered. */ public void appendTypeParameterLabel(ITypeParameter typeParameter, long flags) { try { appendTypeParameterWithBounds(typeParameter, flags); // post qualification if (getFlag(flags, JavaElementLabels.TP_POST_QUALIFIED)) { fBuilder.append(JavaElementLabels.CONCAT_STRING); IMember declaringMember= typeParameter.getDeclaringMember(); appendElementLabel(declaringMember, JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.M_FULLY_QUALIFIED | JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS)); } } catch (JavaModelException e) { JavaLanguageServerPlugin.logException("", e); // NotExistsException will not reach this point } }
/** * Gets a reader for an IMember's Javadoc comment content from the source attachment. * The content does contain only the text from the comment without the Javadoc leading star characters. * Returns <code>null</code> if the member does not contain a Javadoc comment or if no source is available. * @param member The member to get the Javadoc of. * @return Returns a reader for the Javadoc comment content or <code>null</code> if the member * does not contain a Javadoc comment or if no source is available * @throws JavaModelException is thrown when the elements javadoc can not be accessed * @since 3.4 */ private static Reader internalGetContentReader(IMember member) throws JavaModelException { IBuffer buf= member.getOpenable().getBuffer(); if (buf == null) { return null; // no source attachment found } ISourceRange javadocRange= member.getJavadocRange(); if (javadocRange != null) { JavaDocCommentReader reader= new JavaDocCommentReader(buf, javadocRange.getOffset(), javadocRange.getOffset() + javadocRange.getLength() - 1); if (!containsOnlyInheritDoc(reader, javadocRange.getLength())) { reader.reset(); return reader; } } return null; }
private static boolean isAvailable(IJavaElement javaElement) throws JavaModelException { if (javaElement == null) { return false; } if (!javaElement.exists()) { return false; } if (javaElement.isReadOnly()) { return false; } // work around for https://bugs.eclipse.org/bugs/show_bug.cgi?id=48422 // the Java project is now cheating regarding its children so we shouldn't // call isStructureKnown if the project isn't open. // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=52474 if (!(javaElement instanceof IJavaProject) && !(javaElement instanceof ILocalVariable) && !javaElement.isStructureKnown()) { return false; } if (javaElement instanceof IMember && ((IMember) javaElement).isBinary()) { return false; } return true; }
private Location computeDefinitionNavigation(ITypeRoot unit, int line, int column, IProgressMonitor monitor) { try { IJavaElement element = JDTUtils.findElementAtSelection(unit, line, column, this.preferenceManager, monitor); if (element == null) { return null; } ICompilationUnit compilationUnit = (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT); IClassFile cf = (IClassFile) element.getAncestor(IJavaElement.CLASS_FILE); if (compilationUnit != null || (cf != null && cf.getSourceRange() != null) ) { return JDTUtils.toLocation(element); } if (element instanceof IMember && ((IMember) element).getClassFile() != null) { return JDTUtils.toLocation(((IMember) element).getClassFile()); } } catch (JavaModelException e) { JavaLanguageServerPlugin.logException("Problem computing definition for" + unit.getElementName(), e); } return null; }
@Override public JavaTypeMemberBookmarkLocation getBookmarkLocation(Bookmark bookmark, IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor, 100); List<IMember> memberCandidates = getMemberCandidates(bookmark, subMonitor.newChild(30)); for (IMember member : memberCandidates) { LinePosition linePosition = getLineNumber(member, bookmark, subMonitor.newChild(70)); if (linePosition != null) { return new JavaTypeMemberBookmarkLocation(member, linePosition.lineNumber, linePosition.lineOffset); } } if (memberCandidates.isEmpty()) { return null; } else { return new JavaTypeMemberBookmarkLocation(memberCandidates.get(0), null, null); } }
private List<IMember> getMemberCandidates(IType type, Bookmark javaBookmark) { String elementKind = javaBookmark.getPropertyValue(PROP_JAVA_ELEMENT_KIND); String elementName = javaBookmark.getPropertyValue(PROP_JAVA_ELEMENT_NAME); if (KIND_FIELD.equals(elementKind)) { IField field = type.getField(elementName); return field.exists() ? Lists.newArrayList(field) : Collections.emptyList(); } if (KIND_METHOD.equals(elementKind)) { String signature = javaBookmark.getPropertyValue(PROP_JAVA_METHOD_SIGNATURE); IMethod method = null; if (signature != null) { method = getMethod(type, elementName, signature); } if (method == null) { List<IMethod> candidates = getMethodsWithName(type, elementName); return Lists.newArrayList(candidates); } return Lists.newArrayList(method); } if (JavaEditorUtils.isType(elementKind) && elementName != null) { IType memberType = type.getType(elementName); return memberType.exists() ? Lists.newArrayList(memberType) : Collections.emptyList(); } return Collections.emptyList(); }
protected void addMemberBookmarkProperties(Map<String, String> bookmarkProperties, IMember member) { putIfAbsent(bookmarkProperties, PROP_JAVA_ELEMENT_NAME, member.getElementName()); if (member.getDeclaringType() != null) { putIfAbsent(bookmarkProperties, PROP_JAVA_DECLARING_TYPE, member.getDeclaringType().getFullyQualifiedName()); } putIfAbsent(bookmarkProperties, PROP_JAVA_ELEMENT_KIND, getKind(member)); if (member instanceof IMethod) { putIfAbsent(bookmarkProperties, PROP_JAVA_METHOD_SIGNATURE, JavaEditorUtils.getMethodSimpleSignature((IMethod) member)); putIfAbsent(bookmarkProperties, Bookmark.PROPERTY_NAME, bookmarkProperties.get(PROP_JAVA_DECLARING_TYPE) + '.' + member.getElementName() + "()"); } if (member instanceof IType) { IType type = (IType) member; putIfAbsent(bookmarkProperties, PROP_JAVA_TYPE, type.getFullyQualifiedName()); putIfAbsent(bookmarkProperties, Bookmark.PROPERTY_NAME, type.getFullyQualifiedName()); } if (member instanceof IField) { putIfAbsent(bookmarkProperties, Bookmark.PROPERTY_NAME, bookmarkProperties.get(PROP_JAVA_DECLARING_TYPE) + '.' + member.getElementName()); } putIfAbsent(bookmarkProperties, Bookmark.PROPERTY_NAME, member.getElementName()); }
private String getJavadocCommentAsText(IMember member) { try (Reader reader = JavadocContentAccess.getHTMLContentReader(member, true, true)) { if (reader == null) { return null; } String javadocAsHtml = CharStreams.toString(reader); String javadocAsString = Jsoup.clean(javadocAsHtml, "", Whitelist.none(), new OutputSettings().prettyPrint(false)); // trim lines try (BufferedReader bufferedReader = new BufferedReader(new StringReader(javadocAsString))) { return bufferedReader.lines().map(line->line.trim()).collect(Collectors.joining("\n")); } } catch (JavaModelException | IOException e) { return null; } }
public static Integer getLineNumber(IMember member) throws JavaModelException { ITypeRoot typeRoot = member.getTypeRoot(); IBuffer buffer = typeRoot.getBuffer(); if (buffer == null) { return null; } Document document = new Document(buffer.getContents()); int offset = 0; if (SourceRange.isAvailable(member.getNameRange())) { offset = member.getNameRange().getOffset(); } else if (SourceRange.isAvailable(member.getSourceRange())) { offset = member.getSourceRange().getOffset(); } try { return document.getLineOfOffset(offset); } catch (BadLocationException e) { return null; } }
private List sortKeys(Map operations, final String currentType) { ArrayList<IMember> keys = new ArrayList<IMember>(operations.keySet()); Collections.sort(keys, new Comparator<IMember>() { @Override public int compare(IMember m1, IMember m2) { String t1 = m1.getDeclaringType().getElementName(); String t2 = m2.getDeclaringType().getElementName(); if (t1.equals(t2)) return 0; if (t1.equals(currentType)) return -1; if (t2.equals(currentType)) return 1; return t1.compareTo(t2); } }); return keys; }
/** * Gets a reader for an IMember's Javadoc comment content from the source attachment. and renders * the tags in HTML. Returns <code>null</code> if the member does not contain a Javadoc comment or * if no source is available. * * @param member the member to get the Javadoc of. * @param allowInherited for methods with no (Javadoc) comment, the comment of the overridden * class is returned if <code>allowInherited</code> is <code>true</code> * @param useAttachedJavadoc if <code>true</code> Javadoc will be extracted from attached Javadoc * if there's no source * @return a reader for the Javadoc comment content in HTML or <code>null</code> if the member * does not contain a Javadoc comment or if no source is available * @throws org.eclipse.jdt.core.JavaModelException is thrown when the elements Javadoc can not be * accessed * @since 3.2 */ public static Reader getHTMLContentReader( IMember member, boolean allowInherited, boolean useAttachedJavadoc) throws JavaModelException { Reader contentReader = internalGetContentReader(member); if (contentReader != null) return new JavaDoc2HTMLTextReader(contentReader); if (useAttachedJavadoc && member.getOpenable().getBuffer() == null) { // only if no source available String s = member.getAttachedJavadoc(null); if (s != null) return new StringReader(s); } if (allowInherited && (member.getElementType() == IJavaElement.METHOD)) return findDocInHierarchy((IMethod) member, true, useAttachedJavadoc); return null; }
private RefactoringStatus checkAccessedTypes(IMethod sourceMethod, final Optional<IProgressMonitor> monitor, final ITypeHierarchy hierarchy) throws JavaModelException { final RefactoringStatus result = new RefactoringStatus(); final IType[] accessedTypes = getTypesReferencedInMovedMembers(sourceMethod, monitor); final IType destination = getDestinationInterface(sourceMethod).get(); final List<IMember> pulledUpList = Arrays.asList(sourceMethod); for (IType type : accessedTypes) { if (!type.exists()) continue; if (!canBeAccessedFrom(sourceMethod, type, destination, hierarchy) && !pulledUpList.contains(type)) { final String message = org.eclipse.jdt.internal.corext.util.Messages.format( PreconditionFailure.TypeNotAccessible.getMessage(), new String[] { JavaElementLabels.getTextLabel(type, JavaElementLabels.ALL_FULLY_QUALIFIED), JavaElementLabels.getTextLabel(destination, JavaElementLabels.ALL_FULLY_QUALIFIED) }); result.addEntry(RefactoringStatus.ERROR, message, JavaStatusContext.create(type), MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID, PreconditionFailure.TypeNotAccessible.ordinal(), sourceMethod); this.getUnmigratableMethods().add(sourceMethod); } } monitor.ifPresent(IProgressMonitor::done); return result; }
public static boolean isPushDownAvailable(final IMember member) throws JavaModelException { if (!member.exists()) return false; final int type = member.getElementType(); if (type != IJavaElement.METHOD && type != IJavaElement.FIELD) return false; if (JdtFlags.isEnum(member)) return false; if (!Checks.isAvailable(member)) return false; if (JdtFlags.isStatic(member)) return false; if (type == IJavaElement.METHOD) { final IMethod method = (IMethod) member; if (method.isConstructor()) return false; if (JdtFlags.isNative(method)) return false; final IType declaring = method.getDeclaringType(); if (declaring != null && declaring.isAnnotation()) return false; } return true; }
private RenameWizard getWizardType(IJavaElement element) throws JavaModelException { switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT: return RenameWizard.PACKAGE; case IJavaElement.COMPILATION_UNIT: return RenameWizard.COMPILATION_UNIT; case IJavaElement.TYPE: return RenameWizard.TYPE; case IJavaElement.METHOD: final IMethod method = (IMethod) element; if (method.isConstructor()) return RenameWizard.TYPE; else return RenameWizard.METHOD; case IJavaElement.FIELD: if (JdtFlags.isEnum((IMember) element)) { return RenameWizard.ENUM_CONSTANT; } return RenameWizard.FIELD; case IJavaElement.TYPE_PARAMETER: return RenameWizard.TYPE_PARAMETER; case IJavaElement.LOCAL_VARIABLE: return RenameWizard.LOCAL_VARIABLE; } return null; }
/** * Evaluates if a member (possible from another package) is visible from elements in a package. * * @param member The member to test the visibility for * @param pack The package in focus * @return returns <code>true</code> if the member is visible from the package * @throws JavaModelException thrown when the member can not be accessed */ public static boolean isVisible(IMember member, IPackageFragment pack) throws JavaModelException { int type = member.getElementType(); if (type == IJavaElement.INITIALIZER || (type == IJavaElement.METHOD && member.getElementName().startsWith("<"))) { // $NON-NLS-1$ return false; } int otherflags = member.getFlags(); IType declaringType = member.getDeclaringType(); if (Flags.isPublic(otherflags) || (declaringType != null && isInterfaceOrAnnotation(declaringType))) { return true; } else if (Flags.isPrivate(otherflags)) { return false; } IPackageFragment otherpack = (IPackageFragment) member.getAncestor(IJavaElement.PACKAGE_FRAGMENT); return (pack != null && otherpack != null && isSamePackage(pack, otherpack)); }
/** * Extracts the Javadoc for the given Java element and returns it as HTML. * * @param element the Java element to get the documentation for * @return the Javadoc for Java element or <code>null</code> if the Javadoc is not available * @throws org.eclipse.core.runtime.CoreException if fetching the Javadoc for the given element * failed connected */ private String extractJavadoc(IJavaElement element) throws CoreException { if (element instanceof IMember) { return JavadocContentAccess2.getHTMLContent( (IMember) element, true, UrlContextProvider.get(element.getJavaProject().getPath().toString())); } else if (element instanceof IPackageDeclaration) { return JavadocContentAccess2.getHTMLContent( (IPackageDeclaration) element, UrlContextProvider.get(element.getJavaProject().getPath().toString())); } else if (element instanceof IPackageFragment) { return JavadocContentAccess2.getHTMLContent( (IPackageFragment) element, UrlContextProvider.get(element.getJavaProject().getPath().toString())); } return null; }
/** * Evaluates the insertion position of a new node. * * @param listRewrite The list rewriter to which the new node will be added * @param sibling The Java element before which the new element should be added. * @return the AST node of the list to insert before or null to insert as last. * @throws JavaModelException thrown if accessing the Java element failed */ public static ASTNode getNodeToInsertBefore(ListRewrite listRewrite, IJavaElement sibling) throws JavaModelException { if (sibling instanceof IMember) { ISourceRange sourceRange = ((IMember) sibling).getSourceRange(); if (sourceRange == null) { return null; } int insertPos = sourceRange.getOffset(); List<? extends ASTNode> members = listRewrite.getOriginalList(); for (int i = 0; i < members.size(); i++) { ASTNode curr = members.get(i); if (curr.getStartPosition() >= insertPos) { return curr; } } } return null; }
private void addAdjustment( IMember whoToAdjust, ModifierKeyword neededVisibility, Map<IMember, IncomingMemberVisibilityAdjustment> adjustments) throws JavaModelException { ModifierKeyword currentVisibility = ModifierKeyword.fromFlagValue(JdtFlags.getVisibilityCode(whoToAdjust)); if (MemberVisibilityAdjustor.hasLowerVisibility(currentVisibility, neededVisibility) && MemberVisibilityAdjustor.needsVisibilityAdjustments( whoToAdjust, neededVisibility, adjustments)) adjustments.put( whoToAdjust, new MemberVisibilityAdjustor.IncomingMemberVisibilityAdjustment( whoToAdjust, neededVisibility, RefactoringStatus.createWarningStatus( Messages.format( MemberVisibilityAdjustor.getMessage(whoToAdjust), new String[] { MemberVisibilityAdjustor.getLabel(whoToAdjust), MemberVisibilityAdjustor.getLabel(neededVisibility) }), JavaStatusContext.create(whoToAdjust)))); }
private static String getHTMLContentFromSource(IMember member, String urlPrefix) throws JavaModelException { IBuffer buf = member.getOpenable().getBuffer(); if (buf == null) { return null; // no source attachment found } ISourceRange javadocRange = member.getJavadocRange(); if (javadocRange == null) { if (canInheritJavadoc(member)) { // Try to use the inheritDoc algorithm. String inheritedJavadoc = javadoc2HTML(member, "/***/", urlPrefix); // $NON-NLS-1$ if (inheritedJavadoc != null && inheritedJavadoc.length() > 0) { return inheritedJavadoc; } } return null; // getJavaFxPropertyDoc(member); } String rawJavadoc = buf.getText(javadocRange.getOffset(), javadocRange.getLength()); return javadoc2HTML(member, rawJavadoc, urlPrefix); }
private void adjustOutgoingVisibilityChain(final IMember member, final IProgressMonitor monitor) throws JavaModelException { if (!Modifier.isPublic(member.getFlags())) { final ModifierKeyword threshold = computeOutgoingVisibilityThreshold(fReferencing, member, monitor); if (member instanceof IMethod) { adjustOutgoingVisibility( member, threshold, RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_method_warning); } else if (member instanceof IField) { adjustOutgoingVisibility((IField) member, threshold); } else if (member instanceof IType) { adjustOutgoingVisibility( member, threshold, RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_type_warning); } } if (member.getDeclaringType() != null) adjustOutgoingVisibilityChain(member.getDeclaringType(), monitor); }
/** * Searches the given source range of the container for a member that is not the same as the given * type. * * @param type the {@link IType} * @param start the starting position * @param end the ending position * @return the {@link IMember} from the given start-end range * @throws JavaModelException if there is a problem with the backing Java model */ @Nullable private IMember binSearch(IType type, int start, int end) throws JavaModelException { IJavaElement je = getElementAt(type, start); if (je != null && !je.equals(type)) { return asMember(je); } if (end > start) { je = getElementAt(type, end); if (je != null && !je.equals(type)) { return asMember(je); } int mid = ((end - start) / 2) + start; if (mid > start) { je = binSearch(type, start + 1, mid); if (je == null) { je = binSearch(type, mid + 1, end - 1); } return asMember(je); } } return null; }
/** * Resolves the member described by the receiver and returns it if found. Returns <code>null * </code> if no corresponding member can be found. * * @return the resolved member or <code>null</code> if none is found * @throws org.eclipse.jdt.core.JavaModelException if accessing the java model fails */ @Override protected IMember resolveMember() throws JavaModelException { char[] declarationSignature = fProposal.getDeclarationSignature(); String typeName = SignatureUtil.stripSignatureToFQN(String.valueOf(declarationSignature)); IType type = fJavaProject.findType(typeName); if (type != null) { String name = String.valueOf(fProposal.getName()); String[] parameters = Signature.getParameterTypes( String.valueOf(SignatureUtil.fix83600(fProposal.getSignature()))); for (int i = 0; i < parameters.length; i++) { parameters[i] = SignatureUtil.getLowerBound(parameters[i]); } boolean isConstructor = fProposal.isConstructor(); return findMethod(name, parameters, isConstructor, type); } return null; }
/** * Evaluates if a member in the focus' element hierarchy is visible from elements in a package. * * @param member The member to test the visibility for * @param pack The package of the focus element focus * @return returns <code>true</code> if the member is visible from the package * @throws JavaModelException thrown when the member can not be accessed */ public static boolean isVisibleInHierarchy(IMember member, IPackageFragment pack) throws JavaModelException { int type = member.getElementType(); if (type == IJavaElement.INITIALIZER || (type == IJavaElement.METHOD && member.getElementName().startsWith("<"))) { // $NON-NLS-1$ return false; } int otherflags = member.getFlags(); IType declaringType = member.getDeclaringType(); if (Flags.isPublic(otherflags) || Flags.isProtected(otherflags) || (declaringType != null && isInterfaceOrAnnotation(declaringType))) { return true; } else if (Flags.isPrivate(otherflags)) { return false; } IPackageFragment otherpack = (IPackageFragment) member.getAncestor(IJavaElement.PACKAGE_FRAGMENT); return (pack != null && pack.equals(otherpack)); }
public static boolean isDeleteAvailable(final IJavaElement element) { if (!element.exists()) return false; if (element instanceof IJavaModel || element instanceof IJavaProject) return false; if (element.getParent() != null && element.getParent().isReadOnly()) return false; if (element instanceof IPackageFragmentRoot) { IPackageFragmentRoot root = (IPackageFragmentRoot) element; if (root.isExternal() || Checks.isClasspathDelete(root)) // TODO: rename isClasspathDelete return false; if (root.getResource().equals(root.getJavaProject().getProject())) return false; } if (element.getResource() == null && !RefactoringAvailabilityTester.isWorkingCopyElement(element)) return false; if (element instanceof IMember && ((IMember) element).isBinary()) return false; return true; }
public static boolean isExtractSupertypeAvailable(final IStructuredSelection selection) throws JavaModelException { if (!selection.isEmpty()) { if (selection.size() == 1) { if (selection.getFirstElement() instanceof ICompilationUnit) return true; // Do not force opening final IType type = getSingleSelectedType(selection); if (type != null) return Checks.isAvailable(type) && isExtractSupertypeAvailable(new IType[] {type}); } for (final Iterator<?> iterator = selection.iterator(); iterator.hasNext(); ) { if (!(iterator.next() instanceof IMember)) return false; } final Set<IMember> members = new HashSet<IMember>(); @SuppressWarnings("unchecked") List<IMember> selectionList = (List<IMember>) (List<?>) Arrays.asList(selection.toArray()); members.addAll(selectionList); return isExtractSupertypeAvailable(members.toArray(new IMember[members.size()])); } return false; }
public static boolean isMoveStaticAvailable(final IMember member) throws JavaModelException { if (!member.exists()) return false; final int type = member.getElementType(); if (type != IJavaElement.METHOD && type != IJavaElement.FIELD && type != IJavaElement.TYPE) return false; if (JdtFlags.isEnum(member) && type != IJavaElement.TYPE) return false; final IType declaring = member.getDeclaringType(); if (declaring == null) return false; if (!Checks.isAvailable(member)) return false; if (type == IJavaElement.METHOD && declaring.isInterface()) { boolean is18OrHigher = JavaModelUtil.is18OrHigher(member.getJavaProject()); if (!is18OrHigher || !Flags.isStatic(member.getFlags())) return false; } if (type == IJavaElement.METHOD && !JdtFlags.isStatic(member)) return false; if (type == IJavaElement.METHOD && ((IMethod) member).isConstructor()) return false; if (type == IJavaElement.TYPE && !JdtFlags.isStatic(member)) return false; if (!declaring.isInterface() && !JdtFlags.isStatic(member)) return false; return true; }
private static IMethod getIMethodFromMethodWrapper(MethodWrapper m) { try { IMember im = m.getMember(); if (im.getElementType() == IJavaElement.METHOD) { return (IMethod) m.getMember(); } } catch (Exception e) { e.printStackTrace(); } return null; }
static boolean isVisibleMember(IMember member) throws JavaModelException { int f = member.getFlags(); IType jType = member.getDeclaringType(); return jType.getPackageFragment().isDefaultPackage() && (Flags.isPackageDefault(f) || Flags.isProtected(f) || Flags.isPublic(f)) || Flags.isPublic(f); }
private void processAnonymousInnerTypes(ITypeVisitor visitor, BinaryTypeName btn, IMember member, IProgressMonitor monitor) throws JavaModelException { for (final IJavaElement element : member.getChildren()) { if (monitor.isCanceled()) { break; } if (element.getElementType() == IJavaElement.TYPE) { final IType type = (IType) element; processType(visitor, btn.nest(type), type, monitor); } } }
private boolean isSyntheticElement(IJavaElement element) { if (!(element instanceof IMember)) { return false; } IMember member= (IMember)element; if (!(member.isBinary())) { return false; } try { return Flags.isSynthetic(member.getFlags()); } catch (JavaModelException e) { return false; } }
private LinePosition getLineNumber(IMember member, Bookmark bookmark, IProgressMonitor monitor) { Integer estimatedLineNumber = getEstimatedLineNumber(member, bookmark); Integer lineNumber = estimatedLineNumber; Integer lineOffset = null; String lineContent = bookmark.getPropertyValue(TextEditorBookmarkProperties.PROP_LINE_CONTENT); try { ITypeRoot typeRoot = member.getTypeRoot(); if (typeRoot.getBuffer() == null) { return null; } Document document = new Document(typeRoot.getBuffer().getContents()); if (lineContent != null) { DocumentFuzzySearcher searcher = new DocumentFuzzySearcher(document); int foundLineNumber = searcher.findLineNumber(getRegion(member.getSourceRange()), estimatedLineNumber == null ? -1 : estimatedLineNumber, lineContent, monitor); lineNumber = foundLineNumber == -1 ? estimatedLineNumber : foundLineNumber; } if (lineNumber == null) { return null; } lineOffset = getLineOffset(document, lineNumber); if (lineOffset == null) { return null; } return new LinePosition(lineNumber, lineOffset); } catch (JavaModelException e) { return null; } }
private Integer getEstimatedLineNumber(IMember member, Bookmark bookmark) { try { Integer lineNumber = JavaEditorUtils.getLineNumber(member); if (lineNumber == null) { return null; } Integer lineNumberInsideElement = getLineNumberInsideElement(bookmark); if (lineNumberInsideElement != null) { lineNumber += lineNumberInsideElement; } return lineNumber; } catch (JavaModelException e) { return null; } }
private List<IMember> getMemberCandidates(Bookmark javaBookmark, IProgressMonitor monitor) { String type = javaBookmark.getPropertyValue(PROP_JAVA_TYPE); if (type != null) { List<IType> matchingTypes = searchType(type, monitor); return Lists.newArrayList(matchingTypes); } String declaringType = javaBookmark.getPropertyValue(PROP_JAVA_DECLARING_TYPE); if (declaringType == null) { return Collections.emptyList(); } List<IMember> matchingMembers = searchType(declaringType, monitor).stream() .flatMap(matchingType -> getMemberCandidates(matchingType, javaBookmark).stream()) .collect(Collectors.toList()); return matchingMembers; }
@Override public void addBookmarkProperties(Map<String, String> bookmarkProperties, IWorkbenchPart part, ISelection selection, IProgressMonitor monitor) { Object selected = getFirstElement(selection); if (selected instanceof ITypeRoot) { selected = ((ITypeRoot) selected).findPrimaryType(); } if (!(selected instanceof IMember)) { return; } IMember member = (IMember) selected; addMemberBookmarkProperties(bookmarkProperties, member); }