Search in sources :

Example 46 with VariableDeclarator

use of com.github.javaparser.ast.body.VariableDeclarator in project drools by kiegroup.

the class KiePMMLIntervalFactory method getIntervalVariableDeclaration.

static BlockStmt getIntervalVariableDeclaration(final String variableName, final Interval interval) {
    final MethodDeclaration methodDeclaration = INTERVAL_TEMPLATE.getMethodsByName(GETKIEPMMLINTERVAL).get(0).clone();
    final BlockStmt toReturn = methodDeclaration.getBody().orElseThrow(() -> new KiePMMLException(String.format(MISSING_BODY_TEMPLATE, methodDeclaration)));
    final VariableDeclarator variableDeclarator = getVariableDeclarator(toReturn, INTERVAL).orElseThrow(() -> new KiePMMLException(String.format(MISSING_VARIABLE_IN_BODY, INTERVAL, toReturn)));
    variableDeclarator.setName(variableName);
    final ObjectCreationExpr objectCreationExpr = variableDeclarator.getInitializer().orElseThrow(() -> new KiePMMLException(String.format(MISSING_VARIABLE_INITIALIZER_TEMPLATE, INTERVAL, toReturn))).asObjectCreationExpr();
    final Expression leftMarginExpr = getExpressionForObject(interval.getLeftMargin());
    final Expression rightMarginExpr = getExpressionForObject(interval.getRightMargin());
    final CLOSURE closure = CLOSURE.byName(interval.getClosure().value());
    final NameExpr closureExpr = new NameExpr(CLOSURE.class.getName() + "." + closure.name());
    objectCreationExpr.getArguments().set(0, leftMarginExpr);
    objectCreationExpr.getArguments().set(1, rightMarginExpr);
    objectCreationExpr.getArguments().set(2, closureExpr);
    return toReturn;
}
Also used : ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) Expression(com.github.javaparser.ast.expr.Expression) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) NameExpr(com.github.javaparser.ast.expr.NameExpr) KiePMMLException(org.kie.pmml.api.exceptions.KiePMMLException) CLOSURE(org.kie.pmml.api.enums.CLOSURE) CommonCodegenUtils.getVariableDeclarator(org.kie.pmml.compiler.commons.utils.CommonCodegenUtils.getVariableDeclarator) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator)

Example 47 with VariableDeclarator

use of com.github.javaparser.ast.body.VariableDeclarator in project drools by kiegroup.

the class KiePMMLMapValuesFactory method getMapValuesVariableDeclaration.

