Java Code Examples for com.github.javaparser.ast.expr.MethodCallExpr

The following examples show how to use com.github.javaparser.ast.expr.MethodCallExpr. 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: TestSmellDetector   Source File: LazyTest.java    License: GNU General Public License v3.0 7 votes vote down vote up
/**
 * The purpose of this method is to identify the production class methods that are called from the test method
 * When the parser encounters a method call:
 * 1) the method is contained in the productionMethods list
 * or
 * 2) the code will check the 'scope' of the called method
 * A match is made if the scope is either:
 * equal to the name of the production class (as in the case of a static method) or
 * if the scope is a variable that has been declared to be of type of the production class (i.e. contained in the 'productionVariables' list).
 */
@Override
public void visit(MethodCallExpr n, Void arg) {
    super.visit(n, arg);
    if (currentMethod != null) {
        if (productionMethods.stream().anyMatch(i -> i.getNameAsString().equals(n.getNameAsString()) &&
                i.getParameters().size() == n.getArguments().size())) {
            calledProductionMethods.add(new MethodUsage(currentMethod.getNameAsString(), n.getNameAsString()));
        } else {
            if (n.getScope().isPresent()) {
                if (n.getScope().get() instanceof NameExpr) {
                    //checks if the scope of the method being called is either of production class (e.g. static method)
                    //or
                    ///if the scope matches a variable which, in turn, is of type of the production class
                    if (((NameExpr) n.getScope().get()).getNameAsString().equals(productionClassName) ||
                            productionVariables.contains(((NameExpr) n.getScope().get()).getNameAsString())) {
                        calledProductionMethods.add(new MethodUsage(currentMethod.getNameAsString(), n.getNameAsString()));
                    }
                }
            }
        }
    }
}
 
Example 2
Source Project: kogito-runtimes   Source File: WorkItemNodeVisitor.java    License: Apache License 2.0 6 votes vote down vote up
private Expression getParameterExpr(String type, String value) {
    ParamType pType = ParamType.fromString(type);
    if (pType == null) {
        return new StringLiteralExpr(value);
    }
    switch (pType) {
        case BOOLEAN:
            return new BooleanLiteralExpr(Boolean.parseBoolean(value));
        case FLOAT:
            return new MethodCallExpr()
                    .setScope(new NameExpr(Float.class.getName()))
                    .setName("parseFloat")
                    .addArgument(new StringLiteralExpr(value));
        case INTEGER:
            return new IntegerLiteralExpr(Integer.parseInt(value));
        default:
            return new StringLiteralExpr(value);
    }
}
 
Example 3
Source Project: uima-uimaj   Source File: MigrateJCas.java    License: Apache License 2.0 6 votes vote down vote up
/**
   * visitor for field access expressions
   *   - convert ((...type_Type)jcasType).casFeatCode_XXXX to _FI_xxx
   * @param n -
   * @param ignore -
   */
  @Override
  public void visit(FieldAccessExpr n, Object ignore) {
    Expression e;
    Optional<Expression> oe;
    String nname = n.getNameAsString();
    
    if (get_set_method != null) {  
      if (nname.startsWith("casFeatCode_") &&
          ((oe = n.getScope()).isPresent()) &&
          ((e = getUnenclosedExpr(oe.get())) instanceof CastExpr) &&
          ("jcasType".equals(getName(((CastExpr)e).getExpression())))) {
        String featureName = nname.substring("casFeatCode_".length());
//        replaceInParent(n, new NameExpr("_FI_" + featureName)); // repl last in List<Expression> (args)
        
        MethodCallExpr getint = new MethodCallExpr(null, "wrapGetIntCatchException");
        getint.addArgument(new NameExpr("_FH_" + featureName));
        replaceInParent(n, getint);
        
        return;
      } else if (nname.startsWith("casFeatCode_")) {
        reportMigrateFailed("Found field casFeatCode_ ... without a previous cast expr using jcasType");
      }
    }
    super.visit(n,  ignore);      
  }
 
