Java Code Examples for org.eclipse.jdt.core.dom.TypeDeclaration#getMethods()

The following examples show how to use org.eclipse.jdt.core.dom.TypeDeclaration#getMethods() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClientBundleValidator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean visit(TypeDeclaration type) {
  if (!shouldValidateType(type)) {
    return true;
  }

  CompilationUnit cu = (CompilationUnit) type.getRoot();
  for (MethodDeclaration methodDecl : type.getMethods()) {
    if (JavaASTUtils.hasErrors(methodDecl, cu.getProblems())) {
      // Skip any methods that already have JDT errors
      continue;
    }
    validateReturnType(methodDecl);
    validateParameterList(methodDecl);
    validateResourceFile(methodDecl);
  }

  return true;
}
 
Example 2
Source File: TypeCheckingEvolution.java    From JDeodorant with MIT License 6 votes vote down vote up
private List<TypeCheckElimination> generateTypeCheckEliminationsWithinTypeDeclaration(TypeDeclaration typeDeclaration, TypeCheckElimination originalTypeCheckElimination) {
	List<TypeCheckElimination> typeCheckEliminations = new ArrayList<TypeCheckElimination>();
	for(MethodDeclaration method : typeDeclaration.getMethods()) {
		Block methodBody = method.getBody();
		if(methodBody != null) {
			List<TypeCheckElimination> list = generateTypeCheckEliminationsWithinMethodBody(methodBody);
			for(TypeCheckElimination typeCheckElimination : list) {
				if(!typeCheckElimination.allTypeCheckBranchesAreEmpty()) {
					TypeCheckCodeFragmentAnalyzer analyzer = new TypeCheckCodeFragmentAnalyzer(typeCheckElimination, typeDeclaration, method, null);
					if((typeCheckElimination.getTypeField() != null || typeCheckElimination.getTypeLocalVariable() != null || typeCheckElimination.getTypeMethodInvocation() != null) &&
							typeCheckElimination.allTypeCheckingsContainStaticFieldOrSubclassType() && typeCheckElimination.isApplicable()) {
						if(originalTypeCheckElimination.matchingStatesOrSubTypes(typeCheckElimination))
							typeCheckEliminations.add(typeCheckElimination);
					}
				}
			}
		}
	}
	return typeCheckEliminations;
}
 
Example 3
Source File: MethodDiff.java    From apidiff with MIT License 6 votes vote down vote up
/**
 * Finding added methods
 * @param version1
 * @param version2
 */
private void findAddedMethods(APIVersion version1, APIVersion version2) {
	for (TypeDeclaration typeInVersion2 : version2.getApiAcessibleTypes()) {
		if(version1.containsType(typeInVersion2)){
			for(MethodDeclaration methodInVersion2: typeInVersion2.getMethods()){
				if(this.isMethodAcessible(methodInVersion2)){
					MethodDeclaration methodInVersion1 = version1.findMethodByNameAndParameters(methodInVersion2, typeInVersion2);
					String fullNameAndPathMethodVersion2 = this.getFullNameMethodAndPath(methodInVersion2, typeInVersion2);
					if(methodInVersion1 == null && !this.methodsWithPathChanged.contains(fullNameAndPathMethodVersion2)){
						String nameMethod = this.getSimpleNameMethod(methodInVersion2);
						String nameClass = UtilTools.getPath(typeInVersion2);
						String description = this.description.addition(nameMethod, nameClass);
						this.addChange(typeInVersion2, methodInVersion2, Category.METHOD_ADD, false, description);
					}
				}
			}
		}
	}
}
 
Example 4
Source File: MethodDiff.java    From apidiff with MIT License 6 votes vote down vote up
/**
 * Finding removed methods. If class was removed, class removal is a breaking change.
 * @param version1
 * @param version2
 */
