Java Code Examples for com.github.javaparser.ast.body.MethodDeclaration

The following examples show how to use com.github.javaparser.ast.body.MethodDeclaration. These examples are extracted from open source projects. 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 Project: JApiDocs   Source File: ParseUtilsTest.java    License: Apache License 2.0 7 votes vote down vote up
@Test
public void test_parseGenericClassNode(){
    File resultJavaFile = Projects.getTestJavaFile(GenericResult.class);

    ParseUtils.compilationUnit(resultJavaFile).getChildNodesByType(MethodDeclaration.class).forEach(md->{
         md.getType();
    });

    ParseUtils.compilationUnit(resultJavaFile).getClassByName("GenericResult")
            .ifPresent(classDeclaration -> {
                NodeList<TypeParameter> typeParameters = classDeclaration.getTypeParameters();
                for(int i = 0, len = typeParameters.size(); i != len; i++){
                    System.out.println(typeParameters.get(i).getName());
                }
            });
}
 
Example 2
Source Project: kogito-runtimes   Source File: BodyDeclarationComparator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int compare(BodyDeclaration<?> o1, BodyDeclaration<?> o2) {
    if (o1 instanceof FieldDeclaration && o2 instanceof FieldDeclaration) {
        return 0;
    }
    if (o1 instanceof FieldDeclaration && !(o2 instanceof FieldDeclaration)) {
        return -1;
    }
    
    if (o1 instanceof ConstructorDeclaration && o2 instanceof ConstructorDeclaration) {
        return 0;
    }
    if (o1 instanceof ConstructorDeclaration && o2 instanceof MethodDeclaration) {
        return -1;
    }
    if (o1 instanceof ConstructorDeclaration && o2 instanceof FieldDeclaration) {
        return 1;
    }
    return 1;
}
 
Example 3
Source Project: Refactoring-Bot   Source File: RemoveMethodParameter.java    License: MIT License 6 votes vote down vote up
/**
 * @param methodCall
 * @return true if given method call is related to target method, false
 *         otherwise
 */
private boolean isTargetMethodCall(MethodCallExpr methodCall) {
	for (MethodDeclaration targetMethod : allRefactoringRelevantMethodDeclarations) {
		String qualifiedMethodSignatureOfResolvedMethodCall = null;
		String qualifiedMethodSignatureOfTargetMethod = null;
		try {
			qualifiedMethodSignatureOfResolvedMethodCall = methodCall.resolve().getQualifiedSignature();
			qualifiedMethodSignatureOfTargetMethod = RefactoringHelper
					.getQualifiedMethodSignatureAsString(targetMethod);
		} catch (Exception e) {
			logger.error(e.getMessage());
			// TODO could be the case that an external dependency could not be resolved. In
			// such case it is fine to return false. However, it is an issue if a method
			// call that needs to be refactored can not be resolved.
			// see also RefactoringHelper.getQualifiedMethodSignatureAsString
			return false;
		}

		if (qualifiedMethodSignatureOfTargetMethod.equals(qualifiedMethodSignatureOfResolvedMethodCall)) {
			return true;
		}
	}

	return false;
}
 
Example 4
Source Project: dolphin   Source File: MethodDeclarationMerger.java    License: Apache License 2.0 6 votes vote down vote up
@Override public MethodDeclaration doMerge(MethodDeclaration first, MethodDeclaration second) {

    MethodDeclaration md = new MethodDeclaration();
    md.setName(first.getName());
    md.setType(mergeSingle(first.getType(), second.getType()));
    md.setJavaDoc(mergeSingle(first.getJavaDoc(), second.getJavaDoc()));
    md.setModifiers(mergeModifiers(first.getModifiers(), second.getModifiers()));

    md.setDefault(first.isDefault() || second.isDefault());
    md.setArrayCount(Math.max(first.getArrayCount(), second.getArrayCount()));

    md.setAnnotations(mergeCollections(first.getAnnotations(), second.getAnnotations()));

    md.setThrows(mergeListNoDuplicate(first.getThrows(), second.getThrows(), false));
    md.setParameters(mergeCollectionsInOrder(first.getParameters(), second.getParameters()));
    md.setTypeParameters(mergeCollectionsInOrder(first.getTypeParameters(), second.getTypeParameters()));

    md.setBody(mergeSingle(first.getBody(), second.getBody()));

    return md;
  }
 