Example 4
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 5
Source Project: kogito-runtimes   Source File: RuleUnitInstanceGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public ClassOrInterfaceDeclaration classDeclaration() {
    String canonicalName = ruleUnitDescription.getRuleUnitName();
    ClassOrInterfaceDeclaration classDecl = new ClassOrInterfaceDeclaration()
            .setName(targetTypeName)
            .addModifier(Modifier.Keyword.PUBLIC);
    classDecl
            .addExtendedType(
                    new ClassOrInterfaceType(null, AbstractRuleUnitInstance.class.getCanonicalName())
                            .setTypeArguments(new ClassOrInterfaceType(null, canonicalName)))
            .addConstructor(Modifier.Keyword.PUBLIC)
            .addParameter(RuleUnitGenerator.ruleUnitType(canonicalName), "unit")
            .addParameter(canonicalName, "value")
            .addParameter(KieSession.class.getCanonicalName(), "session")
            .setBody(new BlockStmt().addStatement(new MethodCallExpr(
                    "super",
                    new NameExpr("unit"),
                    new NameExpr("value"),
                    new NameExpr("session")
            )));
    classDecl.addMember(bindMethod());
    classDecl.getMembers().sort(new BodyDeclarationComparator());
    return classDecl;
}
 
Example 6
@Override
public List<Statement> setupStatements() {
    return Collections.singletonList(
            new IfStmt(
                    new BinaryExpr(
                            new MethodCallExpr(new MethodCallExpr(null, "config"), "decision"),
                            new NullLiteralExpr(),
                            BinaryExpr.Operator.NOT_EQUALS
                    ),
                    new BlockStmt().addStatement(new ExpressionStmt(new MethodCallExpr(
                            new NameExpr("decisionModels"), "init", NodeList.nodeList(new ThisExpr())
                    ))),
                    null
            )
    );
}
 
Example 7
Source Project: kogito-runtimes   Source File: StateNodeVisitor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Stream<MethodCallExpr> visitCustomFields(StateNode node, VariableScope variableScope) {
    if (node.getConstraints() == null) {
        return Stream.empty();
    }
    return node.getConstraints()
            .entrySet()
            .stream()
            .map((e -> getFactoryMethod(getNodeId(node), METHOD_CONSTRAINT,
                    getOrNullExpr(e.getKey().getConnectionId()),
                    new LongLiteralExpr(e.getKey().getNodeId()),
                    new StringLiteralExpr(e.getKey().getToType()),
                    new StringLiteralExpr(e.getValue().getDialect()),
                    new StringLiteralExpr(StringEscapeUtils.escapeJava(e.getValue().getConstraint())),
                    new IntegerLiteralExpr(e.getValue().getPriority()))));
}
 
Example 8
Source Project: kogito-runtimes   Source File: TriggerMetaData.java    License: Apache License 2.0 6 votes vote down vote up
public static LambdaExpr buildLambdaExpr(Node node, ProcessMetaData metadata) {
    Map<String, Object> nodeMetaData = node.getMetaData();
    TriggerMetaData triggerMetaData = new TriggerMetaData(
            (String) nodeMetaData.get(TRIGGER_REF),
            (String) nodeMetaData.get(TRIGGER_TYPE),
            (String) nodeMetaData.get(MESSAGE_TYPE),
            (String) nodeMetaData.get(MAPPING_VARIABLE),
            String.valueOf(node.getId()))
            .validate();
    metadata.getTriggers().add(triggerMetaData);

    // and add trigger action
    BlockStmt actionBody = new BlockStmt();
    CastExpr variable = new CastExpr(
            new ClassOrInterfaceType(null, triggerMetaData.getDataType()),
            new MethodCallExpr(new NameExpr(KCONTEXT_VAR), "getVariable")
                    .addArgument(new StringLiteralExpr(triggerMetaData.getModelRef())));
    MethodCallExpr producerMethodCall = new MethodCallExpr(new NameExpr("producer_" + node.getId()), "produce").addArgument(new MethodCallExpr(new NameExpr("kcontext"), "getProcessInstance")).addArgument(variable);
    actionBody.addStatement(producerMethodCall);
    return new LambdaExpr(
            new Parameter(new UnknownType(), KCONTEXT_VAR), // (kcontext) ->
            actionBody
    );
}
 
Example 9
protected Expression dotNotationToSetExpression(String dotNotation, String value) {
    String[] elements = dotNotation.split("\\.");
    Expression scope = new NameExpr(elements[0]);
    if (elements.length == 1) {
        return new AssignExpr(
                scope,
                new NameExpr(value),
                AssignExpr.Operator.ASSIGN);
    }
    for (int i = 1; i < elements.length - 1; i++) {
        scope = new MethodCallExpr()
                .setScope(scope)
                .setName("get" + StringUtils.capitalize(elements[i]));
    }

    return new MethodCallExpr()
            .setScope(scope)
            .setName("set" + StringUtils.capitalize(elements[elements.length - 1]))
            .addArgument(value);
}
 