private void findRemoveAndRefactoringMethods(APIVersion version1, APIVersion version2) {
	for (TypeDeclaration typeInVersion1 : version1.getApiAcessibleTypes()) {
		if(version2.containsAccessibleType(typeInVersion1)){
			for (MethodDeclaration methodInVersion1 : typeInVersion1.getMethods()) {
				if(this.isMethodAcessible(methodInVersion1)){
					MethodDeclaration methodInVersion2 = version2.findMethodByNameAndParameters(methodInVersion1, typeInVersion1);
					if(methodInVersion2 == null){
						Boolean refactoring = this.checkAndProcessRefactoring(methodInVersion1, typeInVersion1);
						if(!refactoring){
							this.processRemoveMethod(methodInVersion1, typeInVersion1);
						}
					}
				}
			}
		} 
	}
}
 
Example 5
Source File: MethodDiff.java    From apidiff with MIT License 6 votes vote down vote up
/**
 * Finding methods with change in exception list 
 * @param version1
 * @param version2
 */
private void findChangedExceptionTypeMethods(APIVersion version1, APIVersion version2) {
	for(TypeDeclaration typeVersion1 : version1.getApiAcessibleTypes()){
		if(version2.containsAccessibleType(typeVersion1)){
			for(MethodDeclaration methodVersion1 : typeVersion1.getMethods()){
				if(this.isMethodAcessible(methodVersion1)){
					MethodDeclaration methodVersion2 = version2.getEqualVersionMethod(methodVersion1, typeVersion1);
					if(this.isMethodAcessible(methodVersion2)){
						List<SimpleType> exceptionsVersion1 = methodVersion1.thrownExceptionTypes();
						List<SimpleType> exceptionsVersion2 = methodVersion2.thrownExceptionTypes();
						if(exceptionsVersion1.size() != exceptionsVersion2.size() || (this.diffListExceptions(exceptionsVersion1, exceptionsVersion2))) {
							String nameMethod = this.getSimpleNameMethod(methodVersion1);
							String nameClass = UtilTools.getPath(typeVersion1);
							String description = this.description.exception(nameMethod, exceptionsVersion1, exceptionsVersion2, nameClass);
							this.addChange(typeVersion1, methodVersion1, Category.METHOD_CHANGE_EXCEPTION_LIST, true, description);
						}
					}
				}
			}
		}
	}
}
 
Example 6
Source File: MethodEvolution.java    From JDeodorant with MIT License 5 votes vote down vote up
private List<String> getStringRepresentation(IMethod method, ProjectVersion version) {
	List<String> stringRepresentation = null;
	if(method != null) {
		ICompilationUnit iCompilationUnit = method.getCompilationUnit();
		ASTParser parser = ASTParser.newParser(ASTReader.JLS);
		parser.setKind(ASTParser.K_COMPILATION_UNIT);
		parser.setSource(iCompilationUnit);
		parser.setResolveBindings(true);
		CompilationUnit compilationUnit = (CompilationUnit)parser.createAST(null);
		IType declaringType = method.getDeclaringType();
		TypeDeclaration typeDeclaration = (TypeDeclaration)compilationUnit.findDeclaringNode(declaringType.getKey());
		MethodDeclaration matchingMethodDeclaration = null;
		for(MethodDeclaration methodDeclaration : typeDeclaration.getMethods()) {
			IMethod resolvedMethod = (IMethod)methodDeclaration.resolveBinding().getJavaElement();
			if(resolvedMethod.isSimilar(method)) {
				matchingMethodDeclaration = methodDeclaration;
				break;
			}
		}
		if(matchingMethodDeclaration != null && matchingMethodDeclaration.getBody() != null) {
			methodCodeMap.put(version, matchingMethodDeclaration.toString());
			ASTInformationGenerator.setCurrentITypeRoot(iCompilationUnit);
			MethodBodyObject methodBody = new MethodBodyObject(matchingMethodDeclaration.getBody());
			stringRepresentation = methodBody.stringRepresentation();
		}
	}
	return stringRepresentation;
}
 
Example 7
Source File: MethodDiff.java    From apidiff with MIT License 5 votes vote down vote up
/**
 * Finding methods with changed visibility
 * @param version1
 * @param version2
 */