Example 5
Source Project: kogito-runtimes   Source File: ProcessGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private MethodDeclaration createInstanceWithBusinessKeyMethod(String processInstanceFQCN) {
    MethodDeclaration methodDeclaration = new MethodDeclaration();

    ReturnStmt returnStmt = new ReturnStmt(
            new ObjectCreationExpr()
                    .setType(processInstanceFQCN)
                    .setArguments(NodeList.nodeList(
                            new ThisExpr(),
                            new NameExpr("value"),
                            new NameExpr(BUSINESS_KEY),
                            createProcessRuntime())));

    methodDeclaration.setName("createInstance")
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter(String.class.getCanonicalName(), BUSINESS_KEY)
            .addParameter(modelTypeName, "value")
            .setType(processInstanceFQCN)
            .setBody(new BlockStmt()
                             .addStatement(returnStmt));
    return methodDeclaration;
}
 
Example 6
Source Project: kogito-runtimes   Source File: ProcessGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private MethodDeclaration createInstanceGenericWithBusinessKeyMethod(String processInstanceFQCN) {
    MethodDeclaration methodDeclaration = new MethodDeclaration();

    ReturnStmt returnStmt = new ReturnStmt(
            new MethodCallExpr(new ThisExpr(), "createInstance")
            .addArgument(new NameExpr(BUSINESS_KEY))
            .addArgument(new CastExpr(new ClassOrInterfaceType(null, modelTypeName), new NameExpr("value"))));

    methodDeclaration.setName("createInstance")
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter(String.class.getCanonicalName(), BUSINESS_KEY)
            .addParameter(Model.class.getCanonicalName(), "value")
            .setType(processInstanceFQCN)
            .setBody(new BlockStmt()
                             .addStatement(returnStmt));
    return methodDeclaration;
}
 
Example 7
Source Project: Refactoring-Bot   Source File: RenameMethod.java    License: MIT License 6 votes vote down vote up
/**
 * @param methodCall
 * @return true if given method call is related to target method, false
 *         otherwise
 */
private boolean isTargetMethodCall(MethodCallExpr methodCall) {
	for (MethodDeclaration targetMethod : allRefactoringRelevantMethodDeclarations) {
		String qualifiedMethodSignatureOfResolvedMethodCall = null;
		String qualifiedMethodSignatureOfTargetMethod = null;
		try {
			qualifiedMethodSignatureOfResolvedMethodCall = methodCall.resolve().getQualifiedSignature();
			qualifiedMethodSignatureOfTargetMethod = RefactoringHelper
					.getQualifiedMethodSignatureAsString(targetMethod);
		} catch (Exception e) {
			logger.error(e.getMessage());
			// TODO could be the case that an external dependency could not be resolved. In
			// such case it is fine to return false. However, it is an issue if a method
			// call that needs to be refactored can not be resolved.
			// see also RefactoringHelper.getQualifiedMethodSignatureAsString
			return false;
		}

		if (qualifiedMethodSignatureOfTargetMethod.equals(qualifiedMethodSignatureOfResolvedMethodCall)) {
			return true;
		}
	}

	return false;
}
 
Example 8
/**
 * The purpose of this method is to 'visit' all test methods in the test file.
 */
@Override
public void visit(MethodDeclaration n, Void arg) {

    //JUnit 4
    //check if test method has Ignore annotation
    if (n.getAnnotationByName("Test").isPresent()) {
        if (n.getAnnotationByName("Ignore").isPresent()) {
            testMethod = new TestMethod(n.getNameAsString());
            testMethod.setHasSmell(true);
            smellyElementList.add(testMethod);
            return;
        }
    }

    //JUnit 3
    //check if test method is not public
    if (n.getNameAsString().toLowerCase().startsWith("test")) {
        if (!n.getModifiers().contains(Modifier.PUBLIC)) {
            testMethod = new TestMethod(n.getNameAsString());
            testMethod.setHasSmell(true);
            smellyElementList.add(testMethod);
            return;
        }
    }
}
 
