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

The following examples show how to use com.github.javaparser.ast.body.MethodDeclaration. 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: ParseUtilsTest.java    From JApiDocs with 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 File: RefactoringHelper.java    From Refactoring-Bot with 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 #3
Source File: MethodDeclarationMerger.java    From dolphin with 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 #4
Source File: VisitorParser.java    From apigcc with 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 #5
Source File: ProcessToExecModelGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
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 #6
Source File: CdpClientGenerator.java    From selenium with 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 #7
Source File: BodyDeclarationComparator.java    From kogito-runtimes with 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 #8
Source File: PlayControllerParser.java    From JApiDocs with 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 #9
Source File: VisitorParser.java    From apigcc with 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 #10
Source File: RemoveMethodParameter.java    From Refactoring-Bot with 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 #11
Source File: RemoveMethodParameter.java    From Refactoring-Bot with 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 #12
Source File: ClassCodeAnalyser.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #13
Source File: ProcessGenerator.java    From kogito-runtimes with 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 #14
Source File: ApplicationGeneratorTest.java    From kogito-runtimes with 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 #15
Source File: ProcessGenerator.java    From kogito-runtimes with 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 #16
Source File: RenameMethod.java    From Refactoring-Bot with 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 #17
Source File: IgnoredTest.java    From TestSmellDetector with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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 #18
Source File: CdpClientGenerator.java    From selenium with 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 #19
Source File: DecisionConfigGenerator.java    From kogito-runtimes with 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 #20
Source File: RegistryMethodVisitor.java    From gauge-java with 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 #21
Source File: ResourceOptimism.java    From TestSmellDetector with GNU General Public License v3.0 6 votes vote down vote up
@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 #22
Source File: RenameMethod.java    From Refactoring-Bot with 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 #23
Source File: SleepyTest.java    From TestSmellDetector with 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 #24
Source File: RemoveMethodParameter.java    From Refactoring-Bot with 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 #25
Source File: RegionMapper.java    From JRemapper with 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 #26
Source File: GeneralFixture.java    From TestSmellDetector with 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;

        //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 #27
Source File: ConfigurableEagerTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * The purpose of this method is to 'visit' all test methods.
 */
@Override
public void visit(MethodDeclaration n, Void arg) {
    // ensure that this method is only executed for the test file
    if (Objects.equals(fileType, TEST_FILE)) {
        if (Util.isValidTestMethod(n)) {
            currentMethod = n;
            testMethod = new TestMethod(currentMethod.getNameAsString());
            testMethod.setHasSmell(false); // default value is false
                                           // (i.e. no smell)
            super.visit(n, arg);

            /*
             * the method has a smell if there is more than threshold calls to
             * production methods (not considering the ones inside assertions!)
             */

            testMethod.setHasSmell(eagerCount > threshold);
            smellyElementList.add(testMethod);

            // reset values for next method
            currentMethod = null;
            eagerCount = 0;
            productionVariables = new ArrayList<>();
            calledMethods = new ArrayList<>();
        }
    } else { // collect a list of all public/protected members of the
             // production class
        for (Modifier modifier : n.getModifiers()) {
            if (modifier.name().toLowerCase().equals("public")
                    || modifier.name().toLowerCase().equals("protected")) {
                productionMethods.add(n);
            }
        }

    }
}
 
Example #28
Source File: DMNRestResourceGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void addExceptionMetricsLogging(ClassOrInterfaceDeclaration template, String nameURL) {
    MethodDeclaration method = template.findFirst(MethodDeclaration.class, x -> "toResponse".equals(x.getNameAsString()))
            .orElseThrow(() -> new NoSuchElementException("Method toResponse not found, template has changed."));

    BlockStmt body = method.getBody().orElseThrow(() -> new NoSuchElementException("This method should be invoked only with concrete classes and not with abstract methods or interfaces."));
    ReturnStmt returnStmt = body.findFirst(ReturnStmt.class).orElseThrow(() -> new NoSuchElementException("Check for null dmn result not found, can't add monitoring to endpoint."));
    NodeList<Statement> statements = body.getStatements();
    String methodArgumentName = method.getParameters().get(0).getNameAsString();
    statements.addBefore(parseStatement(String.format("SystemMetricsCollector.registerException(\"%s\", %s.getStackTrace()[0].toString());", nameURL, methodArgumentName)), returnStmt);
}
 
Example #29
Source File: OpenApiObjectGenerator.java    From flow with Apache License 2.0 5 votes vote down vote up
private boolean isAccessForbidden(
        ClassOrInterfaceDeclaration typeDeclaration,
        MethodDeclaration methodDeclaration) {
    return !methodDeclaration.isPublic()
            || (hasSecurityAnnotation(methodDeclaration)
                    ? methodDeclaration.isAnnotationPresent(DenyAll.class)
                    : typeDeclaration.isAnnotationPresent(DenyAll.class));
}
 
Example #30
Source File: TypeErasureAnalyzer.java    From deadcode4j with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(MethodDeclaration n, A arg) {
    this.definedTypeParameters.addLast(getTypeParameterNames(n.getTypeParameters()));
    try {
        super.visit(n, arg);
    } finally {
        this.definedTypeParameters.removeLast();
    }
}