Example 10
protected Expression dotNotationToGetExpression(String dotNotation) {
    String[] elements = dotNotation.split("\\.");
    Expression scope = new NameExpr(elements[0]);

    if (elements.length == 1) {
        return scope;
    }

    for (int i = 1; i < elements.length; i++) {
        scope = new MethodCallExpr()
                .setScope(scope)
                .setName("get" + StringUtils.capitalize(elements[i]));
    }

    return scope;
}
 
Example 11
@Override
public void visit(MethodCallExpr n, Void arg) {
    super.visit(n, arg);
    if (currentMethod != null) {
        // if the name of a method being called is 'print' or 'println' or 'printf' or 'write'
        if (n.getNameAsString().equals("print") || n.getNameAsString().equals("println") || n.getNameAsString().equals("printf") || n.getNameAsString().equals("write")) {
            //check the scope of the method & proceed only if the scope is "out"
            if ((n.getScope().isPresent() &&
                    n.getScope().get() instanceof FieldAccessExpr &&
                    (((FieldAccessExpr) n.getScope().get())).getNameAsString().equals("out"))) {

                FieldAccessExpr f1 = (((FieldAccessExpr) n.getScope().get()));

                //check the scope of the field & proceed only if the scope is "System"
                if ((f1.getScope() != null &&
                        f1.getScope() instanceof NameExpr &&
                        ((NameExpr) f1.getScope()).getNameAsString().equals("System"))) {
                    //a print statement exists in the method body
                    printCount++;
                }
            }

        }
    }
}
 
Example 12
Source Project: kogito-runtimes   Source File: RuleSetNodeVisitor.java    License: Apache License 2.0 6 votes vote down vote up
private MethodCallExpr handleDecision(RuleSetNode.RuleType.Decision ruleType) {

        StringLiteralExpr namespace = new StringLiteralExpr(ruleType.getNamespace());
        StringLiteralExpr model = new StringLiteralExpr(ruleType.getModel());
        Expression decision = ruleType.getDecision() == null ?
                new NullLiteralExpr() : new StringLiteralExpr(ruleType.getDecision());

        MethodCallExpr decisionModels =
                new MethodCallExpr(new NameExpr("app"), "decisionModels");
        MethodCallExpr decisionModel =
                new MethodCallExpr(decisionModels, "getDecisionModel")
                        .addArgument(namespace)
                        .addArgument(model);

        BlockStmt actionBody = new BlockStmt();
        LambdaExpr lambda = new LambdaExpr(new Parameter(new UnknownType(), "()"), actionBody);
        actionBody.addStatement(new ReturnStmt(decisionModel));

        return new MethodCallExpr(METHOD_DECISION)
                .addArgument(namespace)
                .addArgument(model)
                .addArgument(decision)
                .addArgument(lambda);
    }
 
Example 13
Source Project: kogito-runtimes   Source File: RuleSetNodeVisitor.java    License: Apache License 2.0 6 votes vote down vote up
private MethodCallExpr handleRuleUnit(VariableScope variableScope, ProcessMetaData metadata, RuleSetNode ruleSetNode, String nodeName, RuleSetNode.RuleType ruleType) {
    String unitName = ruleType.getName();
    ProcessContextMetaModel processContext = new ProcessContextMetaModel(variableScope, contextClassLoader);
    RuleUnitDescription description;

    try {
        Class<?> unitClass = loadUnitClass(nodeName, unitName, metadata.getPackageName());
        description = new ReflectiveRuleUnitDescription(null, (Class<? extends RuleUnitData>) unitClass);
    } catch (ClassNotFoundException e) {
        logger.warn("Rule task \"{}\": cannot load class {}. " +
                "The unit data object will be generated.", nodeName, unitName);

        GeneratedRuleUnitDescription d = generateRuleUnitDescription(unitName, processContext);
        RuleUnitComponentFactoryImpl impl = (RuleUnitComponentFactoryImpl) RuleUnitComponentFactory.get();
        impl.registerRuleUnitDescription(d);
        description = d;
    }

    RuleUnitHandler handler = new RuleUnitHandler(description, processContext, ruleSetNode, assignableChecker);
    Expression ruleUnitFactory = handler.invoke();

    return new MethodCallExpr("ruleUnit")
            .addArgument(new StringLiteralExpr(ruleType.getName()))
            .addArgument(ruleUnitFactory);

}
 