Example 9
Source Project: selenium   Source File: CdpClientGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public TypeDeclaration<?> toTypeDeclaration() {
  ClassOrInterfaceDeclaration classDecl = new ClassOrInterfaceDeclaration().setName(name);

  String propertyName = decapitalize(name);
  classDecl.addField(getJavaType(), propertyName).setPrivate(true).setFinal(true);

  ConstructorDeclaration constructor = classDecl.addConstructor().setPublic(true);
  constructor.addParameter(getJavaType(), propertyName);
  constructor.getBody().addStatement(String.format(
      "this.%s = java.util.Objects.requireNonNull(%s, \"Missing value for %s\");",
      propertyName, propertyName, name
  ));

  MethodDeclaration fromJson = classDecl.addMethod("fromJson").setPrivate(true).setStatic(true);
  fromJson.setType(name);
  fromJson.addParameter(JsonInput.class, "input");
  fromJson.getBody().get().addStatement(String.format("return %s;", getMapper()));

  MethodDeclaration toString = classDecl.addMethod("toString").setPublic(true);
  toString.setType(String.class);
  toString.getBody().get().addStatement(String.format("return %s.toString();", propertyName));

  return classDecl;
}
 
Example 10
@Override
public void visit(MethodDeclaration n, Void arg) {
    if (Util.isValidTestMethod(n) || Util.isValidSetupMethod(n)) {
        currentMethod = n;
        testMethod = new TestMethod(n.getNameAsString());
        testMethod.setHasSmell(false); //default value is false (i.e. no smell)
        super.visit(n, arg);

        testMethod.setHasSmell(methodVariables.size() >= 1 || hasSmell==true);
        testMethod.addDataItem("ResourceOptimismCount", String.valueOf(resourceOptimismCount));

        smellyElementList.add(testMethod);

        //reset values for next method
        currentMethod = null;
        resourceOptimismCount = 0;
        hasSmell = false;
        methodVariables = new ArrayList<>();
    }
}
 
Example 11
Source Project: JRemapper   Source File: RegionMapper.java    License: MIT License 6 votes vote down vote up
/**
 * @param line
 *            Caret line in editor.
 * @param column
 *            Caret column in editor.
 * @return VDec at position. May be {@code null}.
 */
public VDec getVariableFromPosition(int line, int column) {
	Node node = getSimpleNodeAt(line, column);
	if (node instanceof SimpleName) {
		String name = ((SimpleName) node).asString();
		while (!(node instanceof MethodDeclaration)){
			Optional<Node> parent = node.getParentNode();
			if (!parent.isPresent())
				break;
			node = parent.get();
		}
		MDec owner = resolveMethod(node);
		if (owner != null && owner.isMethod()) {
			Optional<VDec> v = owner.getVariableByName(name);
			if (v.isPresent())
				return v.get();
		}
	}
	return null;
}
 
Example 12
Source Project: Refactoring-Bot   Source File: RefactoringHelper.java    License: MIT License 6 votes vote down vote up
/**
 * @param allJavaFiles
 * @param targetClass
 * @param targetMethod
 * @return list of qualified class or interface names which are reachable via
 *         the inheritance hierarchy of the given class (ancestors, descendants,
 *         siblings, ...) and contain the given target method
 * @throws BotRefactoringException
 * @throws FileNotFoundException
 */
public static Set<String> findRelatedClassesAndInterfaces(List<String> allJavaFiles,
		ClassOrInterfaceDeclaration targetClass, MethodDeclaration targetMethod)
		throws BotRefactoringException, FileNotFoundException {
	Set<ResolvedReferenceTypeDeclaration> relatedClassesAndInterfaces = new HashSet<>();
	relatedClassesAndInterfaces.add(targetClass.resolve());

	addQualifiedNamesToRelatedClassesAndInterfacesRecursively(relatedClassesAndInterfaces, allJavaFiles,
			targetClass, targetMethod);

	Set<String> result = new HashSet<>();
	for (ResolvedReferenceTypeDeclaration declaration : relatedClassesAndInterfaces) {
		result.add(declaration.getQualifiedName());
	}

	return result;
}
 