private void findChangedVisibilityMethods(APIVersion version1, APIVersion version2) {
	for(TypeDeclaration typeVersion1 : version1.getApiAcessibleTypes()){
		if(version2.containsAccessibleType(typeVersion1)){
			for(MethodDeclaration methodVersion1 : typeVersion1.getMethods()){
				MethodDeclaration methodVersion2 = version2.getEqualVersionMethod(methodVersion1, typeVersion1);
				this.checkGainOrLostVisibility(typeVersion1, methodVersion1, methodVersion2);
			}
		}
	}
}
 
Example 8
Source File: MethodDiff.java    From apidiff with MIT License 5 votes vote down vote up
/**
 * Finding change in final/static modifiers
 * @param version1
 * @param version2
 */
private void findChangedFinalAndStatic(APIVersion version1, APIVersion version2) {
	
	for (TypeDeclaration typeVersion1 : version1.getApiAcessibleTypes()) {
		if(version2.containsType(typeVersion1)){//Se type ainda existe.
			for(MethodDeclaration methodVersion1: typeVersion1.getMethods()){
				MethodDeclaration methodVersion2 = version2.findMethodByNameAndParametersAndReturn(methodVersion1, typeVersion1);
				if(this.isMethodAcessible(methodVersion1) && (methodVersion2 != null)){
					this.diffModifierFinal(typeVersion1, methodVersion1, methodVersion2);
					this.diffModifierStatic(typeVersion1, methodVersion1, methodVersion2);
				}
			}
		}
	}
}
 
Example 9
Source File: MoveMethodRefactoring.java    From JDeodorant with MIT License 5 votes vote down vote up
private void setPublicModifierToSourceMethod(IMethodBinding methodBinding, TypeDeclaration sourceTypeDeclaration) {
	MethodDeclaration[] methodDeclarations = sourceTypeDeclaration.getMethods();
	for(MethodDeclaration methodDeclaration : methodDeclarations) {
		if(methodDeclaration.resolveBinding().isEqualTo(methodBinding)) {
			CompilationUnit sourceCompilationUnit = RefactoringUtility.findCompilationUnit(methodDeclaration);
			ASTRewrite sourceRewriter = ASTRewrite.create(sourceCompilationUnit.getAST());
			ListRewrite modifierRewrite = sourceRewriter.getListRewrite(methodDeclaration, MethodDeclaration.MODIFIERS2_PROPERTY);
			Modifier publicModifier = methodDeclaration.getAST().newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD);
			boolean modifierFound = false;
			List<IExtendedModifier> modifiers = methodDeclaration.modifiers();
			for(IExtendedModifier extendedModifier : modifiers) {
				if(extendedModifier.isModifier()) {
					Modifier modifier = (Modifier)extendedModifier;
					if(modifier.getKeyword().equals(Modifier.ModifierKeyword.PUBLIC_KEYWORD)) {
						modifierFound = true;
					}
					else if(modifier.getKeyword().equals(Modifier.ModifierKeyword.PRIVATE_KEYWORD)) {
						modifierFound = true;
						modifierRewrite.replace(modifier, publicModifier, null);
						updateAccessModifier(sourceRewriter, sourceCompilationUnit);
					}
					else if(modifier.getKeyword().equals(Modifier.ModifierKeyword.PROTECTED_KEYWORD)) {
						modifierFound = true;
						IPackageBinding targetTypeDeclarationPackageBinding = this.targetTypeDeclaration.resolveBinding().getPackage();
						IPackageBinding typeDeclarationPackageBinding = sourceTypeDeclaration.resolveBinding().getPackage();
						if(targetTypeDeclarationPackageBinding != null && typeDeclarationPackageBinding != null &&
								!targetTypeDeclarationPackageBinding.isEqualTo(typeDeclarationPackageBinding)) {
							modifierRewrite.replace(modifier, publicModifier, null);
							updateAccessModifier(sourceRewriter, sourceCompilationUnit);
						}
					}
				}
			}
			if(!modifierFound) {
				modifierRewrite.insertFirst(publicModifier, null);
				updateAccessModifier(sourceRewriter, sourceCompilationUnit);
			}
		}
	}
}
 