static BlockStmt getMapValuesVariableDeclaration(final String variableName, final MapValues mapValues) {
    if (mapValues.getInlineTable() == null && mapValues.getTableLocator() != null) {
        throw new UnsupportedOperationException("TableLocator not supported, yet");
    }
    final MethodDeclaration methodDeclaration = MAPVALUES_TEMPLATE.getMethodsByName(GETKIEPMMLMAPVALUES).get(0).clone();
    final BlockStmt mapValuesBody = methodDeclaration.getBody().orElseThrow(() -> new KiePMMLException(String.format(MISSING_BODY_TEMPLATE, methodDeclaration)));
    final VariableDeclarator variableDeclarator = getVariableDeclarator(mapValuesBody, MAPVALUES).orElseThrow(() -> new KiePMMLException(String.format(MISSING_VARIABLE_IN_BODY, MAPVALUES, mapValuesBody)));
    variableDeclarator.setName(variableName);
    final BlockStmt toReturn = new BlockStmt();
    int counter = 0;
    final NodeList<Expression> arguments = new NodeList<>();
    if (mapValues.hasFieldColumnPairs()) {
        for (FieldColumnPair fieldColumnPair : mapValues.getFieldColumnPairs()) {
            String nestedVariableName = String.format(VARIABLE_NAME_TEMPLATE, variableName, counter);
            arguments.add(new NameExpr(nestedVariableName));
            BlockStmt toAdd = getFieldColumnPairVariableDeclaration(nestedVariableName, fieldColumnPair);
            toAdd.getStatements().forEach(toReturn::addStatement);
            counter++;
        }
    }
    String inlineTableVariableName = String.format("%s_InlineTable", variableName);
    BlockStmt toAdd = getInlineTableVariableDeclaration(inlineTableVariableName, mapValues.getInlineTable());
    toAdd.getStatements().forEach(toReturn::addStatement);
    final MethodCallExpr initializer = variableDeclarator.getInitializer().orElseThrow(() -> new KiePMMLException(String.format(MISSING_VARIABLE_INITIALIZER_TEMPLATE, MAPVALUES, toReturn))).asMethodCallExpr();
    final MethodCallExpr builder = getChainedMethodCallExprFrom("builder", initializer);
    final StringLiteralExpr nameExpr = new StringLiteralExpr(variableName);
    final StringLiteralExpr outputColumnExpr = new StringLiteralExpr(mapValues.getOutputColumn());
    builder.setArgument(0, nameExpr);
    builder.setArgument(2, outputColumnExpr);
    final Expression dataTypeExpression = getExpressionForDataType(mapValues.getDataType());
    getChainedMethodCallExprFrom("withDefaultValue", initializer).setArgument(0, getExpressionForObject(mapValues.getDefaultValue()));
    getChainedMethodCallExprFrom("withMapMissingTo", initializer).setArgument(0, getExpressionForObject(mapValues.getMapMissingTo()));
    getChainedMethodCallExprFrom("withDataType", initializer).setArgument(0, dataTypeExpression);
    getChainedMethodCallExprFrom("withKiePMMLInlineTable", initializer).setArgument(0, new NameExpr(inlineTableVariableName));
    getChainedMethodCallExprFrom("asList", initializer).setArguments(arguments);
    mapValuesBody.getStatements().forEach(toReturn::addStatement);
    return toReturn;
}
Also used : MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) NodeList(com.github.javaparser.ast.NodeList) NameExpr(com.github.javaparser.ast.expr.NameExpr) StringLiteralExpr(com.github.javaparser.ast.expr.StringLiteralExpr) FieldColumnPair(org.dmg.pmml.FieldColumnPair) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) CommonCodegenUtils.getVariableDeclarator(org.kie.pmml.compiler.commons.utils.CommonCodegenUtils.getVariableDeclarator) Expression(com.github.javaparser.ast.expr.Expression) KiePMMLException(org.kie.pmml.api.exceptions.KiePMMLException) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr)

Example 48 with VariableDeclarator

use of com.github.javaparser.ast.body.VariableDeclarator in project drools by kiegroup.

the class KiePMMLNodeFactoryTest method populateEvaluateNodeWithNodeFunctions.

@Test
public void populateEvaluateNodeWithNodeFunctions() {
    final BlockStmt toPopulate = new BlockStmt();
    final VariableDeclarator variableDeclarator = new VariableDeclarator();
    variableDeclarator.setType("Object");
    variableDeclarator.setName(NODE_FUNCTIONS);
    toPopulate.addStatement(new VariableDeclarationExpr(variableDeclarator));
    assertFalse(variableDeclarator.getInitializer().isPresent());
    // empty list
    List<String> nestedNodesFullClasses = Collections.emptyList();
    KiePMMLNodeFactory.populateEvaluateNodeWithNodeFunctions(toPopulate, nestedNodesFullClasses);
    commonVerifyEvaluateNodeWithNodeFunctions(variableDeclarator, nestedNodesFullClasses);
    // populated list
    nestedNodesFullClasses = IntStream.range(0, 2).mapToObj(i -> "full.node.NodeClassName" + i).collect(Collectors.toList());
    KiePMMLNodeFactory.populateEvaluateNodeWithNodeFunctions(toPopulate, nestedNodesFullClasses);
    commonVerifyEvaluateNodeWithNodeFunctions(variableDeclarator, nestedNodesFullClasses);
}
Also used : VariableDeclarationExpr(com.github.javaparser.ast.expr.VariableDeclarationExpr) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) Test(org.junit.Test)

Example 49 with VariableDeclarator

use of com.github.javaparser.ast.body.VariableDeclarator in project drools by kiegroup.