Example 13
Source Project: TestSmellDetector   Source File: SleepyTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void visit(MethodDeclaration n, Void arg) {
    if (Util.isValidTestMethod(n)) {
        currentMethod = n;
        testMethod = new TestMethod(n.getNameAsString());
        testMethod.setHasSmell(false); //default value is false (i.e. no smell)
        super.visit(n, arg);

        testMethod.setHasSmell(sleepCount >= 1);
        testMethod.addDataItem("ThreadSleepCount", String.valueOf(sleepCount));

        smellyElementList.add(testMethod);

        //reset values for next method
        currentMethod = null;
        sleepCount = 0;
    }
}
 
Example 14
Source Project: Refactoring-Bot   Source File: RenameMethod.java    License: MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String performRefactoring(BotIssue issue, GitConfiguration gitConfig) throws Exception {
	configureJavaParserForProject(issue);

	String newMethodName = issue.getRefactorString();
	String issueFilePath = gitConfig.getRepoFolder() + File.separator + issue.getFilePath();
	MethodDeclaration targetMethod = findAndValidateTargetMethod(issue, issueFilePath, newMethodName);
	ClassOrInterfaceDeclaration targetClass = RefactoringHelper.getClassOrInterfaceOfMethod(targetMethod);
	Set<String> qualifiedNamesOfRelatedClassesAndInterfaces = RefactoringHelper
			.findRelatedClassesAndInterfaces(issue.getAllJavaFiles(), targetClass, targetMethod);

	HashSet<String> javaFilesRelevantForRefactoring = findRelevantJavaFiles(issue, newMethodName, targetMethod,
			qualifiedNamesOfRelatedClassesAndInterfaces);
	renameRelatedMethodDeclarationsAndMethodCalls(javaFilesRelevantForRefactoring, newMethodName);

	String oldMethodName = targetMethod.getNameAsString();
	return "Renamed method '" + oldMethodName + "' to '" + newMethodName + "'";
}
 
Example 15
Source Project: kogito-runtimes   Source File: DecisionConfigGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private MethodDeclaration generateMergeEventListenerConfigMethod() {
    BlockStmt body = new BlockStmt().addStatement(new ReturnStmt(newObject(CachedDecisionEventListenerConfig.class,
            callMerge(
                    VAR_DECISION_EVENT_LISTENER_CONFIG,
                    DecisionEventListenerConfig.class, "listeners",
                    VAR_DMN_RUNTIME_EVENT_LISTENERS
            )
    )));

    return method(Modifier.Keyword.PRIVATE, DecisionEventListenerConfig.class, METHOD_MERGE_DECISION_EVENT_LISTENER_CONFIG,
            nodeList(
                    new Parameter().setType(genericType(Collection.class, DecisionEventListenerConfig.class)).setName(VAR_DECISION_EVENT_LISTENER_CONFIG),
                    new Parameter().setType(genericType(Collection.class, DMNRuntimeEventListener.class)).setName(VAR_DMN_RUNTIME_EVENT_LISTENERS)
            ),
            body);
}
 
Example 16
Source Project: kogito-runtimes   Source File: ApplicationGeneratorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void compilationUnitWithFactoryMethods() {
    final ApplicationGenerator appGenerator = new ApplicationGenerator(PACKAGE_NAME, new File("target"));
    final String testMethodName = "testMethod";
    final MethodDeclaration methodDeclaration = new MethodDeclaration();
    methodDeclaration.setName(testMethodName);

    appGenerator.addFactoryMethods(Collections.singleton(methodDeclaration));

    final CompilationUnit compilationUnit = appGenerator.compilationUnit();
    assertCompilationUnit(compilationUnit, false, 5);

    final TypeDeclaration mainAppClass = compilationUnit.getTypes().get(0);
    assertThat(mainAppClass.getMembers())
            .filteredOn(member -> member instanceof MethodDeclaration
                    && ((MethodDeclaration) member).getName().toString().equals(testMethodName))
            .hasSize(1);
}
 
