public void initByIMethodBinding(IMethodBinding mBinding) { IMethod iMethod = (IMethod) mBinding.getJavaElement(); try { key = iMethod.getKey().substring(0, iMethod.getKey().indexOf("(")) + iMethod.getSignature(); projectName = mBinding.getJavaElement().getJavaProject() .getElementName(); } catch (Exception e) { projectName = ""; } packageName = mBinding.getDeclaringClass().getPackage().getName(); className = mBinding.getDeclaringClass().getName(); name = mBinding.getName(); parameters = new ArrayList<>(); ITypeBinding[] parameterBindings = mBinding.getParameterTypes(); for (int i = 0; i < parameterBindings.length; i++) { parameters.add(parameterBindings[i].getName()); } }
public static boolean containsMethod (String path, String[] requiredMethods) throws JavaModelException { IResource resource = ResourceManager.getResource(path); IFile file = (IFile) resource; ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file); IType[] types = cu.getAllTypes(); List<String> list = new ArrayList<String>(); for (int i = 0; i < types.length; i++) { IMethod[] methods = types[i].getMethods(); for (int j = 0; j < methods.length; j++) { list.add(methods[j].getElementName()); } } for (int i = 0; i < requiredMethods.length; i++) { String method = requiredMethods[i]; if (!list.contains(method)) return false; } return true; }
@Test public void testEnrichClass() throws Exception { IJavaProject pj = ProjectHelper.getOrCreateSimpleGW4EProject(PROJECT_NAME,true,false); IFile impl = ProjectHelper.createDummyClass (pj); ICompilationUnit compilationUnit = JavaCore.createCompilationUnitFrom(impl); IMethod m = compilationUnit.getTypes() [0].getMethod("runFunctionalTest",new String[0]); assertFalse (m.exists()); IFile file = (IFile) ResourceManager.getResource(pj.getProject().getFullPath().append("src/test/resources/Simple.json").toString()); ResourceContext context = GenerationFactory.getResourceContext(file); ClassExtension ce = context.getClassExtension(); ce.setGenerateRunFunctionalTest(true); ce.setStartElementForJunitTest("start_app"); TestResourceGeneration trg = new TestResourceGeneration(context); JDTManager.enrichClass(impl, trg, new NullProgressMonitor()); m = compilationUnit.getTypes() [0].getMethod("runFunctionalTest",new String[0]); assertTrue (m.exists()); }
/** * 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; }
public ClassDetails(IClassFile classFile, String jarFileName, String packageName, boolean isUserDefined) { LOGGER.debug("Extracting methods from "+classFile.getElementName()); try { this.javaDoc=getJavaDoc(classFile); intialize(classFile,jarFileName,packageName, isUserDefined); for (IJavaElement iJavaElement : classFile.getChildren()) { if (iJavaElement instanceof IType) { IType iType = (IType) iJavaElement; for (IMethod iMethod : iType.getMethods()) { addMethodsToClass(iMethod); } } } } catch (JavaModelException e) { LOGGER.error("Error occurred while fetching methods from class"+cName); } }
public ClassDetails(SourceType javaClassFile, String jarFileName, String packageName, boolean isUserDefined) { Logger LOGGER = LogFactory.INSTANCE.getLogger(ClassDetails.class); LOGGER.debug("Extracting methods from " + cName); try { this.javaDoc=getJavaDoc(javaClassFile); intialize(javaClassFile, jarFileName, packageName, isUserDefined); for (IJavaElement iJavaElement : javaClassFile.getChildren()) { if (iJavaElement instanceof SourceMethod) { addMethodsToClass((IMethod) iJavaElement); } } } catch (JavaModelException e) { LOGGER.error("Error occurred while fetching methods from class" + cName); } }
private String createSignature(IMethod iMethod) throws JavaModelException { StringBuffer buffer = new StringBuffer(); returnType = DataTypes.getDataTypefromString(ExpressionEditorUtil.INSTANCE.lastString(iMethod.getReturnType(), Constants.DOT)); buffer.append(iMethod.getElementName() + SWT.SPACE + Constants.OPENING_BRACKET); if (iMethod.getParameters() != null && iMethod.getParameters().length > 0) { for (int index = 0; index < iMethod.getParameters().length; index++) { buffer.append(DataTypes.getDataTypefromString(ExpressionEditorUtil.INSTANCE.lastString( iMethod.getParameters()[index].getTypeSignature(), Constants.DOT))); buffer.append(SWT.SPACE); buffer.append(iMethod.getParameters()[index].getElementName()); if (index != iMethod.getParameters().length - 1) buffer.append(Constants.COMMA); } } buffer.append(Constants.CLOSING_BRACKET); buffer.append(SWT.SPACE + Constants.DASH + SWT.SPACE + returnType); return buffer.toString(); }
private void handleType(IType type, IFile file, List<ServiceImplementation> serviceImplementations) throws JavaModelException { /* Parcourt les méthodes. */ for (IMethod method : type.getMethods()) { /* Filtre pour ne garder que les méthodes publiques d'instance */ if (method.isConstructor() || Flags.isStatic(method.getFlags()) || Flags.isPrivate(method.getFlags())) { continue; } /* Créé le ServiceImplementation. */ String javaName = method.getElementName(); ISourceRange nameRange = method.getNameRange(); FileRegion fileRegion = new FileRegion(file, nameRange.getOffset(), nameRange.getLength()); ServiceImplementation serviceImplementation = new ServiceImplementation(fileRegion, javaName); serviceImplementations.add(serviceImplementation); } }
private void handleType(IType type, IFile file, List<DaoImplementation> daoImplementations) throws JavaModelException { /* Parcourt les méthodes. */ for (IMethod method : type.getMethods()) { /* Filtre pour ne garder que les méthodes publiques d'instance */ if (method.isConstructor() || Flags.isStatic(method.getFlags()) || Flags.isPrivate(method.getFlags())) { continue; } /* Créé le DaoImplementation. */ String javaName = method.getElementName(); ISourceRange nameRange = method.getNameRange(); FileRegion fileRegion = new FileRegion(file, nameRange.getOffset(), nameRange.getLength()); DaoImplementation daoImplementation = new DaoImplementation(fileRegion, javaName); daoImplementations.add(daoImplementation); } }
private static void parseVertigoDtoField(IMethod method, List<DtoField> fields) { try { if (method.isConstructor() || !Flags.isPublic(method.getFlags())) { return; } IAnnotation fieldAnnotation = JdtUtils.getAnnotation(method, FIELD_ANNOTATION_NAME); if (fieldAnnotation == null) { return; } String domain = (String) JdtUtils.getMemberValue(fieldAnnotation, DOMAIN_FIELD_NAME); /* Cas d'un champ de composition DTO/DTC : on filtre. */ if (domain == null || domain.startsWith(DTO_DOMAIN_PREFIX)) { return; } String constantCaseName = StringUtils.toConstantCase(KspStringUtils.getFieldNameFromGetter(method.getElementName())); String label = (String) JdtUtils.getMemberValue(fieldAnnotation, LABEL_FIELD_NAME); Boolean persistent = (Boolean) JdtUtils.getMemberValue(fieldAnnotation, PERSISTENT_FIELD_NAME); DtoField field = new DtoField(constantCaseName, label, domain, persistent); fields.add(field); } catch (JavaModelException e) { ErrorUtils.handle(e); } }
/** * Copied from org.eclipse.jdt.internal.debug.ui.actions.ToggleBreakpointAdapter * TODO: is there a public API to do this? * * Returns the resolved signature of the given method * @param method method to resolve * @return the resolved method signature or <code>null</code> if none * @throws JavaModelException * @since 3.4 */ public static String resolveMethodSignature(IMethod method) throws JavaModelException { String signature = method.getSignature(); String[] parameterTypes = Signature.getParameterTypes(signature); int length = parameterTypes.length; String[] resolvedParameterTypes = new String[length]; for (int i = 0; i < length; i++) { resolvedParameterTypes[i] = resolveTypeSignature(method, parameterTypes[i]); if (resolvedParameterTypes[i] == null) { return null; } } String resolvedReturnType = resolveTypeSignature(method, Signature.getReturnType(signature)); if (resolvedReturnType == null) { return null; } return Signature.createMethodSignature(resolvedParameterTypes, resolvedReturnType); }
public List<IMethod> getInstanceMethods() { if(jType == null) return Collections.emptyList(); try { List<IMethod> list = new ArrayList<>(); IMethod[] methods = jType.getMethods(); for(IMethod m : methods) if(!m.isConstructor() && !Flags.isStatic(m.getFlags()) && isMethodVisible(m)) list.add(m); return list; } catch (JavaModelException e) { e.printStackTrace(); return Collections.emptyList(); } // return info.getMethods(EnumSet.of(VisibilityInfo.PUBLIC)); }
private boolean isMethodVisible(IMethod m) { try { int f = m.getFlags(); return extension.includeMethod(m.getElementName()) && !jType.isMember() && isVisibleMember(m); // ( // !jType.isMember() && jType.getPackageFragment().isDefaultPackage() && // (Flags.isPackageDefault(f) || Flags.isProtected(f) || Flags.isPublic(f)) // || // Flags.isPublic(f) // ); } catch (JavaModelException e) { e.printStackTrace(); return false; } }
MethodWidget(IMethod method) { setLayoutManager(new FlowLayout()); button = new Button(shortSig(method)); button.setToolTip(new Label(longSig(method))); button.setForegroundColor(ColorConstants.black); FontManager.setFont(button, PandionJConstants.BUTTON_FONT_SIZE); button.setEnabled(methodsEnabled); add(button); resultLabel = new Label(); resultLabel.setForegroundColor(ColorConstants.black); add(resultLabel); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { invoke(model, method, resultLabel); } }); }
@Override public IFigure createFigure(IObjectModel e) { Label label = new Label(); label.setForegroundColor(PandionJConstants.Colors.OBJECT_HEADER_FONT); FontManager.setFont(label, PandionJConstants.OBJECT_HEADER_FONT_SIZE); IType type = e.getType(); if(type != null) { IMethod method = type.getMethod("toString", new String[0]); if(!method.exists()) { label.setText(":" + type.getElementName()); return label; } } invokeToString(e, label); label.setToolTip(new Label("returned by toString()")); e.getRuntimeModel().registerDisplayObserver((event) -> { if(event.type == IRuntimeModel.Event.Type.STEP ||event.type == IRuntimeModel.Event.Type.EVALUATION) { invokeToString(e, label); // label.setText(e.getStringValue()); } }); return label; }
public void setMethod(IMethod method, InvocationAction a) { String key = null; try { IType type = (IType) method.getParent(); key = type.getFullyQualifiedName() + "|" + method.getElementName() + method.getSignature(); } catch (JavaModelException e) { e.printStackTrace(); } if(key != null) { StaticInvocationWidget2 inv = invWidgetsMap.get(key); if(inv == null) { inv = new StaticInvocationWidget2(this, null, method, a); invWidgetsMap.put(key, inv); } inv.refreshItems(); layout.topControl = inv; layout(); } }
public void setMethod(IFile file, IMethod method, InvocationAction a) { String key = null; try { IType type = (IType) method.getParent(); key = type.getFullyQualifiedName() + "|" + method.getElementName() + method.getSignature(); } catch (JavaModelException e) { e.printStackTrace(); } if(key != null) { StaticInvocationWidget inv = invWidgetsMap.get(key); if(inv == null) { inv = new StaticInvocationWidget(this, file, method, a); invWidgetsMap.put(key, inv); } inv.refreshItems(file); layout.topControl = inv; layout(); } }
private Set<IPath> getMethodTypes(final IType typeElement, final List<IImport> imports, final Path path) throws JavaModelException { final IMethod[] methods = typeElement.getMethods(); final Set<IPath> methodTypes = new HashSet<>(); for (final IMethod method : methods) { final String returnType = method.getReturnType(); addToPaths(imports, path, methodTypes, returnType); final String[] parameterTypes = method.getParameterTypes(); for (final String parameterType : parameterTypes) { addToPaths(imports, path, methodTypes, parameterType); } final String[] exceptionTypes = method.getExceptionTypes(); for (final String exceptionType : exceptionTypes) { addToPaths(imports, path, methodTypes, exceptionType); } } return methodTypes; }
private static final boolean resolveTypeParameter(final IMethod method, final String identifier, final StringBuilder result) throws JavaModelException { IType type = method.getDeclaringType(); if (resolveTypeParameter(type, method.getTypeParameters(), identifier, result)) { return true; } while (type != null) { if (resolveTypeParameter(type, type.getTypeParameters(), identifier, result)) { return true; } type = type.getDeclaringType(); } return false; }
@Override public boolean visit(MethodDeclaration methodDeclaration) { IBinding binding = methodDeclaration.resolveBinding(); if (binding == null) return false; currentMethod = (IMethod) binding.getJavaElement(); if (currentMethod != null) { methodDetails = new MethodDetails(); String handleIdentifier = currentMethod.getHandleIdentifier(); allDetails.put(handleIdentifier, methodDetails); methodDetails.setModifiers(methodDeclaration.getModifiers()); methodDetails.setParameters(getParameters(methodDeclaration.parameters())); Type returnType2 = methodDeclaration.getReturnType2(); if (returnType2 != null) { ITypeBinding typeBinding = returnType2.resolveBinding(); IJavaElement returnType = typeBinding.getJavaElement(); if (returnType instanceof IType) { methodDetails.setReturnType((IType) returnType); } } } return true; }
@Test public void testFromMethodWithBooleanReturnValueAndIsPropertyReturnsProperty() throws JavaModelException { IMethod method = mock(IMethod.class); when(method.getElementName()).thenReturn("isFoo"); IAnnotation required = mock(IAnnotation.class); when(method.getAnnotation(PipelineOptionsNamespaces.validationRequired(version))) .thenReturn(required); when(required.exists()).thenReturn(false); when(required.getElementName()) .thenReturn(PipelineOptionsNamespaces.validationRequired(version)); when(method.getAnnotations()).thenReturn(new IAnnotation[] {required}); IAnnotation description = mock(IAnnotation.class); when(description.exists()).thenReturn(false); when(method.getAnnotation(PipelineOptionsNamespaces.descriptionAnnotation(version))) .thenReturn(description); PipelineOptionsProperty property = PipelineOptionsProperty.fromMethod(method, version); assertEquals("foo", property.getName()); assertFalse(property.isRequired()); assertTrue(property.getGroups().isEmpty()); }
@Test public void testFromMethodWithNoValidationRequiredAnnotationIsNotRequired() throws JavaModelException { IMethod method = mock(IMethod.class); when(method.getElementName()).thenReturn("getFoo"); IAnnotation required = mock(IAnnotation.class); when(method.getAnnotation(PipelineOptionsNamespaces.validationRequired(version))) .thenReturn(required); when(required.exists()).thenReturn(false); when(required.getElementName()) .thenReturn(PipelineOptionsNamespaces.validationRequired(version)); when(method.getAnnotations()).thenReturn(new IAnnotation[] {required}); IAnnotation description = mock(IAnnotation.class); when(description.exists()).thenReturn(false); when(method.getAnnotation(PipelineOptionsNamespaces.descriptionAnnotation(version))) .thenReturn(description); PipelineOptionsProperty property = PipelineOptionsProperty.fromMethod(method, version); assertEquals("foo", property.getName()); assertFalse(property.isRequired()); assertTrue(property.getGroups().isEmpty()); }
@Test public void testFromMethodWithoutDescriptionHasAbsentOptional() throws Exception { IMethod method = mock(IMethod.class); when(method.getElementName()).thenReturn("getFoo"); IAnnotation required = mock(IAnnotation.class); when(method.getAnnotation(PipelineOptionsNamespaces.validationRequired(version))) .thenReturn(required); when(required.exists()).thenReturn(false); when(required.getElementName()) .thenReturn(PipelineOptionsNamespaces.validationRequired(version)); when(method.getAnnotations()).thenReturn(new IAnnotation[] {required}); IAnnotation description = mock(IAnnotation.class); when(description.exists()).thenReturn(false); when(method.getAnnotation(PipelineOptionsNamespaces.descriptionAnnotation(version))) .thenReturn(description); PipelineOptionsProperty property = PipelineOptionsProperty.fromMethod(method, version); assertNull(property.getDescription()); }
@Before public void setup() throws Exception { MockitoAnnotations.initMocks(this); rootType = mockType(PipelineOptionsNamespaces.rootType(version)); when(rootType.getMethods()).thenReturn(new IMethod[0]); when(rootType.exists()).thenReturn(true); when(project.findType(PipelineOptionsNamespaces.rootType(version))) .thenReturn(rootType); when(rootType.newTypeHierarchy(Mockito.<IProgressMonitor>any())).thenReturn(typeHierarchy); when(typeHierarchy.getSuperInterfaces(rootType)).thenReturn(new IType[0]); pipelineOptionsHierarchy = new JavaProjectPipelineOptionsHierarchy(project, version, new NullProgressMonitor()); }
@Test public void testGetPipelineOptionsTypeReturnsPipelineOptions() throws Exception { String intermediateTypeName = "com.google.IntermediateOptionsType"; IType intermediateType = mockType(intermediateTypeName); when(intermediateType.getMethods()).thenReturn(new IMethod[0]); String requestedTypeName = "foo.bar.RequestedType"; IType requestedType = mockType(requestedTypeName); when(requestedType.getMethods()).thenReturn(new IMethod[0]); when(project.findType(requestedTypeName)).thenReturn(requestedType); when(rootType.newTypeHierarchy(Mockito.<IProgressMonitor>any())).thenReturn(typeHierarchy); when(typeHierarchy.contains(requestedType)).thenReturn(true); when(typeHierarchy.getSuperInterfaces(requestedType)) .thenReturn(new IType[] {intermediateType}); when(typeHierarchy.getSuperInterfaces(intermediateType)).thenReturn(new IType[] {rootType}); when(typeHierarchy.getSuperInterfaces(rootType)).thenReturn(new IType[0]); PipelineOptionsType type = pipelineOptionsHierarchy.getPipelineOptionsType(requestedTypeName); assertEquals(requestedTypeName, type.getName()); assertEquals(3, pipelineOptionsHierarchy.getOptionsHierarchy(requestedTypeName).size()); }
@Test public void testGetPipelineOptionsTypeForTypeNotInProjectReturnsAbsent() throws Exception { IType rootType = mockType(PipelineOptionsNamespaces.rootType(version)); when(rootType.getMethods()).thenReturn(new IMethod[0]); when(rootType.exists()).thenReturn(true); when(project.findType(PipelineOptionsNamespaces.rootType(version))) .thenReturn(rootType); String requestedTypeName = "foo.bar.RequestedType"; when(project.findType(requestedTypeName)).thenReturn(null); ITypeHierarchy hierarchy = mock(ITypeHierarchy.class); when(rootType.newTypeHierarchy(Mockito.<IProgressMonitor>any())).thenReturn(hierarchy); PipelineOptionsType type = pipelineOptionsHierarchy.getPipelineOptionsType(requestedTypeName); assertNull(type); }
private LaunchableResource toLaunchableResource(IResource resource) { if (resource == null) { return null; } IJavaElement javaElement = resource.getAdapter(IJavaElement.class); if (javaElement != null && javaElement.exists() && javaElement instanceof ICompilationUnit) { ICompilationUnit compilationUnit = (ICompilationUnit) javaElement; IType javaType = compilationUnit.findPrimaryType(); if (javaType == null) { return null; } IMethod mainMethod = javaType.getMethod( "main", new String[] {Signature.createTypeSignature("String[]", false)}); return new LaunchableResource(resource, mainMethod, javaType); } return new LaunchableResource(resource); }
private Set<PipelineOptionsProperty> getProperties(IType optionsType) { try { ImmutableSet.Builder<PipelineOptionsProperty> propertiesBuilder = ImmutableSet.builder(); for (IMethod method : optionsType.getMethods()) { PipelineOptionsProperty property = PipelineOptionsProperty.fromMethod(method, majorVersion); if (property != null) { propertiesBuilder.add(property); } } return propertiesBuilder.build(); } catch (JavaModelException e) { DataflowCorePlugin.logError( e, "Error while retrieving Methods for Options type %s", optionsType); return Collections.emptySet(); } }
/** * @see Measure#measure */ @Override public <T> void measure(T unit) { IMethod[] iMethods = null; try { IType[] iTypes = ((ICompilationUnit)unit).getTypes(); for (IType iType : iTypes){ iMethods = iType.getMethods(); } } catch (JavaModelException exception) { logger.error(exception); } CompilationUnit parse = parse(unit); ResponseForClassVisitor visitor = ResponseForClassVisitor.getInstance(); visitor.cleanVariables(); visitor.addListOfMethodsDeclaration(iMethods); parse.accept(visitor); setCalculatedValue(getResponseForClassValue(visitor)); setMeanValue(getCalculatedValue()); setMaxValue(getCalculatedValue(), parse.getJavaElement().getElementName()); }
/** * Method to check with methods share common attributes, according to * CK definition. * @author Mariana Azevedo * @since 13/07/2014 * @param methods */ private void checkMethodsWithSharedAttributes(IMethod[] methods){ IScanner scanner = null; for (IMethod method : methods) { String methodName = method.getElementName(); try { scanner = ToolFactory.createScanner(false, false, false, false); scanner.setSource(method.getSource().toCharArray()); while(true){ int charactere = scanner.getNextToken(); if (charactere == ITerminalSymbols.TokenNameEOF) break; if (charactere == ITerminalSymbols.TokenNameIdentifier) { addMethods(new String(scanner.getCurrentTokenSource()), methodName); } } } catch (JavaModelException exception1) { logger.error(exception1); } catch (InvalidInputException exception2) { logger.error(exception2); } } }
/** * @see IBuilder#build */ @Override public void build(Measure measure, ItemMeasured item) { try { for (IType unit : myClass.getAllTypes()) { for (IMethod method : unit.getMethods()) { ItemMeasured methodItem = new ItemMeasured(method.getElementName(), item); measure.measure(method); methodItem.setValue(measure.getCalculatedValue()); methodItem.setMean(measure.getMeanValue()); item.addValue(measure.getCalculatedValue()); item.addMean(measure.getMeanValue()); item.setMax(measure.getMaxValue()); item.setClassWithMax(measure.getClassWithMaxValue()); item.addChild(methodItem); } } } catch (JavaModelException exception) { logger.error(exception); } }
private static String[] getUniqueParameterNames(MethodReference methodReference, IMethodBinding functionalMethod) throws JavaModelException { String[] parameterNames = ((IMethod) functionalMethod.getJavaElement()).getParameterNames(); List<String> oldNames = new ArrayList<>(Arrays.asList(parameterNames)); String[] newNames = new String[oldNames.size()]; List<String> excludedNames = new ArrayList<>(ASTNodes.getVisibleLocalVariablesInScope(methodReference)); for (int i = 0; i < oldNames.size(); i++) { String paramName = oldNames.get(i); List<String> allNamesToExclude = new ArrayList<>(excludedNames); allNamesToExclude.addAll(oldNames.subList(0, i)); allNamesToExclude.addAll(oldNames.subList(i + 1, oldNames.size())); if (allNamesToExclude.contains(paramName)) { String newParamName = createName(paramName, allNamesToExclude); excludedNames.add(newParamName); newNames[i] = newParamName; } else { newNames[i] = paramName; } } return newNames; }
private static String getUniqueMethodName(ASTNode astNode, String suggestedName) throws JavaModelException { while (astNode != null && !(astNode instanceof TypeDeclaration)) { astNode = astNode.getParent(); } if (astNode instanceof TypeDeclaration) { ITypeBinding typeBinding = ((TypeDeclaration) astNode).resolveBinding(); if (typeBinding == null) { return suggestedName; } IType type = (IType) typeBinding.getJavaElement(); if (type == null) { return suggestedName; } IMethod[] methods = type.getMethods(); int suggestedPostfix = 2; String resultName = suggestedName; while (suggestedPostfix < 1000) { if (!hasMethod(methods, resultName)) { return resultName; } resultName = suggestedName + suggestedPostfix++; } } return suggestedName; }
private int compareInTheSameType(IMethodBinding firstMethodBinding, IMethodBinding secondMethodBinding) { try { IMethod firstMethod= (IMethod)firstMethodBinding.getJavaElement(); IMethod secondMethod= (IMethod)secondMethodBinding.getJavaElement(); if (firstMethod == null || secondMethod == null) { return 0; } ISourceRange firstSourceRange= firstMethod.getSourceRange(); ISourceRange secondSourceRange= secondMethod.getSourceRange(); if (!SourceRange.isAvailable(firstSourceRange) || !SourceRange.isAvailable(secondSourceRange)) { return firstMethod.getElementName().compareTo(secondMethod.getElementName()); } else { return firstSourceRange.getOffset() - secondSourceRange.getOffset(); } } catch (JavaModelException e) { return 0; } }
private static boolean sameParameters(IMethodBinding method, IMethod candidate) throws JavaModelException { ITypeBinding[] methodParamters= method.getParameterTypes(); String[] candidateParameters= candidate.getParameterTypes(); if (methodParamters.length != candidateParameters.length) { return false; } IType scope= candidate.getDeclaringType(); for (int i= 0; i < methodParamters.length; i++) { ITypeBinding methodParameter= methodParamters[i]; String candidateParameter= candidateParameters[i]; if (!sameParameter(methodParameter, candidateParameter, scope)) { return false; } } return true; }
private static String[] getParameterTypeNamesForSeeTag(IMethod overridden) { try { ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); parser.setProject(overridden.getJavaProject()); IBinding[] bindings = parser.createBindings(new IJavaElement[] { overridden }, null); if (bindings.length == 1 && bindings[0] instanceof IMethodBinding) { return getParameterTypeNamesForSeeTag((IMethodBinding) bindings[0]); } } catch (IllegalStateException e) { // method does not exist } // fall back code. Not good for generic methods! String[] paramTypes = overridden.getParameterTypes(); String[] paramTypeNames = new String[paramTypes.length]; for (int i = 0; i < paramTypes.length; i++) { paramTypeNames[i] = Signature.toString(Signature.getTypeErasure(paramTypes[i])); } return paramTypeNames; }
private void findAllDeclarations(IProgressMonitor monitor, WorkingCopyOwner owner) throws CoreException { fDeclarations = new ArrayList<>(); class MethodRequestor extends SearchRequestor { @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { IMethod method = (IMethod) match.getElement(); boolean isBinary = method.isBinary(); if (!isBinary) { fDeclarations.add(method); } } } int limitTo = IJavaSearchConstants.DECLARATIONS | IJavaSearchConstants.IGNORE_DECLARING_TYPE | IJavaSearchConstants.IGNORE_RETURN_TYPE; int matchRule = SearchPattern.R_ERASURE_MATCH | SearchPattern.R_CASE_SENSITIVE; SearchPattern pattern = SearchPattern.createPattern(fMethod, limitTo, matchRule); MethodRequestor requestor = new MethodRequestor(); SearchEngine searchEngine = owner != null ? new SearchEngine(owner) : new SearchEngine(); searchEngine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, createSearchScope(), requestor, monitor); }
private static Reader findDocInHierarchy(IMethod method, boolean useAttachedJavadoc) throws JavaModelException { /* * Catch ExternalJavaProject in which case * no hierarchy can be built. */ if (!method.getJavaProject().exists()) { return null; } IType type= method.getDeclaringType(); ITypeHierarchy hierarchy= type.newSupertypeHierarchy(null); MethodOverrideTester tester= new MethodOverrideTester(type, hierarchy); IType[] superTypes= hierarchy.getAllSupertypes(type); for (IType curr : superTypes) { IMethod overridden= tester.findOverriddenMethodInType(curr, method); if (overridden != null) { Reader reader = getHTMLContentReader(overridden, false, useAttachedJavadoc); if (reader != null) { return reader; } } } return null; }