Example 10
Source File: SharedUtils.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
public static MethodDeclaration findMethodDeclarationByName(TypeDeclaration owner, String name) {
	for (MethodDeclaration methodDeclaration : owner.getMethods()) {
		if (methodDeclaration.getName().getFullyQualifiedName().equals(name)) {
			return methodDeclaration;
		}
	}
	return null;
}
 
Example 11
Source File: APIVersion.java    From apidiff with MIT License 5 votes vote down vote up
private MethodDeclaration findMethodByNameAndReturn(MethodDeclaration method, TypeDeclaration type){
	MethodDeclaration methodVersionOld = null;
	for (TypeDeclaration versionType : this.apiAccessibleTypes) {
		if(versionType.getName().toString().equals(type.getName().toString())){
			for(MethodDeclaration versionMethod : versionType.getMethods()){
				if(!ComparatorMethod.isDiffMethodByNameAndReturn(versionMethod, method)){
					methodVersionOld =  versionMethod;
				}
			}
		}
	}
	return methodVersionOld;
}
 
Example 12
Source File: TypeCheckCodeFragmentAnalyzer.java    From JDeodorant with MIT License 5 votes vote down vote up
public TypeCheckCodeFragmentAnalyzer(TypeCheckElimination typeCheckElimination,
		TypeDeclaration typeDeclaration, MethodDeclaration typeCheckMethod, IFile iFile) {
	this.typeCheckElimination = typeCheckElimination;
	this.typeDeclaration = typeDeclaration;
	this.typeCheckMethod = typeCheckMethod;
	this.fields = typeDeclaration.getFields();
	this.methods = typeDeclaration.getMethods();
	this.typeVariableCounterMap = new LinkedHashMap<SimpleName, Integer>();
	this.typeMethodInvocationCounterMap = new LinkedHashMap<MethodInvocation, Integer>();
	this.complexExpressionMap = new LinkedHashMap<Expression, IfStatementExpressionAnalyzer>();
	typeCheckElimination.setTypeCheckClass(typeDeclaration);
	typeCheckElimination.setTypeCheckMethod(typeCheckMethod);
	typeCheckElimination.setTypeCheckIFile(iFile);
	processTypeCheckCodeFragment();
}
 
Example 13
Source File: JavaASTVisitor.java    From SnowGraph with Apache License 2.0 5 votes vote down vote up
private boolean visitClass(TypeDeclaration node) {

        ClassInfo classInfo = new ClassInfo();
        classInfo.name = node.getName().getFullyQualifiedName();
        classInfo.fullName = NameResolver.getFullName(node);
        classInfo.visibility = getVisibility(node);
        classInfo.isAbstract = isAbstract(node);
        classInfo.isFinal = isFinal(node);
        classInfo.superClassType = node.getSuperclassType() == null ? "java.lang.Object" : NameResolver.getFullName(node.getSuperclassType());
        List<Type> superInterfaceList = node.superInterfaceTypes();
        for (Type superInterface : superInterfaceList)
            classInfo.superInterfaceTypeList.add(NameResolver.getFullName(superInterface));
        if (node.getJavadoc() != null)
            classInfo.comment = sourceContent.substring(node.getJavadoc().getStartPosition(), node.getJavadoc().getStartPosition() + node.getJavadoc().getLength());
        classInfo.content = sourceContent.substring(node.getStartPosition(), node.getStartPosition() + node.getLength());
        elementInfoPool.classInfoMap.put(classInfo.fullName, classInfo);

        MethodDeclaration[] methodDeclarations = node.getMethods();
        for (MethodDeclaration methodDeclaration : methodDeclarations) {
            MethodInfo methodInfo = createMethodInfo(methodDeclaration, classInfo.fullName);
            elementInfoPool.methodInfoMap.put(methodInfo.hashName(), methodInfo);
        }

        FieldDeclaration[] fieldDeclarations = node.getFields();
        for (FieldDeclaration fieldDeclaration : fieldDeclarations) {
            List<FieldInfo> fieldInfos = createFieldInfos(fieldDeclaration, classInfo.fullName);
            for (FieldInfo fieldInfo : fieldInfos)
                elementInfoPool.fieldInfoMap.put(fieldInfo.hashName(), fieldInfo);
        }
        return true;
    }
 