Example 17
private static void extractResultsFromMethodDeclaration(MethodDeclaration md, CodeAnalysisResult result) {
    // Note that md.getEnd().get().line returns the last line of the method, not of the signature
    if (!md.getBody().isPresent()) {
        return;
    }
    BlockStmt body = md.getBody().get();

    // Since a signature might span over different lines we need to get to its body and take its beginning
    // Also note that interfaces have no body ! So this might fail !
    int methodBegin = md.getBegin().get().line;
    int methodBodyBegin = body.getBegin().get().line;
    int methodEnd = md.getEnd().get().line;
    for (int line = methodBegin; line <= methodBodyBegin; line++) {
        // method signatures are non coverable
        result.nonCoverableCode(line);
    }

    String signature = md.getDeclarationAsString(false, false, false);
    signature = signature.substring(signature.indexOf(' ') + 1); // Remove return type

    result.methodSignatures(Range.between(methodBegin, methodBodyBegin));
    result.methods(Range.between(methodBegin, methodEnd));
    result.testAccordionMethodDescription(signature, methodBegin, methodEnd);
}
 
Example 18
Source Project: Refactoring-Bot   Source File: RemoveMethodParameter.java    License: MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String performRefactoring(BotIssue issue, GitConfiguration gitConfig) throws Exception {
	configureJavaParserForProject(issue);

	String parameterName = issue.getRefactorString();
	String issueFilePath = gitConfig.getRepoFolder() + File.separator + issue.getFilePath();
	MethodDeclaration targetMethod = findAndValidateTargetMethod(issue, issueFilePath, parameterName);
	ClassOrInterfaceDeclaration targetClass = RefactoringHelper.getClassOrInterfaceOfMethod(targetMethod);
	Set<String> qualifiedNamesOfRelatedClassesAndInterfaces = RefactoringHelper
			.findRelatedClassesAndInterfaces(issue.getAllJavaFiles(), targetClass, targetMethod);

	HashSet<String> javaFilesRelevantForRefactoring = findRelevantJavaFiles(issue, parameterName,
			targetMethod, qualifiedNamesOfRelatedClassesAndInterfaces);
	removeParameterFromRelatedMethodDeclarationsAndMethodCalls(javaFilesRelevantForRefactoring, targetMethod,
			parameterName);

	String targetMethodSignature = RefactoringHelper.getLocalMethodSignatureAsString(targetMethod);
	return "Removed parameter '" + parameterName + "' from method '" + targetMethodSignature + "'";
}
 
Example 19
public MethodDeclaration generateMethod(WorkflowProcess process) {

        CompilationUnit clazz = parse(this.getClass().getResourceAsStream("/class-templates/ProcessTemplate.java"));
        clazz.setPackageDeclaration(process.getPackageName());

        String extractedProcessId = extractProcessId(process.getId());

        String packageName = clazz.getPackageDeclaration().map(NodeWithName::getNameAsString).orElse(null);
        ProcessMetaData metadata = new ProcessMetaData(process.getId(),
                extractedProcessId,
                process.getName(),
                process.getVersion(),
                packageName,
                "process");

        MethodDeclaration processMethod = new MethodDeclaration();
        processVisitor.visitProcess(process, processMethod, metadata);

        return processMethod;
    }
 