Example 14
Source Project: kogito-runtimes   Source File: RuleSetNodeVisitor.java    License: Apache License 2.0 6 votes vote down vote up
private MethodCallExpr handleRuleFlowGroup(RuleSetNode.RuleType ruleType) {
    // build supplier for rule runtime
    BlockStmt actionBody = new BlockStmt();
    LambdaExpr lambda = new LambdaExpr(new Parameter(new UnknownType(), "()"), actionBody);

    MethodCallExpr ruleRuntimeBuilder = new MethodCallExpr(
            new MethodCallExpr(new NameExpr("app"), "ruleUnits"), "ruleRuntimeBuilder");
    MethodCallExpr ruleRuntimeSupplier = new MethodCallExpr(
            ruleRuntimeBuilder, "newKieSession",
            NodeList.nodeList(new StringLiteralExpr("defaultStatelessKieSession"), new NameExpr("app.config().rule()")));
    actionBody.addStatement(new ReturnStmt(ruleRuntimeSupplier));

    return new MethodCallExpr("ruleFlowGroup")
            .addArgument(new StringLiteralExpr(ruleType.getName()))
            .addArgument(lambda);

}
 
Example 15
Source Project: kogito-runtimes   Source File: RuleUnitMetaModel.java    License: Apache License 2.0 6 votes vote down vote up
public Statement injectCollection(
        String targetUnitVar, String sourceProcVar) {
    BlockStmt blockStmt = new BlockStmt();
    RuleUnitVariable v = ruleUnitDescription.getVar(targetUnitVar);
    String appendMethod = appendMethodOf(v.getType());
    blockStmt.addStatement(assignVar(v));
    blockStmt.addStatement(
            iterate(new VariableDeclarator()
                            .setType("Object").setName("it"),
                    new NameExpr(sourceProcVar))
                    .setBody(new ExpressionStmt(
                            new MethodCallExpr()
                                    .setScope(new NameExpr(localVarName(v)))
                                    .setName(appendMethod)
                                    .addArgument(new NameExpr("it")))));
    return blockStmt;
}
 
Example 16
Source Project: kogito-runtimes   Source File: RuleUnitMetaModel.java    License: Apache License 2.0 5 votes vote down vote up
public Statement extractIntoScalar(String sourceUnitVar, String targetProcessVar) {
    BlockStmt blockStmt = new BlockStmt();
    RuleUnitVariable v = ruleUnitDescription.getVar(sourceUnitVar);
    String localVarName = localVarName(v);
    blockStmt.addStatement(assignVar(v))
            .addStatement(new ExpressionStmt(
                    new MethodCallExpr(new NameExpr(localVarName), "subscribe")
                            .addArgument(new MethodCallExpr(
                                    new NameExpr(DataObserver.class.getCanonicalName()), "ofUpdatable")
                                                 .addArgument(parseExpression("o -> kcontext.setVariable(\"" + targetProcessVar + "\", o)")))));

    return blockStmt;
}
 
Example 17
Source Project: enkan   Source File: AppendRoutingVisitor.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public void visit(final MethodCallExpr n, final RoutingDefineContext arg) {
    if (n.getName().equals("define") && n.getScope().equals(ASTHelper.createNameExpr("Routes"))) {
        arg.setInRoutingDefine(true);
        super.visit(n, arg);
        arg.setInRoutingDefine(false);
    } else {
        super.visit(n, arg);
    }
}
 
Example 18
Source Project: Refactoring-Bot   Source File: RemoveMethodParameterTest.java    License: MIT License 5 votes vote down vote up
/**
 * Asserts that all method calls in the body of methodWithTargetMethodCalls have
 * the same argument size as the refactoredMethod has arguments
 * 
 * @param methodWithTargetMethodCalls
 * @param refactoredMethod
 */
private void assertAllMethodCallsArgumentSizeEqualToRefactoredMethodParameterCount(
		MethodDeclaration methodWithTargetMethodCalls, MethodDeclaration refactoredMethod) {
	for (MethodCallExpr methodCall : methodWithTargetMethodCalls.getBody().get().findAll(MethodCallExpr.class)) {
		if (methodCall.getNameAsString().equals(refactoredMethod.getNameAsString())) {
			NodeList<Expression> callerMethodArguments = methodCall.getArguments();
			NodeList<Parameter> refactoredMethodParameters = refactoredMethod.getParameters();

			assertThat(callerMethodArguments).hasSameSizeAs(refactoredMethodParameters);
		}
	}
}
 