the class KiePMMLNodeFactoryTest method commonVerifyEvaluateNodeWithScoreDistributions.

private void commonVerifyEvaluateNodeWithScoreDistributions(final VariableDeclarator variableDeclarator, final List<ScoreDistribution> scoreDistributions) {
    assertTrue(variableDeclarator.getInitializer().isPresent());
    Expression expression = variableDeclarator.getInitializer().get();
    assertTrue(expression instanceof MethodCallExpr);
    MethodCallExpr methodCallExpr = (MethodCallExpr) expression;
    assertEquals("Arrays", methodCallExpr.getScope().get().toString());
    assertEquals("asList", methodCallExpr.getName().toString());
    NodeList<Expression> arguments = methodCallExpr.getArguments();
    assertEquals(scoreDistributions.size(), arguments.size());
    arguments.forEach(argument -> assertTrue(argument instanceof ObjectCreationExpr));
    List<ObjectCreationExpr> objectCreationExprs = arguments.stream().map(ObjectCreationExpr.class::cast).collect(Collectors.toList());
    scoreDistributions.forEach(scoreDistribution -> {
        Optional<ObjectCreationExpr> retrieved = objectCreationExprs.stream().filter(objectCreationExpr -> scoreDistribution.getValue().equals(objectCreationExpr.getArgument(2).asStringLiteralExpr().asString())).findFirst();
        assertTrue(retrieved.isPresent());
        Expression recordCountExpected = getExpressionForObject(scoreDistribution.getRecordCount().intValue());
        Expression confidenceExpected = getExpressionForObject(scoreDistribution.getConfidence().doubleValue());
        Expression probabilityExpected = scoreDistribution.getProbability() != null ? getExpressionForObject(scoreDistribution.getProbability().doubleValue()) : new NullLiteralExpr();
        retrieved.ifPresent(objectCreationExpr -> {
            assertEquals(recordCountExpected, objectCreationExpr.getArgument(3));
            assertEquals(confidenceExpected, objectCreationExpr.getArgument(4));
            assertEquals(probabilityExpected, objectCreationExpr.getArgument(5));
        });
    });
}
Also used : ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) StaticJavaParser.parseClassOrInterfaceType(com.github.javaparser.StaticJavaParser.parseClassOrInterfaceType) Arrays(java.util.Arrays) Random(java.util.Random) NullLiteralExpr(com.github.javaparser.ast.expr.NullLiteralExpr) Node(org.dmg.pmml.tree.Node) PMMLModelTestUtils.getRandomPMMLScoreDistributions(org.kie.pmml.compiler.api.testutils.PMMLModelTestUtils.getRandomPMMLScoreDistributions) ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) Map(java.util.Map) Expression(com.github.javaparser.ast.expr.Expression) CompilationUnit(com.github.javaparser.ast.CompilationUnit) NodeList(com.github.javaparser.ast.NodeList) PMML(org.dmg.pmml.PMML) CommonCodegenUtils(org.kie.pmml.compiler.commons.utils.CommonCodegenUtils) EVALUATE_NODE(org.kie.pmml.models.tree.compiler.factories.KiePMMLNodeFactory.EVALUATE_NODE) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr) TreeModel(org.dmg.pmml.tree.TreeModel) MISSING_VALUE_PENALTY(org.kie.pmml.models.tree.compiler.factories.KiePMMLNodeFactory.MISSING_VALUE_PENALTY) Collectors(java.util.stream.Collectors) FileUtils.getFileContent(org.kie.test.util.filesystem.FileUtils.getFileContent) VariableDeclarationExpr(com.github.javaparser.ast.expr.VariableDeclarationExpr) List(java.util.List) Assert.assertFalse(org.junit.Assert.assertFalse) CommonCodegenUtils.getExpressionForObject(org.kie.pmml.compiler.commons.utils.CommonCodegenUtils.getExpressionForObject) Optional(java.util.Optional) PACKAGE_CLASS_TEMPLATE(org.kie.pmml.commons.Constants.PACKAGE_CLASS_TEMPLATE) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) TypeExpr(com.github.javaparser.ast.expr.TypeExpr) AS_LIST(org.kie.pmml.models.tree.compiler.factories.KiePMMLNodeFactory.AS_LIST) NODE_FUNCTIONS(org.kie.pmml.models.tree.compiler.factories.KiePMMLNodeFactory.NODE_FUNCTIONS) IntStream(java.util.stream.IntStream) BeforeClass(org.junit.BeforeClass) SCORE(org.kie.pmml.models.tree.compiler.factories.KiePMMLNodeFactory.SCORE) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) DerivedField(org.dmg.pmml.DerivedField) ModelUtils.getDerivedFields(org.kie.pmml.compiler.api.utils.ModelUtils.getDerivedFields) DoubleLiteralExpr(com.github.javaparser.ast.expr.DoubleLiteralExpr) ScoreDistribution(org.dmg.pmml.ScoreDistribution) KiePMMLTreeModelUtils.createNodeClassName(org.kie.pmml.models.tree.compiler.utils.KiePMMLTreeModelUtils.createNodeClassName) JavaParserUtils.getFromSource(org.kie.pmml.compiler.commons.utils.JavaParserUtils.getFromSource) KiePMMLNode(org.kie.pmml.models.tree.model.KiePMMLNode) JavaParserUtils(org.kie.pmml.compiler.commons.utils.JavaParserUtils) PACKAGE_NAME(org.kie.pmml.commons.Constants.PACKAGE_NAME) Assert.assertNotNull(org.junit.Assert.assertNotNull) CommonTestingUtils.getFieldsFromDataDictionaryAndDerivedFields(org.kie.pmml.compiler.api.CommonTestingUtils.getFieldsFromDataDictionaryAndDerivedFields) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) DataDictionary(org.dmg.pmml.DataDictionary) Test(org.junit.Test) NameExpr(com.github.javaparser.ast.expr.NameExpr) Statement(com.github.javaparser.ast.stmt.Statement) MethodReferenceExpr(com.github.javaparser.ast.expr.MethodReferenceExpr) TestUtils(org.kie.pmml.compiler.api.testutils.TestUtils) SCORE_DISTRIBUTIONS(org.kie.pmml.models.tree.compiler.factories.KiePMMLNodeFactory.SCORE_DISTRIBUTIONS) HasClassLoaderMock(org.kie.pmml.compiler.commons.mocks.HasClassLoaderMock) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) EMPTY_LIST(org.kie.pmml.models.tree.compiler.factories.KiePMMLNodeFactory.EMPTY_LIST) NullLiteralExpr(com.github.javaparser.ast.expr.NullLiteralExpr) Expression(com.github.javaparser.ast.expr.Expression) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr)