Example 20
Source Project: JApiDocs   Source File: PlayControllerParser.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void afterHandleMethod(RequestNode requestNode, MethodDeclaration md) {
    PlayRoutesParser.RouteNode routeNode = PlayRoutesParser.INSTANCE.getRouteNode(getControllerFile(), md.getNameAsString());
    if(routeNode == null){
        return;
    }

    String method = routeNode.method.toUpperCase();
    if("*".equals(method)) {
        requestNode.setMethod(Arrays.asList(RequestMethod.GET.name(), RequestMethod.POST.name()));
    } else {
        requestNode.addMethod(RequestMethod.valueOf(method).name());
    }

    requestNode.setUrl(routeNode.routeUrl);

    md.getParameters().forEach(p -> {
        String paraName  = p.getName().asString();
        ParamNode paramNode = requestNode.getParamNodeByName(paraName);
        if(paramNode != null){
            p.getAnnotationByName("Required").ifPresent(r -> {
                paramNode.setRequired(true);
            });
        }
    });
}
 
Example 21
@Override
public void visit(MethodDeclaration n, Void arg) {
    if (Util.isValidTestMethod(n)) {
        currentMethod = n;

        //call visit(NameExpr) for current method
        super.visit(n, arg);

        testMethod = new TestMethod(n.getNameAsString());
        testMethod.setHasSmell(fixtureCount.size() != setupFields.size());
        smellyElementList.add(testMethod);

        fixtureCount = new HashSet();;
        currentMethod = null;
    }
}
 
Example 22
Source Project: selenium   Source File: CdpClientGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public BodyDeclaration<?> toMethodDeclaration() {
  MethodDeclaration methodDecl = new MethodDeclaration().setName(name).setPublic(true).setStatic(true);
  if (type == null) {
    methodDecl.setType("Event<Void>").getBody().get().addStatement(
        String.format("return new Event<>(\"%s.%s\");", domain.name, name));
  } else {
    methodDecl.setType(String.format("Event<%s>", getFullJavaType()));
    if (type instanceof VoidType) {
      methodDecl.getBody().get().addStatement(
          String.format("return new Event<>(\"%s.%s\", input -> null);", domain.name, name));
    } else if (type instanceof ObjectType) {
      methodDecl.getBody().get().addStatement(String.format(
          "return new Event<>(\"%s.%s\", input -> %s);",
          domain.name, name, type.getMapper()));
    } else {
      methodDecl.getBody().get().addStatement(String.format(
          "return new Event<>(\"%s.%s\", ConverterFunctions.map(\"%s\", %s));",
          domain.name, name, type.getName(), type.getTypeToken()));
    }
  }
  return methodDecl;
}
 
Example 23
Source Project: Refactoring-Bot   Source File: RemoveMethodParameter.java    License: MIT License 6 votes vote down vote up
/**
 * Tries to find the target method in the given class or interface. Checks if
 * the found method itself could be refactored, without yet checking other code
 * locations
 * 
 * @param issue
 * @param filePath
 * @param parameterToBeRemoved
 * @return
 * @throws BotRefactoringException
 * @throws FileNotFoundException
 */
private MethodDeclaration findAndValidateTargetMethod(BotIssue issue, String filePath, String parameterToBeRemoved)
		throws BotRefactoringException, FileNotFoundException {
	List<ClassOrInterfaceDeclaration> classesAndInterfaces = RefactoringHelper
			.getAllClassesAndInterfacesFromFile(filePath);

	MethodDeclaration targetMethod = null;
	for (ClassOrInterfaceDeclaration classOrInterface : classesAndInterfaces) {
		for (MethodDeclaration currentMethod : classOrInterface.getMethods()) {
			if (RefactoringHelper.isMethodDeclarationAtLine(currentMethod, issue.getLine())) {
				targetMethod = currentMethod;
				break;
			}
		}
		if (targetMethod != null) {
			break;
		}
	}

	if (targetMethod == null) {
		throw new BotRefactoringException("Could not find a method declaration at the given line!");
	}
	validateMethodHasParameter(targetMethod, parameterToBeRemoved);
	validateParameterUnused(targetMethod, parameterToBeRemoved);
	return targetMethod;
}
 