Example 19
Source Project: kogito-runtimes   Source File: ProcessInstanceGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private ConstructorDeclaration constructorDecl() {
    return new ConstructorDeclaration()
            .setName(targetTypeName)
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter(ProcessGenerator.processType(canonicalName), PROCESS)
            .addParameter(model.getModelClassSimpleName(), VALUE)
            .addParameter(ProcessRuntime.class.getCanonicalName(), PROCESS_RUNTIME)
            .setBody(new BlockStmt().addStatement(new MethodCallExpr(
                    "super",
                    new NameExpr(PROCESS),
                    new NameExpr(VALUE),
                    new NameExpr(PROCESS_RUNTIME))));
}
 
Example 20
Source Project: kogito-runtimes   Source File: MessageProducerGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public String generate() {
    CompilationUnit clazz = parse(
            this.getClass().getResourceAsStream("/class-templates/MessageProducerTemplate.java"));
    clazz.setPackageDeclaration(process.getPackageName());

    ClassOrInterfaceDeclaration template = clazz.findFirst(ClassOrInterfaceDeclaration.class).get();
    template.setName(resourceClazzName);        
    
    template.findAll(ClassOrInterfaceType.class).forEach(cls -> interpolateTypes(cls, trigger.getDataType()));
    template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("produce")).forEach(md -> md.getParameters().stream().filter(p -> p.getNameAsString().equals(EVENT_DATA_VAR)).forEach(p -> p.setType(trigger.getDataType())));
    template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("configure")).forEach(md -> md.addAnnotation("javax.annotation.PostConstruct"));
    template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("marshall")).forEach(md -> {
        md.getParameters().stream().filter(p -> p.getNameAsString().equals(EVENT_DATA_VAR)).forEach(p -> p.setType(trigger.getDataType()));
        md.findAll(ClassOrInterfaceType.class).forEach(t -> t.setName(t.getNameAsString().replace("$DataEventType$", messageDataEventClassName)));
    });
    
    if (useInjection()) {
        annotator.withApplicationComponent(template);
        
        FieldDeclaration emitterField = template.findFirst(FieldDeclaration.class).filter(fd -> fd.getVariable(0).getNameAsString().equals("emitter")).get();
        annotator.withInjection(emitterField);
        annotator.withOutgoingMessage(emitterField, trigger.getName());
        emitterField.getVariable(0).setType(annotator.emitterType("String"));
        
        MethodDeclaration produceMethod = template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("produce")).findFirst().orElseThrow(() -> new IllegalStateException("Cannot find produce methos in MessageProducerTemplate"));
        BlockStmt body = new BlockStmt();
        MethodCallExpr sendMethodCall = new MethodCallExpr(new NameExpr("emitter"), "send");
        annotator.withMessageProducer(sendMethodCall, trigger.getName(), new MethodCallExpr(new ThisExpr(), "marshall").addArgument(new NameExpr("pi")).addArgument(new NameExpr(EVENT_DATA_VAR)));
        body.addStatement(sendMethodCall);
        produceMethod.setBody(body);

        template.findAll(FieldDeclaration.class,
                fd -> fd.getVariable(0).getNameAsString().equals("useCloudEvents")).forEach(fd -> annotator.withConfigInjection(fd, "kogito.messaging.as-cloudevents"));
        
    } 
    template.getMembers().sort(new BodyDeclarationComparator());
    return clazz.toString();
}
 