Example 50 with VariableDeclarator

use of com.github.javaparser.ast.body.VariableDeclarator in project checker-framework by typetools.

the class AnnotationFileParser method putNewElement.

// Used only by getMembers().
/**
 * If {@code typeElt} contains an element for {@code member}, adds to {@code elementsToDecl} a
 * mapping from member's element to member. Does nothing if a mapping already exists.
 *
 * <p>Otherwise (if there is no element for {@code member}), adds to {@code fakeOverrideDecls}
 * zero or more mappings. Each mapping is from an element that {@code member} would override to
 * {@code member}.
 *
 * <p>This method does not read or write field {@link annotationFileAnnos}.
 *
 * @param elementsToDecl the mapping that is side-effected by this method
 * @param fakeOverrideDecls fake overrides, also side-effected by this method
 * @param typeElt the class in which {@code member} is declared
 * @param member the stub file declaration of a method
 * @param typeDeclName used only for debugging
 * @param astNode where to report errors
 */
private void putNewElement(Map<Element, BodyDeclaration<?>> elementsToDecl, Map<Element, List<BodyDeclaration<?>>> fakeOverrideDecls, TypeElement typeElt, BodyDeclaration<?> member, String typeDeclName, NodeWithRange<?> astNode) {
    if (member instanceof MethodDeclaration) {
        MethodDeclaration method = (MethodDeclaration) member;
        Element elt = findElement(typeElt, method, /*noWarn=*/
        true);
        if (elt != null) {
            putIfAbsent(elementsToDecl, elt, method);
        } else {
            ExecutableElement overriddenMethod = fakeOverriddenMethod(typeElt, method);
            if (overriddenMethod == null) {
                // Didn't find the element and it isn't a fake override.  Issue a warning.
                findElement(typeElt, method, /*noWarn=*/
                false);
            } else {
                List<BodyDeclaration<?>> l = fakeOverrideDecls.computeIfAbsent(overriddenMethod, __ -> new ArrayList<>());
                l.add(member);
            }
        }
    } else if (member instanceof ConstructorDeclaration) {
        Element elt = findElement(typeElt, (ConstructorDeclaration) member);
        if (elt != null) {
            putIfAbsent(elementsToDecl, elt, member);
        }
    } else if (member instanceof FieldDeclaration) {
        FieldDeclaration fieldDecl = (FieldDeclaration) member;
        for (VariableDeclarator var : fieldDecl.getVariables()) {
            Element varelt = findElement(typeElt, var);
            if (varelt != null) {
                putIfAbsent(elementsToDecl, varelt, fieldDecl);
            }
        }
    } else if (member instanceof EnumConstantDeclaration) {
        Element elt = findElement(typeElt, (EnumConstantDeclaration) member, astNode);
        if (elt != null) {
            putIfAbsent(elementsToDecl, elt, member);
        }
    } else if (member instanceof ClassOrInterfaceDeclaration) {
        Element elt = findElement(typeElt, (ClassOrInterfaceDeclaration) member);
        if (elt != null) {
            putIfAbsent(elementsToDecl, elt, member);
        }
    } else if (member instanceof EnumDeclaration) {
        Element elt = findElement(typeElt, (EnumDeclaration) member);
        if (elt != null) {
            putIfAbsent(elementsToDecl, elt, member);
        }
    } else {
        stubDebug(String.format("Ignoring element of type %s in %s", member.getClass(), typeDeclName));
    }
}
Also used : EnumConstantDeclaration(com.github.javaparser.ast.body.EnumConstantDeclaration) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) PackageElement(javax.lang.model.element.PackageElement) VariableElement(javax.lang.model.element.VariableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) BodyDeclaration(com.github.javaparser.ast.body.BodyDeclaration) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) EnumDeclaration(com.github.javaparser.ast.body.EnumDeclaration)