Example 24
Source Project: gauge-java   Source File: RegistryMethodVisitor.java    License: Apache License 2.0 6 votes vote down vote up
private String getClassName(MethodDeclaration methodDeclaration) {
    AtomicReference<String> className = new AtomicReference<>();
    methodDeclaration.findAncestor(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration.class)
            .ifPresent(c -> className.set(c.getNameAsString()));
    String classNameStr = className.get() == null ? null : className.get();
    if (classNameStr == null) {
        return null;
    }

    AtomicReference<Name> packageName = new AtomicReference<>();
    methodDeclaration.findCompilationUnit()
            .ifPresent(c -> c.getPackageDeclaration()
                    .ifPresent(p -> packageName.set(p.getName()))
            );
    String packageNameStr = packageName.get() == null ? null : packageName.get().asString();

    if (packageNameStr == null) {
        return classNameStr;
    }
    return packageNameStr + "." + classNameStr;
}
 
Example 25
Source Project: apigcc   Source File: VisitorParser.java    License: MIT License 6 votes vote down vote up
@Override
public void visit(final MethodDeclaration n, final Node arg) {
    if (arg instanceof Chapter && parserStrategy.accept(n)) {
        Chapter chapter = (Chapter) arg;
        Section section = new Section();
        section.setId(n.getNameAsString());
        section.setName(n.getNameAsString());
        section.setIndex(chapter.getSections().size());
        n.getComment().ifPresent(section::accept);

        parserStrategy.visit(n, chapter, section);

        visitReturn(n, section);

        chapter.getSections().add(section);
        super.visit(n, section);
    }
}
 
Example 26
Source Project: apigcc   Source File: VisitorParser.java    License: MIT License 6 votes vote down vote up
/**
 * 解析方法返回类型
 * @param n
 * @param section
 */
private void visitReturn(MethodDeclaration n, Section section) {
    Optional<Tag> optional = section.tag("return");
    if(optional.isPresent()){
        //解析@return标签
        String content = optional.get().getContent();
        if (StringHelper.nonBlank(content)) {
            section.setRawResponse(content);
            return;
        }
    }
    TypeDescription description = Apigcc.getInstance().getTypeResolvers().resolve(n.getType());
    if(description.isAvailable()){
        if(description.isPrimitive() || description.isString()){
            section.setRawResponse(description.getValue());
        }else if(description.isArray()){
            section.setResponse(description.asArray().getValue());
        }else if(description.isObject()){
            section.setResponse(description.asObject().getValue());
        }
        section.addResponseRows(description.rows());
    }
}
 
Example 27
Source Project: Refactoring-Bot   Source File: RenameMethod.java    License: MIT License 5 votes vote down vote up
/**
 * Tries to find the target method in the given class or interface. Checks if
 * the found method itself could be refactored, without yet checking other code
 * locations
 * 
 * @param issue
 * @param filePath
 * @param newMethodName
 * @return
 * @throws BotRefactoringException
 * @throws FileNotFoundException
 */
private MethodDeclaration findAndValidateTargetMethod(BotIssue issue, String filePath, String newMethodName)
		throws BotRefactoringException, FileNotFoundException {
	List<ClassOrInterfaceDeclaration> classesAndInterfaces = RefactoringHelper
			.getAllClassesAndInterfacesFromFile(filePath);

	MethodDeclaration targetMethod = null;
	for (ClassOrInterfaceDeclaration classOrInterface : classesAndInterfaces) {
		for (MethodDeclaration currentMethod : classOrInterface.getMethods()) {
			if (RefactoringHelper.isMethodDeclarationAtLine(currentMethod, issue.getLine())) {
				targetMethod = currentMethod;
				break;
			}
		}
		if (targetMethod != null) {
			break;
		}
	}

	if (targetMethod == null) {
		throw new BotRefactoringException("Could not find specified method declaration at given line!");
	}

	String oldMethodName = targetMethod.getNameAsString();
	if (oldMethodName.equals(newMethodName)) {
		throw new BotRefactoringException("New method name must differ from the current one!");
	}

	return targetMethod;
}
 
Example 28
Source Project: Refactoring-Bot   Source File: RemoveMethodParameterTest.java    License: MIT License 5 votes vote down vote up
/**
 * Test whether the refactoring was performed correctly in the sub class of the
 * target class (descendant)
 * 
 * @throws Exception
 */
