private static String[] getParameterTypesAsStringArray(IMethod method) { Set<String> typeParameterNames = new HashSet<String>(); try { for (ITypeParameter param : method.getDeclaringType().getTypeParameters()) { typeParameterNames.add(param.getElementName()); } for (ITypeParameter param : method.getTypeParameters()) { typeParameterNames.add(param.getElementName()); } } catch (JavaModelException e) { } String[] parameterTypesAsString = new String[method.getParameterTypes().length]; for (int i = 0; i < method.getParameterTypes().length; i++) { String parameterTypeString = Signature.getElementType(method.getParameterTypes()[i]); boolean isArray = !parameterTypeString.equals(method.getParameterTypes()[i]); String parameterType = resolveClassNameBySignature(parameterTypeString, method.getDeclaringType()); if (typeParameterNames.contains(parameterType)) { parameterTypesAsString[i] = Object.class.getName() + (isArray ? ClassUtils.ARRAY_SUFFIX : ""); } else { parameterTypesAsString[i] = parameterType + (isArray ? ClassUtils.ARRAY_SUFFIX : ""); } } return parameterTypesAsString; }
private RefactoringStatus checkRelatedMethods() throws CoreException { RefactoringStatus result = new RefactoringStatus(); for (Iterator<IMethod> iter = fMethodsToRename.iterator(); iter.hasNext(); ) { IMethod method = iter.next(); result.merge( Checks.checkIfConstructorName( method, getNewElementName(), method.getDeclaringType().getElementName())); String[] msgData = new String[] { BasicElementLabels.getJavaElementName(method.getElementName()), BasicElementLabels.getJavaElementName( method.getDeclaringType().getFullyQualifiedName('.')) }; if (!method.exists()) { result.addFatalError( Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_not_in_model, msgData)); continue; } if (method.isBinary()) result.addFatalError( Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_no_binary, msgData)); if (method.isReadOnly()) result.addFatalError( Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_no_read_only, msgData)); if (JdtFlags.isNative(method)) result.addError( Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_no_native_1, msgData)); } return result; }
private boolean canSwitchNames(IMethod nukeTarget, IMethod nameSwitchTarget) { String nukeName = nukeTarget.getElementName(); String nameSwitchName = nameSwitchTarget.getElementName(); boolean result = !nukeName.equals(nameSwitchName); result &= !hasMember(nukeTarget.getDeclaringType(), nameSwitchName); result &= !hasMember(nameSwitchTarget.getDeclaringType(), nukeName); return result; }
static final IMethod[] hierarchyDeclaresMethodName( IProgressMonitor pm, ITypeHierarchy hierarchy, IMethod method, String newName) throws CoreException { try { Set<IMethod> result = new HashSet<>(); IType type = method.getDeclaringType(); IMethod foundMethod = Checks.findMethod(newName, method.getParameterTypes().length, false, type); if (foundMethod != null) result.add(foundMethod); IMethod[] foundInHierarchyClasses = classesDeclareMethodName( hierarchy, Arrays.asList(hierarchy.getAllClasses()), method, newName); if (foundInHierarchyClasses != null) result.addAll(Arrays.asList(foundInHierarchyClasses)); IType[] implementingClasses = hierarchy.getImplementingClasses(type); IMethod[] foundInImplementingClasses = classesDeclareMethodName(hierarchy, Arrays.asList(implementingClasses), method, newName); if (foundInImplementingClasses != null) result.addAll(Arrays.asList(foundInImplementingClasses)); return result.toArray(new IMethod[result.size()]); } finally { if (pm != null) { pm.done(); } } }
@Override public Change createChange(IProgressMonitor monitor) throws CoreException { try { final TextChange[] changes = fChangeManager.getAllChanges(); final List<TextChange> list = new ArrayList<>(changes.length); list.addAll(Arrays.asList(changes)); String project = null; IJavaProject javaProject = fMethod.getJavaProject(); if (javaProject != null) project = javaProject.getElementName(); int flags = JavaRefactoringDescriptor.JAR_MIGRATION | JavaRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE; try { if (!Flags.isPrivate(fMethod.getFlags())) flags |= RefactoringDescriptor.MULTI_CHANGE; } catch (JavaModelException exception) { JavaPlugin.log(exception); } final IType declaring = fMethod.getDeclaringType(); try { if (declaring.isAnonymous() || declaring.isLocal()) flags |= JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT; } catch (JavaModelException exception) { JavaPlugin.log(exception); } final String description = Messages.format( RefactoringCoreMessages.RenameMethodProcessor_descriptor_description_short, BasicElementLabels.getJavaElementName(fMethod.getElementName())); final String header = Messages.format( RefactoringCoreMessages.RenameMethodProcessor_descriptor_description, new String[] { JavaElementLabels.getTextLabel(fMethod, JavaElementLabels.ALL_FULLY_QUALIFIED), BasicElementLabels.getJavaElementName(getNewElementName()) }); final String comment = new JDTRefactoringDescriptorComment(project, this, header).asString(); final RenameJavaElementDescriptor descriptor = RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor( IJavaRefactorings.RENAME_METHOD); descriptor.setProject(project); descriptor.setDescription(description); descriptor.setComment(comment); descriptor.setFlags(flags); descriptor.setJavaElement(fMethod); descriptor.setNewName(getNewElementName()); descriptor.setUpdateReferences(fUpdateReferences); descriptor.setKeepOriginal(fDelegateUpdating); descriptor.setDeprecateDelegate(fDelegateDeprecation); return new DynamicValidationRefactoringChange( descriptor, RefactoringCoreMessages.RenameMethodProcessor_change_name, list.toArray(new Change[list.size()])); } finally { monitor.done(); } }
public String getReturnType() { try { IType type = method.getDeclaringType(); String name = getClassNameFromSignature(method.getReturnType()); return getQualifiedClassName(type, name); } catch (JavaModelException e) { return null; } }
@Override public boolean visit(TypeDeclaration node) { String targetType = targetMethod.getDeclaringType().getFullyQualifiedName().replace('$', '.'); String currentType = node.resolveBinding().getQualifiedName(); if (targetType.equals(currentType)) nestLevel = 1; else if (nestLevel > 0) nestLevel++; return true; }
public UserOperatorType getOperatorType() { if (operatorType == null) { IType type = method.getDeclaringType(); IAnnotation ann = getAnnotation(type, method, ANNOTATION_SET); if (ann != null) { operatorType = UserOperatorType.valueOf(ann.getElementName()); } } return operatorType; }
private RefactoringStatus analyzeRenameChanges(IProgressMonitor pm) throws CoreException { ICompilationUnit[] newDeclarationWCs = null; try { pm.beginTask("", 4); // $NON-NLS-1$ RefactoringStatus result = new RefactoringStatus(); ICompilationUnit[] declarationCUs = getDeclarationCUs(); newDeclarationWCs = RenameAnalyzeUtil.createNewWorkingCopies( declarationCUs, fChangeManager, fWorkingCopyOwner, new SubProgressMonitor(pm, 1)); IMethod[] wcOldMethods = new IMethod[fMethodsToRename.size()]; IMethod[] wcNewMethods = new IMethod[fMethodsToRename.size()]; int i = 0; for (Iterator<IMethod> iter = fMethodsToRename.iterator(); iter.hasNext(); i++) { IMethod method = iter.next(); ICompilationUnit newCu = RenameAnalyzeUtil.findWorkingCopyForCu(newDeclarationWCs, method.getCompilationUnit()); IType typeWc = (IType) JavaModelUtil.findInCompilationUnit(newCu, method.getDeclaringType()); if (typeWc == null) { // should not happen i--; wcOldMethods = CollectionsUtil.toArray( Arrays.asList(wcOldMethods).subList(0, wcOldMethods.length - 1), IMethod.class); wcNewMethods = CollectionsUtil.toArray( Arrays.asList(wcNewMethods).subList(0, wcNewMethods.length - 1), IMethod.class); continue; } wcOldMethods[i] = getMethodInWorkingCopy(method, getCurrentElementName(), typeWc); wcNewMethods[i] = getMethodInWorkingCopy(method, getNewElementName(), typeWc); } // SearchResultGroup[] newOccurrences= findNewOccurrences(newMethods, newDeclarationWCs, new // SubProgressMonitor(pm, 3)); SearchResultGroup[] newOccurrences = batchFindNewOccurrences( wcNewMethods, wcOldMethods, newDeclarationWCs, new SubProgressMonitor(pm, 3), result); result.merge( RenameAnalyzeUtil.analyzeRenameChanges2( fChangeManager, fOccurrences, newOccurrences, getNewElementName())); return result; } finally { pm.done(); if (newDeclarationWCs != null) { for (int i = 0; i < newDeclarationWCs.length; i++) { newDeclarationWCs[i].discardWorkingCopy(); } } } }
/** * @return Error message or <code>null</code> if setter can be renamed. * @throws CoreException should not happen */ public String canEnableSetterRenaming() throws CoreException { if (fField.getDeclaringType().isInterface()) return getSetter() == null ? "" : null; // $NON-NLS-1$ IMethod setter = getSetter(); if (setter == null) return ""; // $NON-NLS-1$ final NullProgressMonitor monitor = new NullProgressMonitor(); if (MethodChecks.isVirtual(setter)) { final ITypeHierarchy hierarchy = setter.getDeclaringType().newTypeHierarchy(monitor); if (MethodChecks.isDeclaredInInterface(setter, hierarchy, monitor) != null || MethodChecks.overridesAnotherMethod(setter, hierarchy) != null) return RefactoringCoreMessages.RenameFieldRefactoring_declared_in_supertype; } return null; }
/** * Returns the smallest enclosing <code>IType</code> if the specified object is a main method, or * <code>null</code> * * @param o the object to inspect * @return the smallest enclosing <code>IType</code> of the specified object if it is a main * method or <code>null</code> if it is not */ private IType isMainMethod(Object o) { if (o instanceof IAdaptable) { IAdaptable adapt = (IAdaptable) o; IJavaElement element = (IJavaElement) adapt.getAdapter(IJavaElement.class); if (element != null && element.getElementType() == IJavaElement.METHOD) { try { IMethod method = (IMethod) element; if (method.isMainMethod()) { return method.getDeclaringType(); } } catch (JavaModelException jme) { JDIDebugUIPlugin.log(jme); } } } return null; }
private void checkOverridden(RefactoringStatus status, IProgressMonitor pm) throws JavaModelException { pm.beginTask("", 9); // $NON-NLS-1$ pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_checking_overridden); MethodDeclaration decl = fSourceProvider.getDeclaration(); IMethod method = (IMethod) decl.resolveBinding().getJavaElement(); if (method == null || Flags.isPrivate(method.getFlags())) { pm.worked(8); return; } IType type = method.getDeclaringType(); ITypeHierarchy hierarchy = type.newTypeHierarchy(new SubProgressMonitor(pm, 6)); checkSubTypes(status, method, hierarchy.getAllSubtypes(type), new SubProgressMonitor(pm, 1)); checkSuperClasses( status, method, hierarchy.getAllSuperclasses(type), new SubProgressMonitor(pm, 1)); checkSuperInterfaces( status, method, hierarchy.getAllSuperInterfaces(type), new SubProgressMonitor(pm, 1)); pm.setTaskName(""); // $NON-NLS-1$ }
public List<Attribute> getAttributes() { Map<String, Value> map; { IType type = method.getDeclaringType(); Parameter r = new Parameter(); createAttribute(type, method, r); map = r.attributes; } List<Attribute> list = new ArrayList<Attribute>(map.size()); for (Entry<String, Value> entry : map.entrySet()) { String[] ss = entry.getKey().split("#"); Value value = entry.getValue(); Attribute attr = new Attribute(ss[0], ss[1], value.type); attr.setValue(value.value); list.add(attr); } return list; }
public String convertToString(Object parameterValue) throws ParameterValueConversionException { if (!(parameterValue instanceof IJavaElement)) { throw new ParameterValueConversionException( "parameterValue must be an IJavaElement"); //$NON-NLS-1$ } IJavaElement javaElement = (IJavaElement) parameterValue; IJavaProject javaProject = javaElement.getJavaProject(); if (javaProject == null) { throw new ParameterValueConversionException( "Could not get IJavaProject for element"); //$NON-NLS-1$ } StringBuffer buffer; if (javaElement instanceof IType) { IType type = (IType) javaElement; buffer = composeTypeReference(type); } else if (javaElement instanceof IMethod) { IMethod method = (IMethod) javaElement; buffer = composeTypeReference(method.getDeclaringType()); buffer.append(TYPE_END_CHAR); buffer.append(method.getElementName()); String[] parameterTypes = method.getParameterTypes(); buffer.append(PARAM_START_CHAR); for (int i = 0; i < parameterTypes.length; i++) { buffer.append(parameterTypes[i]); } buffer.append(PARAM_END_CHAR); } else if (javaElement instanceof IField) { IField field = (IField) javaElement; buffer = composeTypeReference(field.getDeclaringType()); buffer.append(TYPE_END_CHAR); buffer.append(field.getElementName()); } else { throw new ParameterValueConversionException("Unsupported IJavaElement type"); // $NON-NLS-1$ } return buffer.toString(); }
/** * Finds a method declaration in a type's hierarchy. The search is top down, so this returns the * first declaration of the method in the hierarchy. This searches for a method with a name and * signature. Parameter types are only compared by the simple name, no resolving for the fully * qualified type name is done. Constructors are only compared by parameters, not the name. * * @param type Searches in this type's supertypes. * @param name The name of the method to find * @param paramTypes The type signatures of the parameters e.g. <code>{"QString;","I"}</code> * @param isConstructor If the method is a constructor * @return The first method found or null, if nothing found */ private static IMethod findMethodDeclarationInHierarchy( ITypeHierarchy hierarchy, IType type, String name, String[] paramTypes, boolean isConstructor) throws JavaModelException { IType[] superTypes = hierarchy.getAllSupertypes(type); for (int i = superTypes.length - 1; i >= 0; i--) { IMethod first = JavaModelUtil.findMethod(name, paramTypes, isConstructor, superTypes[i]); if (first != null && !Flags.isPrivate(first.getFlags())) { // the order getAllSupertypes does make assumptions of the order of inner elements -> search // recursively IMethod res = findMethodDeclarationInHierarchy( hierarchy, first.getDeclaringType(), name, paramTypes, isConstructor); if (res != null) { return res; } return first; } } return null; }
private static void appendMethodReference(IMethod meth, StringBuffer buf) throws JavaModelException { buf.append(meth.getElementName()); /* * The Javadoc tool for Java SE 8 changed the anchor syntax and now tries to avoid "strange" characters in URLs. * This breaks all clients that directly create such URLs. * We can't know what format is required, so we just guess by the project's compiler compliance. */ boolean is18OrHigher = JavaModelUtil.is18OrHigher(meth.getJavaProject()); buf.append(is18OrHigher ? '-' : '('); String[] params = meth.getParameterTypes(); IType declaringType = meth.getDeclaringType(); boolean isVararg = Flags.isVarargs(meth.getFlags()); int lastParam = params.length - 1; for (int i = 0; i <= lastParam; i++) { if (i != 0) { buf.append(is18OrHigher ? "-" : ", "); // $NON-NLS-1$ //$NON-NLS-2$ } String curr = Signature.getTypeErasure(params[i]); String fullName = JavaModelUtil.getResolvedTypeName(curr, declaringType); if (fullName == null) { // e.g. a type parameter "QE;" fullName = Signature.toString(Signature.getElementType(curr)); } if (fullName != null) { buf.append(fullName); int dim = Signature.getArrayCount(curr); if (i == lastParam && isVararg) { dim--; } while (dim > 0) { buf.append(is18OrHigher ? ":A" : "[]"); // $NON-NLS-1$ //$NON-NLS-2$ dim--; } if (i == lastParam && isVararg) { buf.append("..."); // $NON-NLS-1$ } } } buf.append(is18OrHigher ? '-' : ')'); }
/** * Computes the valid proposals for the <code>javax.ws.rs.PathParam</code> annotation value. The * proposals are based on: * * <ul> * <li>The values of the <code>javax.ws.rs.Path</code> annotations, both at the method and at * the type level (inclusion), * <li>The values of the sibling <code>javax.ws.rs.PathParam</code> annotations (exclusion). * </ul> * * @param javaContext the invocation context * @param pathParamAnnotationBinding the annotation bindings * @param method the enclosing java method * @param compilationUnit the compilation unit (AST3) * @return the list of computed completion proposals * @throws CoreException in case of underlying exception * @throws BadLocationException * @throws org.eclipse.jface.text.BadLocationException */ private List<ICompletionProposal> internalComputePathParamProposals( JavaContentAssistInvocationContext javaContext, IAnnotationBinding pathParamAnnotationBinding, IMethod method, CompilationUnit compilationUnit) throws CoreException, BadLocationException { ITypedRegion region = getRegion(javaContext); String matchValue = javaContext .getDocument() .get(region.getOffset(), javaContext.getInvocationOffset() - region.getOffset()); // int cursorPosition = javaContext.getInvocationOffset(); List<ICompletionProposal> completionProposals = new ArrayList<ICompletionProposal>(); // compute proposals from @Path annotations on the method completionProposals.addAll( generateCompletionProposal(method, compilationUnit, region, matchValue)); // compute proposals from @Path annotations on the type completionProposals.addAll( generateCompletionProposal(method.getDeclaringType(), compilationUnit, region, matchValue)); return completionProposals; }
/** * Method to post process returned flags from the {@link * org.eclipse.pde.api.tools.internal.JavadocTagManager} * * @param tag the tag to process * @param element the {@link IJavaElement} the tag will appear on * @return true if the tag should be included in completion proposals, false otherwise */ private boolean acceptTag(IApiJavadocTag tag, IJavaElement element) throws JavaModelException { if (fExistingTags != null) { Boolean fragments = fExistingTags.get(tag.getTagName()); // if the tag has a fragment don't overwrite / propose again if (fragments != null && Boolean.FALSE.equals(fragments)) { return false; } } switch (element.getElementType()) { case IJavaElement.TYPE: { IType type = (IType) element; int flags = type.getFlags(); String tagname = tag.getTagName(); if (Flags.isAbstract(flags)) { return !tagname.equals(JavadocTagManager.TAG_NOINSTANTIATE); } if (Flags.isFinal(flags)) { return !tagname.equals(JavadocTagManager.TAG_NOEXTEND); } break; } case IJavaElement.METHOD: { IMethod method = (IMethod) element; if (Flags.isFinal(method.getFlags()) || Flags.isStatic(method.getFlags())) { return !tag.getTagName().equals(JavadocTagManager.TAG_NOOVERRIDE); } IType type = method.getDeclaringType(); if (type != null && Flags.isFinal(type.getFlags())) { return !tag.getTagName().equals(JavadocTagManager.TAG_NOOVERRIDE); } break; } default: break; } return true; }
private IType getDefiningType(Object element) throws JavaModelException { int kind = ((IJavaElement) element).getElementType(); if (kind != IJavaElement.METHOD && kind != IJavaElement.FIELD && kind != IJavaElement.INITIALIZER) { return null; } IType declaringType = ((IMember) element).getDeclaringType(); if (kind != IJavaElement.METHOD) { return declaringType; } ITypeHierarchy hierarchy = getSuperTypeHierarchy(declaringType); if (hierarchy == null) { return declaringType; } IMethod method = (IMethod) element; MethodOverrideTester tester = new MethodOverrideTester(declaringType, hierarchy); IMethod res = tester.findDeclaringMethod(method, true); if (res == null || method.equals(res)) { return declaringType; } return res.getDeclaringType(); }
// ------- private static IMethod[] classesDeclareMethodName( ITypeHierarchy hier, List<IType> classes, IMethod method, String newName) throws CoreException { Set<IMethod> result = new HashSet<>(); IType type = method.getDeclaringType(); List<IType> subtypes = Arrays.asList(hier.getAllSubtypes(type)); int parameterCount = method.getParameterTypes().length; boolean isMethodPrivate = JdtFlags.isPrivate(method); for (Iterator<IType> iter = classes.iterator(); iter.hasNext(); ) { IType clazz = iter.next(); IMethod[] methods = clazz.getMethods(); boolean isSubclass = subtypes.contains(clazz); for (int j = 0; j < methods.length; j++) { IMethod foundMethod = Checks.findMethod(newName, parameterCount, false, new IMethod[] {methods[j]}); if (foundMethod == null) continue; if (isSubclass || type.equals(clazz)) result.add(foundMethod); else if ((!isMethodPrivate) && (!JdtFlags.isPrivate(methods[j]))) result.add(foundMethod); } } return result.toArray(new IMethod[result.size()]); }
@Override public IJavaCompletionProposal[] getAssists( IInvocationContext context, IProblemLocation[] locations) throws CoreException { ICompilationUnit compilationUnit = context.getCompilationUnit(); IType primaryType = compilationUnit.findPrimaryType(); if (primaryType == null || !primaryType.isInterface()) ; // return null; IJavaElement[] elements = compilationUnit.codeSelect(context.getSelectionOffset(), context.getSelectionLength()); for (IJavaElement element : elements) { if (element.getElementType() == IJavaElement.METHOD) { IMethod method = (IMethod) element; if (!method.getDeclaringType().isInterface()) return null; final String statementAnnotation = getStatementAnnotation(method); if (method.getParameters().length == 0 && statementAnnotation == null) return null; CompilationUnit astNode = getAstNode(compilationUnit); astNode.recordModifications(); final MapperMethod mapperMethod = getMapperMethod(astNode, method); if (mapperMethod == null) return null; List<IJavaCompletionProposal> proposals = new ArrayList<IJavaCompletionProposal>(); if (method.getParameters().length > 0) { proposals.add( new QuickAssistCompletionProposal("Add @Param to parameters") { private CompilationUnit astNode; private MapperMethod method; @SuppressWarnings("unchecked") @Override public void apply(IDocument document) { List<SingleVariableDeclaration> params = method.parameters(); for (SingleVariableDeclaration param : params) { List<IExtendedModifier> modifiers = param.modifiers(); if (!hasParamAnnotation(modifiers)) { if (JavaMapperUtil.TYPE_ROW_BOUNDS.equals( param.resolveBinding().getType().getQualifiedName())) continue; AST ast = param.getAST(); SingleMemberAnnotation annotation = ast.newSingleMemberAnnotation(); annotation.setTypeName(ast.newName("Param")); StringLiteral paramValue = ast.newStringLiteral(); paramValue.setLiteralValue(param.getName().getFullyQualifiedName()); annotation.setValue(paramValue); param.modifiers().add(annotation); } } TextEdit textEdit = astNode.rewrite(document, null); try { textEdit.apply(document); } catch (MalformedTreeException e) { Activator.log(Status.ERROR, e.getMessage(), e); } catch (BadLocationException e) { Activator.log(Status.ERROR, e.getMessage(), e); } } private boolean hasParamAnnotation(List<IExtendedModifier> modifiers) { for (IExtendedModifier modifier : modifiers) { if (modifier.isAnnotation() && "Param" .equals( ((Annotation) modifier).getTypeName().getFullyQualifiedName())) { return true; } } return false; } private QuickAssistCompletionProposal init( CompilationUnit astNode, MapperMethod method) { this.astNode = astNode; this.method = method; return this; } }.init(astNode, mapperMethod)); } if (mapperMethod.getStatement() != null) { proposals.add( new QuickAssistCompletionProposal( "Copy @" + statementAnnotation + " statement to clipboard") { @Override public void apply(IDocument document) { Clipboard clipboard = new Clipboard(Display.getCurrent()); clipboard.setContents( new Object[] {mapperMethod.getStatement()}, new Transfer[] {TextTransfer.getInstance()}); } }); } return proposals.toArray(new IJavaCompletionProposal[proposals.size()]); } } return null; }
public static URL getJavadocLocation(IJavaElement element, boolean includeMemberReference) throws JavaModelException { URL baseLocation = getJavadocBaseLocation(element); if (baseLocation == null) { return null; } String urlString = baseLocation.toExternalForm(); StringBuffer urlBuffer = new StringBuffer(urlString); if (!urlString.endsWith("/")) { // $NON-NLS-1$ urlBuffer.append('/'); } StringBuffer pathBuffer = new StringBuffer(); StringBuffer fragmentBuffer = new StringBuffer(); switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT: appendPackageSummaryPath((IPackageFragment) element, pathBuffer); break; case IJavaElement.JAVA_PROJECT: case IJavaElement.PACKAGE_FRAGMENT_ROOT: appendIndexPath(pathBuffer); break; case IJavaElement.IMPORT_CONTAINER: element = element.getParent(); // $FALL-THROUGH$ case IJavaElement.COMPILATION_UNIT: IType mainType = ((ICompilationUnit) element).findPrimaryType(); if (mainType == null) { return null; } appendTypePath(mainType, pathBuffer); break; case IJavaElement.CLASS_FILE: appendTypePath(((IClassFile) element).getType(), pathBuffer); break; case IJavaElement.TYPE: appendTypePath((IType) element, pathBuffer); break; case IJavaElement.FIELD: IField field = (IField) element; appendTypePath(field.getDeclaringType(), pathBuffer); if (includeMemberReference) { appendFieldReference(field, fragmentBuffer); } break; case IJavaElement.METHOD: IMethod method = (IMethod) element; appendTypePath(method.getDeclaringType(), pathBuffer); if (includeMemberReference) { appendMethodReference(method, fragmentBuffer); } break; case IJavaElement.INITIALIZER: appendTypePath(((IMember) element).getDeclaringType(), pathBuffer); break; case IJavaElement.IMPORT_DECLARATION: IImportDeclaration decl = (IImportDeclaration) element; if (decl.isOnDemand()) { IJavaElement cont = JavaModelUtil.findTypeContainer( element.getJavaProject(), Signature.getQualifier(decl.getElementName())); if (cont instanceof IType) { appendTypePath((IType) cont, pathBuffer); } else if (cont instanceof IPackageFragment) { appendPackageSummaryPath((IPackageFragment) cont, pathBuffer); } } else { IType imp = element.getJavaProject().findType(decl.getElementName()); appendTypePath(imp, pathBuffer); } break; case IJavaElement.PACKAGE_DECLARATION: IJavaElement pack = element.getAncestor(IJavaElement.PACKAGE_FRAGMENT); if (pack != null) { appendPackageSummaryPath((IPackageFragment) pack, pathBuffer); } else { return null; } break; default: return null; } try { String fragment = fragmentBuffer.length() == 0 ? null : fragmentBuffer.toString(); try { URI relativeURI = new URI(null, null, pathBuffer.toString(), fragment); urlBuffer.append(relativeURI.toString()); return new URL(urlBuffer.toString()); } catch (URISyntaxException e) { JavaPlugin.log(e); return new URL(urlBuffer.append(pathBuffer).toString()); } } catch (MalformedURLException e) { JavaPlugin.log(e); } return null; }
public JavaRefactoringDescriptor buildEclipseDescriptor() throws Exception { System.err.println("[eclipse-rename] Building descriptor..."); IJavaElement element = location.getIJavaElement(); String kind = getRenameKind(element); // [1] BUGFIX was needed: The scripting interface didn't allow VariableDeclarationFragments as // IJavaElements // and thus had to be extended // [2] WORKAROUND for scripting interface bug (see below) if (kind.equals(IJavaRefactorings.RENAME_METHOD)) { IMethod m = (IMethod) element; if (m.isConstructor()) { // Rename the type instead (as the UI would do-- the scripting interface will only rename // the constructor, which is broken) kind = IJavaRefactorings.RENAME_TYPE; element = m.getDeclaringType(); } } System.err.println("[eclipse-rename] Kind = " + kind + ", element = " + element); // [3] Don't test for package fragments now if (kind.equals(IJavaRefactorings.RENAME_PACKAGE)) return null; // don't bother with this now if (element == null) { System.err.println("!!! ABORT: No IJavaElement to represent location"); throw new RuntimeException("!!! ABORT: No IJavaElement for location"); } if (element instanceof ILocalVariable) { System.err.println("element is of type " + element.getClass()); final ILocalVariable fLocalVariable = (ILocalVariable) element; final ISourceRange sourceRange = fLocalVariable.getNameRange(); final CompilationUnit fCompilationUnitNode = location.getCompilationUnit(); ASTNode name = NodeFinder.perform(fCompilationUnitNode, sourceRange); System.err.println("node is of type " + name.getClass()); if (name == null) System.err.println("!!! ILV doesn't have associated name!"); if (name.getParent() instanceof VariableDeclaration) System.err.println("ILV has parent : " + (VariableDeclaration) name.getParent()); else System.err.println( "!!! ILV doesn't have var declaration parent, instead " + name.getParent().getClass()); } System.err.println("Trying to rename a " + kind + ": " + element); if (element instanceof SimpleName) System.err.println(" Name = '" + ((SimpleName) element).getIdentifier() + "'"); if (kind.equals(IJavaRefactorings.RENAME_TYPE)) { System.err.println("(Possibly need a new launch configuration)"); tproject.renameClass((IType) element, new_name); } final RenameJavaElementDescriptor descriptor = (RenameJavaElementDescriptor) getDescriptor(kind); descriptor.setJavaElement(element); descriptor.setNewName(this.new_name); if (element.getElementType() == IJavaElement.TYPE || element.getElementType() == IJavaElement.PACKAGE_FRAGMENT) descriptor.setUpdateQualifiedNames(true); else descriptor.setUpdateQualifiedNames(false); descriptor.setUpdateReferences(true); descriptor.setDeprecateDelegate(false); descriptor.setRenameGetters(false); descriptor.setRenameSetters(false); descriptor.setKeepOriginal(false); descriptor.setUpdateHierarchy(false); descriptor.setUpdateSimilarDeclarations(false); // [3] Fix: Eclipse will complain if the transformation is a no-op, but we don't want that: if (element.getElementName().equals(this.new_name)) throw new NOPException(); System.err.println("[eclipse-rename] Computed descriptor."); return descriptor; }
/** {@inheritDoc} */ public boolean matches(IMethod method, String prefix) { return !TypeFilter.isFiltered(method.getDeclaringType()); }
@Override public List<ICompletionProposal> computeCompletionProposals( final ContentAssistInvocationContext context, final IProgressMonitor monitor) { final List<ICompletionProposal> list = new ArrayList<ICompletionProposal>(); boolean extendContext = false; try { if (context instanceof JavaContentAssistInvocationContext) { final ITextViewer viewer = context.getViewer(); final List<ScriptVariable> scriptVariables = getScriptVariables(viewer); if (scriptVariables.isEmpty()) { return list; } final CompletionContext coreContext = ((JavaContentAssistInvocationContext) context).getCoreContext(); if (coreContext != null && !coreContext.isExtended()) { // must use reflection to set the fields ReflectionUtils.setPrivateField( InternalCompletionContext.class, "isExtended", coreContext, true); extendContext = true; } final ICompilationUnit unit = ((JavaContentAssistInvocationContext) context).getCompilationUnit(); if (unit instanceof GroovyCompilationUnit) { if (((GroovyCompilationUnit) unit).getModuleNode() == null) { return Collections.emptyList(); } final ContentAssistContext assistContext = new GroovyCompletionProposalComputer() .createContentAssistContext( (GroovyCompilationUnit) unit, context.getInvocationOffset(), context.getDocument()); CharSequence prefix = null; try { prefix = context.computeIdentifierPrefix(); } catch (final BadLocationException e) { BonitaStudioLog.error(e); } if (assistContext != null && assistContext.completionNode instanceof VariableExpression) { try { final VariableExpression expr = (VariableExpression) assistContext.completionNode; if (scriptVariables != null) { for (final ScriptVariable f : scriptVariables) { if (expr.getName().equals(f.getName())) { final IType type = javaProject.findType(f.getType()); if (type == null) { return list; } for (final IMethod m : type.getMethods()) { if (m.getElementName().startsWith(prefix.toString())) { final GroovyCompletionProposal proposal = new GroovyCompletionProposal( CompletionProposal.METHOD_REF, context.getInvocationOffset()); proposal.setName(m.getElementName().toCharArray()); proposal.setCompletion( m.getElementName().substring(prefix.length()).toCharArray()); proposal.setFlags(m.getFlags()); if (prefix.length() == m.getElementName().length()) { proposal.setReplaceRange( context.getInvocationOffset(), context.getInvocationOffset()); proposal.setReceiverRange(0, 0); } else { proposal.setReplaceRange( context.getInvocationOffset() - prefix.length(), context.getInvocationOffset()); proposal.setReceiverRange(prefix.length(), prefix.length()); } final char[][] parametersArray = new char[m.getParameterNames().length][256]; final List<Parameter> parameters = new ArrayList<Parameter>(); for (int i = 0; i < m.getParameterNames().length; i++) { parametersArray[i] = m.getParameterNames()[i].toCharArray(); parameters.add( new Parameter( ClassHelper.make( Signature.getSignatureSimpleName(m.getParameterTypes()[i])), m.getParameterNames()[i])); } final ClassNode classNode = ClassHelper.make(m.getDeclaringType().getFullyQualifiedName()); proposal.setDeclarationSignature( ProposalUtils.createTypeSignature(classNode)); proposal.setParameterNames(parametersArray); if (m.getDeclaringType().getFullyQualifiedName().equals(f.getType())) { proposal.setRelevance(100); } final MethodNode methodNode = new MethodNode( m.getElementName(), m.getFlags(), ClassHelper.make( Signature.getSignatureSimpleName(m.getReturnType())), parameters.toArray(new Parameter[parameters.size()]), new ClassNode[0], null); final char[] methodSignature = ProposalUtils.createMethodSignature(methodNode); proposal.setSignature(methodSignature); final GroovyJavaGuessingCompletionProposal groovyProposal = GroovyJavaGuessingCompletionProposal.createProposal( proposal, (JavaContentAssistInvocationContext) context, true, "Groovy", ProposalFormattingOptions.newFromOptions()); if (groovyProposal != null) { list.add(groovyProposal); } } } } } } } catch (final JavaModelException e) { BonitaStudioLog.error(e); } } } return list; } } finally { final CompletionContext coreContext = ((JavaContentAssistInvocationContext) context).getCoreContext(); if (extendContext && coreContext != null && coreContext.isExtended()) { // must use reflection to set the fields ReflectionUtils.setPrivateField( InternalCompletionContext.class, "isExtended", coreContext, false); } } return Collections.emptyList(); }
private String getDeclaringTypeLabel() { return JavaElementLabels.getElementLabel( fMethod.getDeclaringType(), JavaElementLabels.ALL_DEFAULT); }
@Override public Object getNewElement() { return fMethod.getDeclaringType().getMethod(getNewElementName(), fMethod.getParameterTypes()); }
private IMethod mockMethod(IType declaringType, String methodName) { IMethod mock = mock(IMethod.class); when(mock.getElementName()).thenReturn(methodName); when(mock.getDeclaringType()).thenReturn(declaringType); return mock; }
private static void generate(IRSEDiagramEngine diagramEngine) { if (diagramEngine == null) return; LinkedHashMap<IType, List<Invocation>> history = SeqUtil.getNavigationHistory(numNavigationsToInclude); List<CodeUnit> classUnits = new ArrayList<CodeUnit>(); List<CodeUnit> methodUnits = new ArrayList<CodeUnit>(); List<ArtifactFragment> toAddToDiagram = new ArrayList<ArtifactFragment>(); for (IType type : history.keySet()) { if (!openTabs.contains(type)) continue; Resource classOfNavigationRes = RJCore.jdtElementToResource(StoreUtil.getDefaultStoreRepository(), type); CodeUnit classOfNavigationCU = GenerateUtil.getCodeUnitForRes(classOfNavigationRes, null, classUnits, null); // Add method calls for (Invocation invocation : history.get(type)) { IType container = null; if (invocation.getMethodElement() != null) { IMethod method = invocation.getMethodElement(); container = method.getDeclaringType(); } if (container == null) continue; boolean containerIsAnOpenTab = false; for (IType navigatedType : openTabs) { if (navigatedType.equals(container)) { containerIsAnOpenTab = true; break; } } if (!containerIsAnOpenTab) continue; // Find the method declaration in which the invocation is made CompilationUnit cu = ASTUtil.getAst(IJEUtils.ije_getTypeRoot(type)); MethodDeclarationFinder finder = new MethodDeclarationFinder(cu); MethodDeclaration declaration = finder.findDeclaration(invocation.getStartPosition()); if (declaration == null || declaration.resolveBinding() == null || declaration.resolveBinding().getJavaElement() == null) continue; Resource declarationRes = RJCore.jdtElementToResource( StoreUtil.getDefaultStoreRepository(), declaration.resolveBinding().getJavaElement()); CodeUnit declarationThatMakesInvocation = GenerateUtil.getCodeUnitForRes(declarationRes, null, methodUnits, classOfNavigationCU); String instanceName = (invocation.getInvocation() instanceof SuperMethodInvocation) ? null : MethodUtil.getInstanceCalledOn(invocation); CodeUnit containerOfDeclOfInvokedMethod = GenerateUtil.getCodeUnitForRes( RJCore.jdtElementToResource(StoreUtil.getDefaultStoreRepository(), container), instanceName, classUnits, null); Resource declOfInvokedMethodRes = RJCore.jdtElementToResource( StoreUtil.getDefaultStoreRepository(), invocation.getMethodElement()); CodeUnit declOfInvokedMethodCU = GenerateUtil.getCodeUnitForRes( declOfInvokedMethodRes, null, methodUnits, containerOfDeclOfInvokedMethod); ArtifactRel rel = new ArtifactRel(declarationThatMakesInvocation, declOfInvokedMethodCU, RJCore.calls); declarationThatMakesInvocation.addSourceConnection(rel); declOfInvokedMethodCU.addTargetConnection(rel); } // Add inheritance relationships among classes for (Resource superClassRes : InstanceUtil.getSuperClasses(classOfNavigationRes)) { CodeUnit superClassCU = GenerateUtil.getCodeUnitForRes(superClassRes, null, classUnits, null); IJavaElement superClassElt = RJCore.resourceToJDTElement(StoreUtil.getDefaultStoreRepository(), superClassRes); if (!history.keySet().contains(superClassElt)) continue; // superclass has not been recently navigated if (!openTabs.contains(superClassElt)) continue; // superclass is not an open tab ArtifactRel inheritanceRel = new ArtifactRel(classOfNavigationCU, superClassCU, RJCore.inherits); classOfNavigationCU.addSourceConnection(inheritanceRel); superClassCU.addTargetConnection(inheritanceRel); } } for (CodeUnit classUnit : classUnits) { if (classUnit.getShownChildren().size() > 0) toAddToDiagram.add(classUnit); } int numBeingAdded = toAddToDiagram.size(); if (numBeingAdded < numNavigationsToInclude) { // Diagram going to be small, so add a reasonable number // of the open tabs that were most recently activated // (openTabs list is ordered with most recently activated first) for (int i = 0; i < openTabs.size() && numBeingAdded < numNavigationsToInclude; i++) { IType type = openTabs.get(i); // only adding top level tabs here, not any nested classes if (!(type instanceof SourceType) || ((SourceType) type).getParent().getElementType() == IJavaElement.TYPE) continue; Resource classOfNavigationRes = RJCore.jdtElementToResource(StoreUtil.getDefaultStoreRepository(), type); CodeUnit classOfNavigationCU = GenerateUtil.getCodeUnitForRes(classOfNavigationRes, null, classUnits, null); if (!toAddToDiagram.contains(classOfNavigationCU)) { toAddToDiagram.add(classOfNavigationCU); numBeingAdded++; } } } diagramEngine.openDiagramFromNavigatedTabs( toAddToDiagram, new ArrayList<ArtifactFragment>(classUnits)); }
/** * Initializes the refactoring from scripting arguments. Used by {@link * RenameVirtualMethodProcessor} and {@link RenameNonVirtualMethodProcessor} * * @param extended the arguments * @return the resulting status */ protected final RefactoringStatus initialize(JavaRefactoringArguments extended) { fInitialized = true; final String handle = extended.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT); if (handle != null) { final IJavaElement element = JavaRefactoringDescriptorUtil.handleToElement(extended.getProject(), handle, false); final String refactoring = getProcessorName(); if (element instanceof IMethod) { final IMethod method = (IMethod) element; final IType declaring = method.getDeclaringType(); if (declaring != null && declaring.exists()) { final IMethod[] methods = declaring.findMethods(method); if (methods != null && methods.length == 1 && methods[0] != null) { if (!methods[0].exists()) return JavaRefactoringDescriptorUtil.createInputFatalStatus( methods[0], refactoring, IJavaRefactorings.RENAME_METHOD); fMethod = methods[0]; initializeWorkingCopyOwner(); } else return JavaRefactoringDescriptorUtil.createInputFatalStatus( null, refactoring, IJavaRefactorings.RENAME_METHOD); } else return JavaRefactoringDescriptorUtil.createInputFatalStatus( element, refactoring, IJavaRefactorings.RENAME_METHOD); } else return JavaRefactoringDescriptorUtil.createInputFatalStatus( element, refactoring, IJavaRefactorings.RENAME_METHOD); } else return RefactoringStatus.createFatalErrorStatus( Messages.format( RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT)); final String name = extended.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME); if (name != null && !"".equals(name)) // $NON-NLS-1$ setNewElementName(name); else return RefactoringStatus.createFatalErrorStatus( Messages.format( RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME)); final String references = extended.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_REFERENCES); if (references != null) { fUpdateReferences = Boolean.valueOf(references).booleanValue(); } else return RefactoringStatus.createFatalErrorStatus( Messages.format( RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JavaRefactoringDescriptorUtil.ATTRIBUTE_REFERENCES)); final String delegate = extended.getAttribute(ATTRIBUTE_DELEGATE); if (delegate != null) { fDelegateUpdating = Boolean.valueOf(delegate).booleanValue(); } else return RefactoringStatus.createFatalErrorStatus( Messages.format( RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_DELEGATE)); final String deprecate = extended.getAttribute(ATTRIBUTE_DEPRECATE); if (deprecate != null) { fDelegateDeprecation = Boolean.valueOf(deprecate).booleanValue(); } else return RefactoringStatus.createFatalErrorStatus( Messages.format( RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_DEPRECATE)); return new RefactoringStatus(); }