Example 14
Source File: BuilderClassRemover.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
private boolean isTypeLooksLikeABuilder(TypeDeclaration nestedType) {
    if (nestedType.getTypes().length > 0) {
        return false;
    }
    if (nestedType.getMethods().length < 2) {
        return false;
    }
    if (getNumberOfEmptyPrivateConstructors(nestedType) != 1) {
        return false;
    }
    return true;
}
 
Example 15
Source File: ASTNodeFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static TypeParameter newTypeParameter(AST ast, String content) {
	StringBuffer buffer= new StringBuffer(TYPEPARAM_HEADER);
	buffer.append(content);
	buffer.append(TYPEPARAM_FOOTER);
	ASTParser p= ASTParser.newParser(ast.apiLevel());
	p.setSource(buffer.toString().toCharArray());
	CompilationUnit root= (CompilationUnit) p.createAST(null);
	List<AbstractTypeDeclaration> list= root.types();
	TypeDeclaration typeDecl= (TypeDeclaration) list.get(0);
	MethodDeclaration methodDecl= typeDecl.getMethods()[0];
	TypeParameter tp= (TypeParameter) methodDecl.typeParameters().get(0);
	ASTNode result= ASTNode.copySubtree(ast, tp);
	result.accept(new PositionClearer());
	return (TypeParameter) result;
}
 
Example 16
Source File: JavaASTUtilsTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public void testGetSource() {
  String expectedSource = createString(testClassSource);
  String actualSource = JavaASTUtils.getSource(ast);
  assertEquals(expectedSource, actualSource);

  CompilationUnit root = (CompilationUnit) ast;
  TypeDeclaration typeDecl = (TypeDeclaration) root.types().get(0);
  TypeDeclaration innerTypeDecl = typeDecl.getTypes()[0];
  MethodDeclaration getNumberDecl = innerTypeDecl.getMethods()[0];

  String expectedMethodSource = createString(new String[] {
      "public static int getNumber() {", "      return 777;", "    }"});
  String actualMethodSource = JavaASTUtils.getSource(getNumberDecl);
  assertEquals(expectedMethodSource, actualMethodSource);
}
 
Example 17
Source File: AbstractPairedInterfaceValidator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public List<CategorizedProblem> validate(TypeDeclaration changedInterface,
    ITypeBinding dependentTypeBinding) {
  CompilationUnit compilationUnit = getCompilationUnit(changedInterface);
  if (JavaASTUtils.hasErrors(changedInterface, compilationUnit.getProblems())) {
    /*
     * Don't validate any type that already has errors (we are assuming that
     * it has JDT errors.
     */
    return Collections.emptyList();
  }

  if (dependentTypeBinding == null) {
    return doMissingDependentInterface(changedInterface);
  }

  // Check that for every method on the changed interface, there is a
  // corresponding method on the dependent interface
  List<CategorizedProblem> problems = new ArrayList<CategorizedProblem>();
  for (MethodDeclaration methodDeclaration : changedInterface.getMethods()) {
    List<CategorizedProblem> methodProblems = doValidateMethodOnChangedType(
        methodDeclaration, dependentTypeBinding);
    problems.addAll(methodProblems);
  }

  List<ITypeBinding> superTypeBindings = new ArrayList<ITypeBinding>();
  RemoteServiceUtilities.expandSuperInterfaces(dependentTypeBinding,
      superTypeBindings);

  for (ITypeBinding typeBinding : superTypeBindings) {
    for (IMethodBinding methodBinding : typeBinding.getDeclaredMethods()) {
      List<CategorizedProblem> dependentMethodProblems = doValidateMethodOnDependentInterface(
          methodBinding, changedInterface, typeBinding);
      problems.addAll(dependentMethodProblems);
    }
  }

  return problems;
}
 