Example 21
Source Project: kogito-runtimes   Source File: PersistenceGenerator.java    License: Apache License 2.0 5 votes vote down vote up
protected void fileSystemBasedPersistence(List<GeneratedFile> generatedFiles) {
	ClassOrInterfaceDeclaration persistenceProviderClazz = new ClassOrInterfaceDeclaration()
            .setName("KogitoProcessInstancesFactoryImpl")
            .setModifiers(Modifier.Keyword.PUBLIC)
            .addExtendedType("org.kie.kogito.persistence.KogitoProcessInstancesFactory");
    
    CompilationUnit compilationUnit = new CompilationUnit("org.kie.kogito.persistence");            
    compilationUnit.getTypes().add(persistenceProviderClazz);                 
    
    if (useInjection()) {
        annotator.withApplicationComponent(persistenceProviderClazz);            
        
        FieldDeclaration pathField = new FieldDeclaration().addVariable(new VariableDeclarator()
                                                                                 .setType(new ClassOrInterfaceType(null, new SimpleName(Optional.class.getCanonicalName()), NodeList.nodeList(new ClassOrInterfaceType(null, String.class.getCanonicalName()))))
                                                                                 .setName(PATH_NAME));
        annotator.withConfigInjection(pathField, KOGITO_PERSISTENCE_FS_PATH_PROP);
        // allow to inject path for the file system storage
        BlockStmt pathMethodBody = new BlockStmt();                
        pathMethodBody.addStatement(new ReturnStmt(new MethodCallExpr(new NameExpr(PATH_NAME), "orElse").addArgument(new StringLiteralExpr("/tmp"))));
        
        MethodDeclaration pathMethod = new MethodDeclaration()
                .addModifier(Keyword.PUBLIC)
                .setName(PATH_NAME)
                .setType(String.class)                                
                .setBody(pathMethodBody);
        
        persistenceProviderClazz.addMember(pathField);
        persistenceProviderClazz.addMember(pathMethod);
    }
    
    String packageName = compilationUnit.getPackageDeclaration().map(pd -> pd.getName().toString()).orElse("");
    String clazzName = packageName + "." + persistenceProviderClazz.findFirst(ClassOrInterfaceDeclaration.class).map(c -> c.getName().toString()).get();
 
    generatedFiles.add(new GeneratedFile(GeneratedFile.Type.CLASS,
                                         clazzName.replace('.', '/') + ".java",
                                         compilationUnit.toString().getBytes(StandardCharsets.UTF_8))); 
    
    persistenceProviderClazz.getMembers().sort(new BodyDeclarationComparator());
}
 
Example 22
@Override
public void visit(MethodCallExpr n, Void arg) {
    super.visit(n, arg);
    if (currentMethod != null) {
        if (!calledMethods.contains(new CalledMethod(n.getArguments().size(), n.getNameAsString()))) {
            calledMethods.add(new CalledMethod(n.getArguments().size(), n.getNameAsString()));
        }
    }
}
 
Example 23
public void addProcessToApplication(ProcessGenerator r) {
    ObjectCreationExpr newProcess = new ObjectCreationExpr()
            .setType(r.targetCanonicalName())
            .addArgument("application");
    IfStmt byProcessId = new IfStmt(new MethodCallExpr(new StringLiteralExpr(r.processId()), "equals", NodeList.nodeList(new NameExpr("processId"))),
                                    new ReturnStmt(new MethodCallExpr(
                                            newProcess,
                                            "configure")),
                                    null);

    byProcessIdMethodDeclaration
            .getBody()
            .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
            .addStatement(byProcessId);
}
 
Example 24
@Override
public ClassOrInterfaceDeclaration classDeclaration() {
    byProcessIdMethodDeclaration
            .getBody()
            .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
            .addStatement(new ReturnStmt(new NullLiteralExpr()));

    NodeList<Expression> processIds = NodeList.nodeList(processes.stream().map(p -> new StringLiteralExpr(p.processId())).collect(Collectors.toList()));
    processesMethodDeclaration
            .getBody()
            .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
            .addStatement(new ReturnStmt(new MethodCallExpr(new NameExpr(Arrays.class.getCanonicalName()), "asList", processIds)));

    FieldDeclaration applicationFieldDeclaration = new FieldDeclaration();
    applicationFieldDeclaration
            .addVariable( new VariableDeclarator( new ClassOrInterfaceType(null, "Application"), "application") )
            .setModifiers( Modifier.Keyword.PRIVATE, Modifier.Keyword.FINAL );
    applicationDeclarations.add( applicationFieldDeclaration );

    ConstructorDeclaration constructorDeclaration = new ConstructorDeclaration("Processes")
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter( "Application", "application" )
            .setBody( new BlockStmt().addStatement( "this.application = application;" ) );
    applicationDeclarations.add( constructorDeclaration );

    ClassOrInterfaceDeclaration cls = super.classDeclaration().setMembers(applicationDeclarations);
    cls.getMembers().sort(new BodyDeclarationComparator());
    
    return cls;
}
 
Example 25
Source Project: Refactoring-Bot   Source File: RenameMethodTest.java    License: MIT License 5 votes vote down vote up
/**
 * @param methodWithMethodCalls
 * @param calledMethodName
 * @return number of method calls inside the given method to a method with the
 *         given name
 */