@Test
public void testSubClassRefactored() throws Exception {
	// arrange
	List<File> filesToConsider = new ArrayList<File>();
	filesToConsider.add(fileOfTestClass);
	filesToConsider.add(fileOfSubClass);
	int lineNumberOfMethodWithParameterToBeRemoved = removeParameterTestClass.getLineOfMethodWithUnusedParameter(0,
			0, 0);
	String parameterName = "b";

	CompilationUnit cuOriginalFileOfSubClass = StaticJavaParser.parse(fileOfSubClass);
	MethodDeclaration originalMethodInSubClass = RefactoringHelper.getMethodDeclarationByLineNumber(
			removeParameterSubClass.getLineOfMethodWithUnusedParameter(0, 0, 0), cuOriginalFileOfSubClass);
	assertThat(originalMethodInSubClass).isNotNull();

	// act
	performRemoveParameter(filesToConsider, fileOfTestClass, lineNumberOfMethodWithParameterToBeRemoved,
			parameterName);

	// assert that target's sub class has been refactored
	CompilationUnit cuRefactoredFileOfSubClass = StaticJavaParser.parse(fileOfSubClass);
	String methodInSubClassName = originalMethodInSubClass.getNameAsString();
	MethodDeclaration methodInSubClass = getMethodByName(SUB_CLASS_NAME, methodInSubClassName,
			cuRefactoredFileOfSubClass);
	assertThat(methodInSubClass).isNotNull();
	assertThat(methodInSubClass.getParameterByName(parameterName).isPresent()).isFalse();
}
 
Example 29
Source Project: TestSmellDetector   Source File: Util.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static boolean isValidTestMethod(MethodDeclaration n) {
    boolean valid = false;

    if (!n.getAnnotationByName("Ignore").isPresent()) {
        //only analyze methods that either have a @test annotation (Junit 4) or the method name starts with 'test'
        if (n.getAnnotationByName("Test").isPresent() || n.getNameAsString().toLowerCase().startsWith("test")) {
            //must be a public method
            if (n.getModifiers().contains(Modifier.PUBLIC)) {
                valid = true;
            }
        }
    }

    return valid;
}
 
Example 30
Source Project: Refactoring-Bot   Source File: RemoveMethodParameterTest.java    License: MIT License 5 votes vote down vote up
/**
 * Test that the refactoring algorithm finds the correct method in case that
 * there is an inner class before the target method declaration
 * 
 * @throws Exception
 */
@Test
public void testRefactoringOfMethodPlacedAfterInnerClass() throws Exception {
	// arrange
	List<File> filesToConsider = new ArrayList<File>();
	filesToConsider.add(fileOfTestClass);
	int lineNumberOfMethodWithParameterToBeRemoved = removeParameterTestClass
			.getLineOfMethodPlacedInAndAfterInnerClass(0, 0, 0);
	String parameterName = "b";

	CompilationUnit cuOriginalFileOfTestClass = StaticJavaParser.parse(fileOfTestClass);
	MethodDeclaration originalMethod = RefactoringHelper.getMethodDeclarationByLineNumber(
			lineNumberOfMethodWithParameterToBeRemoved, cuOriginalFileOfTestClass);
	assertThat(originalMethod).isNotNull();

	// act
	performRemoveParameter(filesToConsider, fileOfTestClass, lineNumberOfMethodWithParameterToBeRemoved,
			parameterName);

	// assert that method in outer class (the method for which the actual renaming
	// was intended) has been refactored
	CompilationUnit cuRefactoredFileOfTestClass = StaticJavaParser.parse(fileOfTestClass);
	MethodDeclaration refactoredMethod = RefactoringHelper.getMethodDeclarationByLineNumber(
			lineNumberOfMethodWithParameterToBeRemoved, cuRefactoredFileOfTestClass);
	assertThat(refactoredMethod).isNotNull();
	assertThat(refactoredMethod.getParameterByName(parameterName).isPresent()).isFalse();
}