Example 18
Source File: ASTNodeFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static Type newType(AST ast, String content) {
	StringBuffer buffer= new StringBuffer(TYPE_HEADER);
	buffer.append(content);
	buffer.append(TYPE_FOOTER);
	ASTParser p= ASTParser.newParser(ast.apiLevel());
	p.setSource(buffer.toString().toCharArray());
	CompilationUnit root= (CompilationUnit) p.createAST(null);
	List<AbstractTypeDeclaration> list= root.types();
	TypeDeclaration typeDecl= (TypeDeclaration) list.get(0);
	MethodDeclaration methodDecl= typeDecl.getMethods()[0];
	ASTNode type= methodDecl.getReturnType2();
	ASTNode result= ASTNode.copySubtree(ast, type);
	result.accept(new PositionClearer());
	return (Type)result;
}
 
Example 19
Source File: AbstractUpdateSignatureProposal.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private static int candidateCount(TypeDeclaration type, String name) {
  int count = 0;

  for (MethodDeclaration method : type.getMethods()) {
    if (name.equals(method.getName().getIdentifier())) {
      count += 1;
    }
  }

  return count;
}
 
Example 20
Source File: RemoteServiceValidatorTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
public void testMissingSyncMethod() throws JavaModelException {
  ICompilationUnit syncInterface = JavaProjectUtilities.createCompilationUnit(
      javaProject,
      "com.google.TestService",
      "package com.google;\npublic interface TestService extends com.google.gwt.user.client.rpc.RemoteService {  }\n");

  ICompilationUnit asyncInterface = JavaProjectUtilities.createCompilationUnit(
      javaProject,
      "com.google.TestServiceAsync",
      "package com.google;\nimport com.google.gwt.user.client.rpc.AsyncCallback;\npublic interface TestServiceAsync { void foo(AsyncCallback foo); }\n");

  RemoteServiceValidator rsv = new RemoteServiceValidator();
  ValidationResult validationResults;

  ASTNode syncAst = newAST(syncInterface);
  CompilationUnit syncUnit = (CompilationUnit) syncAst;
  TypeDeclaration syncTypeDecl = JavaASTUtils.findTypeDeclaration(syncUnit,
      "com.google.TestService");

  ASTNode asyncAst = newAST(asyncInterface);
  CompilationUnit asyncUnit = (CompilationUnit) asyncAst;
  TypeDeclaration asyncTypeDecl = JavaASTUtils.findTypeDeclaration(asyncUnit,
      "com.google.TestServiceAsync");

  // Test that an error is reported on TestInteface because it is missing the
  // sync version of method void foo(AsyncCallback);
  validationResults = rsv.validate(syncAst);
  List<? extends CategorizedProblem> expectedSyncProblems = Arrays.asList(RemoteServiceProblemFactory.newMissingSyncMethodOnSync(
      syncTypeDecl, asyncTypeDecl.resolveBinding().getDeclaredMethods()[0]));
  assertProblemsEqual(expectedSyncProblems, validationResults.getProblems());
  assertEquals(Arrays.asList("com.google.TestServiceAsync"),
      validationResults.getTypeDependencies());

  // Test that an error is reported on TestIntefaceAsync because it has no
  // foo(AsyncCallback) method
  validationResults = rsv.validate(asyncAst);
  MethodDeclaration asyncMethodDeclaration = asyncTypeDecl.getMethods()[0];
  List<? extends CategorizedProblem> expectedAsyncProblems = Arrays.asList(RemoteServiceProblemFactory.newMissingSyncMethodOnAsync(
      asyncMethodDeclaration,
      syncTypeDecl.resolveBinding()));
  assertProblemsEqual(expectedAsyncProblems, validationResults.getProblems());
  assertEquals(Arrays.asList("com.google.TestService"),
      validationResults.getTypeDependencies());
}