private int countNumberOfMethodCalls(MethodDeclaration methodWithMethodCalls, String calledMethodName) {
	int numberOfMethodsWithNewMethodName = 0;
	for (MethodCallExpr methodCall : methodWithMethodCalls.getBody().get().findAll(MethodCallExpr.class)) {
		if (methodCall.getNameAsString().equals(calledMethodName)) {
			numberOfMethodsWithNewMethodName++;
		}
	}
	return numberOfMethodsWithNewMethodName;
}
 
Example 26
Source Project: kogito-runtimes   Source File: ProcessConfigGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private MethodDeclaration generateExtractEventListenerConfigMethod() {
    BlockStmt body = new BlockStmt().addStatement(new ReturnStmt(
            new MethodCallExpr(new ThisExpr(), METHOD_MERGE_PROCESS_EVENT_LISTENER_CONFIG, NodeList.nodeList(
                    annotator.getMultiInstance(VAR_PROCESS_EVENT_LISTENER_CONFIGS),
                    annotator.getMultiInstance(VAR_PROCESS_EVENT_LISTENERS)
            ))
    ));

    return method(Modifier.Keyword.PRIVATE, ProcessEventListenerConfig.class, METHOD_EXTRACT_PROCESS_EVENT_LISTENER_CONFIG, body);
}
 
Example 27
Source Project: kogito-runtimes   Source File: QueryEndpointGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void generateQueryMethods(CompilationUnit cu, ClassOrInterfaceDeclaration clazz, String returnType) {
    boolean hasDI = annotator != null;
    MethodDeclaration queryMethod = clazz.getMethodsByName("executeQuery").get(0);
    queryMethod.getParameter(0).setType(ruleUnit.getCanonicalName() + (hasDI ? "" : "DTO"));
    setGeneric(queryMethod.getType(), returnType);

    Statement statement = queryMethod
            .getBody()
            .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
            .getStatement(0);
    statement.findAll(VariableDeclarator.class).forEach(decl -> setUnitGeneric(decl.getType()));
    statement.findAll( MethodCallExpr.class ).forEach( m -> m.addArgument( hasDI ? "unitDTO" : "unitDTO.get()" ) );

    Statement returnStatement = queryMethod
            .getBody()
            .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
            .getStatement(1);
    returnStatement.findAll(VariableDeclarator.class).forEach(decl -> setGeneric(decl.getType(), returnType));

    MethodDeclaration queryMethodSingle = clazz.getMethodsByName("executeQueryFirst").get(0);
    queryMethodSingle.getParameter(0).setType(ruleUnit.getCanonicalName() + (hasDI ? "" : "DTO"));
    queryMethodSingle.setType(toNonPrimitiveType(returnType));

    Statement statementSingle = queryMethodSingle
            .getBody()
            .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
            .getStatement(0);
    statementSingle.findAll(VariableDeclarator.class).forEach(decl -> setGeneric(decl.getType(), returnType));

    Statement returnMethodSingle = queryMethodSingle
            .getBody()
            .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
            .getStatement(1);
    returnMethodSingle.findAll(VariableDeclarator.class).forEach(decl -> decl.setType(toNonPrimitiveType(returnType)));

    if (useMonitoring) {
        addMonitoringToResource(cu, new MethodDeclaration[]{queryMethod, queryMethodSingle}, endpointName);
    }
}
 
Example 28
Source Project: kogito-runtimes   Source File: QueryEndpointGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void generateResultClass(ClassOrInterfaceDeclaration clazz, MethodDeclaration toResultMethod) {
    ClassOrInterfaceDeclaration resultClass = new ClassOrInterfaceDeclaration(new NodeList<Modifier>(Modifier.publicModifier(), Modifier.staticModifier()), false, "Result");
    clazz.addMember(resultClass);

    ConstructorDeclaration constructor = resultClass.addConstructor(Modifier.Keyword.PUBLIC);
    BlockStmt constructorBody = constructor.createBody();

    ObjectCreationExpr resultCreation = new ObjectCreationExpr();
    resultCreation.setType("Result");
    BlockStmt resultMethodBody = toResultMethod.createBody();
    resultMethodBody.addStatement(new ReturnStmt(resultCreation));

    query.getBindings().forEach((name, type) -> {
        resultClass.addField(type, name, Modifier.Keyword.PRIVATE, Modifier.Keyword.FINAL);

        MethodDeclaration getterMethod = resultClass.addMethod("get" + ucFirst(name), Modifier.Keyword.PUBLIC);
        getterMethod.setType(type);
        BlockStmt body = getterMethod.createBody();
        body.addStatement(new ReturnStmt(new NameExpr(name)));

        constructor.addAndGetParameter(type, name);
        constructorBody.addStatement(new AssignExpr(new NameExpr("this." + name), new NameExpr(name), AssignExpr.Operator.ASSIGN));

        MethodCallExpr callExpr = new MethodCallExpr(new NameExpr("tuple"), "get");
        callExpr.addArgument(new StringLiteralExpr(name));
        resultCreation.addArgument(new CastExpr(classToReferenceType(type), callExpr));
    });
}
 