Aggregations

VariableDeclarator (com.github.javaparser.ast.body.VariableDeclarator)110 BlockStmt (com.github.javaparser.ast.stmt.BlockStmt)50 MethodDeclaration (com.github.javaparser.ast.body.MethodDeclaration)44 Expression (com.github.javaparser.ast.expr.Expression)43 KiePMMLException (org.kie.pmml.api.exceptions.KiePMMLException)41 CommonCodegenUtils.getVariableDeclarator (org.kie.pmml.compiler.commons.utils.CommonCodegenUtils.getVariableDeclarator)39 NameExpr (com.github.javaparser.ast.expr.NameExpr)33 StringLiteralExpr (com.github.javaparser.ast.expr.StringLiteralExpr)32 MethodCallExpr (com.github.javaparser.ast.expr.MethodCallExpr)30 Test (org.junit.Test)25 ObjectCreationExpr (com.github.javaparser.ast.expr.ObjectCreationExpr)24 ClassOrInterfaceDeclaration (com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)18 VariableDeclarationExpr (com.github.javaparser.ast.expr.VariableDeclarationExpr)17 CompilationUnit (com.github.javaparser.ast.CompilationUnit)16 NodeList (com.github.javaparser.ast.NodeList)16 ResolvedType (com.github.javaparser.resolution.types.ResolvedType)14 FieldDeclaration (com.github.javaparser.ast.body.FieldDeclaration)13 ReflectionTypeSolver (com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver)13 NullLiteralExpr (com.github.javaparser.ast.expr.NullLiteralExpr)11 Parameter (com.github.javaparser.ast.body.Parameter)9