private void extractIMethod(IMethod method, boolean annotationElement) { try { StringBuilder fqnBuilder = new StringBuilder(fqnStack.peek()); if (method.isConstructor()) { fqnBuilder.append('.').append("<init>"); } else { fqnBuilder.append('.').append(method.getElementName()); } fqnBuilder.append('('); boolean first = true; for (String param : method.getParameterTypes()) { if (first) { first = false; } else { fqnBuilder.append(','); } String sig = typeSignatureToFqn(param); fqnBuilder.append(sig); } fqnBuilder.append(')'); String fqn = fqnBuilder.toString(); // Write the entity if (annotationElement) { entityWriter.writeAnnotationElement(fqn, method.getFlags(), path); } else if (method.isConstructor()) { entityWriter.writeConstructor(fqn, method.getFlags(), path); } else { entityWriter.writeMethod(fqn, method.getFlags(), path); } // Write the inside relation relationWriter.writeInside(fqn, fqnStack.peek(), path); // Write the returns relation relationWriter.writeReturns(fqn, typeSignatureToFqn(method.getReturnType()), path); // Write the receives relation String[] paramTypes = method.getParameterTypes(); for (int i = 0; i < paramTypes.length; i++) { localVariableWriter.writeClassParameter( "arg" + i, typeSignatureToFqn(paramTypes[i]), fqn, i, path); // relationWriter.writeReceives(fqn, typeSignatureToFqn(paramTypes[i]), "arg" + i, // i); } int pos = 0; for (ITypeParameter param : method.getTypeParameters()) { relationWriter.writeParametrizedBy(fqn, getTypeParam(param), pos++, path); } } catch (JavaModelException e) { logger.log(Level.SEVERE, "Error in extracting class file", e); } }
@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(); } }
/** * Create a {@link BeansJavaCompletionProposal} for the given {@link IMethod} and report it on the * {@link ContentAssistRequest}. */ protected void createMethodProposal(IContentAssistProposalRecorder recorder, IMethod method) { try { String[] parameterNames = method.getParameterNames(); String[] parameterTypes = JdtUtils.getParameterTypesString(method); String returnType = JdtUtils.getReturnTypeString(method, true); String methodName = JdtUtils.getMethodName(method); String replaceText = methodName; StringBuilder buf = new StringBuilder(); // add method name buf.append(replaceText); // add method parameters if (parameterTypes.length > 0 && parameterNames.length > 0) { buf.append(" ("); for (int i = 0; i < parameterTypes.length; i++) { buf.append(parameterTypes[i]); buf.append(' '); buf.append(parameterNames[i]); if (i < (parameterTypes.length - 1)) { buf.append(", "); } } buf.append(") "); } else { buf.append("() "); } // add return type if (returnType != null) { buf.append(Signature.getSimpleName(returnType)); buf.append(" - "); } else { buf.append(" void - "); } // add class name buf.append(JdtUtils.getParentName(method)); String displayText = buf.toString(); Image image = Activator.getDefault() .getJavaElementLabelProvider() .getImageLabel(method, method.getFlags() | JavaElementImageProvider.SMALL_ICONS); recorder.recordProposal(image, METHOD_RELEVANCE, displayText, replaceText, method); } catch (JavaModelException e) { // do nothing } }
/** * 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 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$ }
/** * 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 ? '-' : ')'); }
/** * We don't include nested types because structural changes of nested types should not affect * Xtend classes which use top level types. * * @deprecated This method is not used anymore. */ @Deprecated protected void traverseType(IType type, NameBasedEObjectDescriptionBuilder acceptor) { try { if (type.exists()) { for (IField field : type.getFields()) { if (!Flags.isSynthetic(field.getFlags())) { String fieldName = field.getElementName(); acceptor.accept(fieldName); } } for (IMethod method : type.getMethods()) { if (!Flags.isSynthetic(method.getFlags())) { String methodName = method.getElementName(); acceptor.accept(methodName); } } } } catch (JavaModelException e) { if (LOGGER.isDebugEnabled()) LOGGER.debug(e, e); } }
/** * Determines is the java element contains a specific method. * * <p>The syntax for the property tester is of the form: methodname, signature, modifiers. * * <ol> * <li>methodname - case sensitive method name, required. For example, <code>toString</code>. * <li>signature - JLS style method signature, required. For example, <code>(QString;)V</code>. * <li>modifiers - optional space separated list of modifiers, for example, <code>public static * </code>. * </ol> * * @param element the element to check for the method * @param args first arg is method name, secondary args are parameter types signatures * @return true if the method is found in the element, false otherwise */ private boolean hasMethod(IJavaElement element, Object[] args) { try { if (args.length > 1) { IType type = getType(element); if (type != null && type.exists()) { String name = (String) args[0]; String signature = (String) args[1]; String[] parms = Signature.getParameterTypes(signature); String returnType = Signature.getReturnType(signature); IMethod candidate = type.getMethod(name, parms); if (candidate.exists()) { // check return type if (candidate.getReturnType().equals(returnType)) { // check modifiers if (args.length > 2) { String modifierText = (String) args[2]; String[] modifiers = modifierText.split(" "); // $NON-NLS-1$ int flags = 0; for (int j = 0; j < modifiers.length; j++) { String modifier = modifiers[j]; Integer flag = (Integer) fgModifiers.get(modifier); if (flag != null) { flags = flags | flag.intValue(); } } if (candidate.getFlags() == flags) { return true; } } } } } } } catch (JavaModelException e) { } return false; }
protected void setUp() throws Exception { super.setUp(); fProject = new SWTTestProject(); IType control = fProject.getProject().findType("org.eclipse.swt.widgets.Control"); ExtractInterfaceProcessor processor = new ExtractInterfaceProcessor( control, JavaPreferencesSettings.getCodeGenerationSettings(fProject.getProject())); fRefactoring = new ProcessorBasedRefactoring(processor); IMethod[] methods = control.getMethods(); List extractedMembers = new ArrayList(); for (int i = 0; i < methods.length; i++) { IMethod method = methods[i]; int flags = method.getFlags(); if (Flags.isPublic(flags) && !Flags.isStatic(flags) && !method.isConstructor()) { extractedMembers.add(method); } } processor.setTypeName("IControl"); processor.setExtractedMembers( (IMember[]) extractedMembers.toArray(new IMember[extractedMembers.size()])); processor.setReplace(true); }
@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 void extractIType(IType type) { try { String fqn = type.getFullyQualifiedName(); // Write the entity if (type.isClass()) { entityWriter.writeClass(fqn, type.getFlags(), path); // Write the superclass String superSig = type.getSuperclassTypeSignature(); if (superSig != null) { relationWriter.writeExtends(fqn, typeSignatureToFqn(superSig), path); } } else if (type.isAnnotation()) { entityWriter.writeAnnotation(fqn, type.getFlags(), path); } else if (type.isInterface()) { entityWriter.writeInterface(fqn, type.getFlags(), path); } else if (type.isEnum()) { entityWriter.writeEnum(fqn, type.getFlags(), path); } // Write the superinterfaces for (String superIntSig : type.getSuperInterfaceTypeSignatures()) { relationWriter.writeImplements(fqn, typeSignatureToFqn(superIntSig), path); } if (!fqnStack.isEmpty()) { relationWriter.writeInside(type.getFullyQualifiedName(), fqnStack.peek(), path); } fqnStack.push(type.getFullyQualifiedName()); for (IType child : type.getTypes()) { extractIType(child); } for (IField field : type.getFields()) { if (!Flags.isSynthetic(field.getFlags())) { extractIField(field); } } for (IMethod method : type.getMethods()) { if (!Flags.isSynthetic(method.getFlags()) || (Flags.isSynthetic(method.getFlags()) && method.isConstructor() && method.getParameterTypes().length == 0)) { extractIMethod(method, type.isAnnotation()); } } int pos = 0; for (ITypeParameter param : type.getTypeParameters()) { relationWriter.writeParametrizedBy(fqn, getTypeParam(param), pos++, path); } fqnStack.pop(); } catch (Exception e) { logger.log(Level.SEVERE, "Error in extracting class file", e); } }
/** * Determines is the java element contains a method with a specific annotation. * * <p>The syntax for the property tester is of the form: qualified or unqualified annotation name, * modifiers * <li>qualified or unqualified annotation name, required. For example, <code>org.junit.JUnit * </code>. * <li>modifiers - optional space separated list of modifiers, for example, <code>public static * </code>. * </ol> * * @param element the element to check for the method * @param annotationName the qualified or unqualified name of the annotation to look for * @return true if the method is found in the element, false otherwise */ private boolean hasMethodWithAnnotation(IJavaElement element, Object[] args) { try { String annotationType = (String) args[0]; int flags = 0; if (args.length > 1) { String[] modifiers = ((String) args[1]).split(" "); // $NON-NLS-1$ for (int j = 0; j < modifiers.length; j++) { String modifier = modifiers[j]; Integer flag = (Integer) fgModifiers.get(modifier); if (flag != null) { flags = flags | flag.intValue(); } } } else { flags = -1; } IType type = getType(element); if (type == null || !type.exists()) { return false; } IMethod[] methods = type.getMethods(); if (methods.length == 0) { return false; } IBuffer buffer = null; IOpenable openable = type.getOpenable(); if (openable instanceof ICompilationUnit) { buffer = ((ICompilationUnit) openable).getBuffer(); } else if (openable instanceof IClassFile) { buffer = ((IClassFile) openable).getBuffer(); } if (buffer == null) { return false; } IScanner scanner = null; // delay initialization for (int i = 0; i < methods.length; i++) { IMethod curr = methods[i]; if (curr.isConstructor() || (flags != -1 && flags != (curr.getFlags() & FLAGS_MASK))) { continue; } ISourceRange sourceRange = curr.getSourceRange(); ISourceRange nameRange = curr.getNameRange(); if (sourceRange != null && nameRange != null) { if (scanner == null) { scanner = ToolFactory.createScanner(false, false, true, false); scanner.setSource(buffer.getCharacters()); } scanner.resetTo(sourceRange.getOffset(), nameRange.getOffset()); if (findAnnotation(scanner, annotationType)) { return true; } } } } catch (JavaModelException e) { } catch (InvalidInputException e) { } return false; }
private boolean isPrivate(IMethod method) throws JavaModelException { return (method.getFlags() & Flags.AccPrivate) != 0; }