Example 29
@Override
public void visit(MethodCallExpr n, Void arg) {
    super.visit(n, arg);
    if (currentMethod != null) {
        // if the name of a method being called is an assertion and has 3 parameters
        if (n.getNameAsString().startsWith(("assertArrayEquals")) ||
                n.getNameAsString().startsWith(("assertEquals")) ||
                n.getNameAsString().startsWith(("assertNotSame")) ||
                n.getNameAsString().startsWith(("assertSame")) ||
                n.getNameAsString().startsWith(("assertThat"))) {
            assertCount++;
            // assert methods that do not contain a message
            if (n.getArguments().size() < 3) {
                assertNoMessageCount++;
            }
        }
        // if the name of a method being called is an assertion and has 2 parameters
        else if (n.getNameAsString().equals("assertFalse") ||
                n.getNameAsString().equals("assertNotNull") ||
                n.getNameAsString().equals("assertNull") ||
                n.getNameAsString().equals("assertTrue")) {
            assertCount++;
            // assert methods that do not contain a message
            if (n.getArguments().size() < 2) {
                assertNoMessageCount++;
            }
        }

        // if the name of a method being called is 'fail'
        else if (n.getNameAsString().equals("fail")) {
            assertCount++;
            // fail method does not contain a message
            if (n.getArguments().size() < 1) {
                assertNoMessageCount++;
            }
        }

    }
}
 
Example 30
Source Project: kogito-runtimes   Source File: RuleUnitGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public void classDeclaration(ClassOrInterfaceDeclaration cls) {
    cls.setName(targetTypeName)
            .setModifiers(Modifier.Keyword.PUBLIC)
            .getExtendedTypes().get(0).setTypeArguments(nodeList(new ClassOrInterfaceType(null, typeName)));

    if (annotator != null) {
        annotator.withSingletonComponent(cls);
        cls.findFirst(ConstructorDeclaration.class, c -> !c.getParameters().isEmpty()) // non-empty constructor
                .ifPresent(annotator::withInjection);
    }

    String ruleUnitInstanceFQCN = RuleUnitInstanceGenerator.qualifiedName(packageName, typeName);
    cls.findAll(ConstructorDeclaration.class).forEach(this::setClassName);
    cls.findAll(ObjectCreationExpr.class, o -> o.getType().getNameAsString().equals("$InstanceName$"))
            .forEach(o -> o.setType(ruleUnitInstanceFQCN));
    cls.findAll(ObjectCreationExpr.class, o -> o.getType().getNameAsString().equals("$Application$"))
            .forEach(o -> o.setType(applicationPackageName + ".Application"));
    cls.findAll(ObjectCreationExpr.class, o -> o.getType().getNameAsString().equals("$RuleModelName$"))
            .forEach(o -> o.setType(packageName + "." + generatedSourceFile + "_" + typeName));
    cls.findAll(MethodDeclaration.class, m -> m.getType().asString().equals("$InstanceName$"))
            .stream()
            .map(m -> m.setType(ruleUnitInstanceFQCN))
            .flatMap(m -> m.getParameters().stream())
            .filter(p -> p.getType().asString().equals("$ModelName$"))
            .forEach(o -> o.setType(typeName));
    cls.findAll( MethodCallExpr.class).stream()
            .flatMap( mCall -> mCall.getArguments().stream() )
            .filter( e -> e.isNameExpr() && e.toNameExpr().get().getNameAsString().equals( "$ModelClass$" ) )
            .forEach( e -> e.toNameExpr().get().setName( typeName + ".class" ) );
    cls.findAll(TypeParameter.class)
            .forEach(tp -> tp.setName(typeName));
}