Search in sources :

Example 31 with ClassOrInterfaceDeclaration

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

the class CompilerBytecodeLoader method getSourceForUnaryTest.

public String getSourceForUnaryTest(String packageName, String className, String feelExpression, Expression theExpression, Set<FieldDeclaration> fieldDeclarations) {
    CompilationUnit cu = getCompilationUnit(CompiledFEELUnaryTests.class, "/TemplateCompiledFEELUnaryTests.java", packageName, className, feelExpression, theExpression, fieldDeclarations);
    ClassOrInterfaceDeclaration classSource = cu.getClassByName(className).orElseThrow(() -> new IllegalArgumentException("Cannot find class by name " + className));
    classSource.setStatic(true);
    return classSource.toString();
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)

Example 32 with ClassOrInterfaceDeclaration

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

the class CompilerBytecodeLoader method getCompilationUnit.

public <T> CompilationUnit getCompilationUnit(Class<T> clazz, String templateResourcePath, String cuPackage, String cuClass, String feelExpression, Expression theExpression, Set<FieldDeclaration> fieldDeclarations) {
    CompilationUnit cu = parse(CompilerBytecodeLoader.class.getResourceAsStream(templateResourcePath));
    cu.setPackageDeclaration(cuPackage);
    final String className = templateResourcePath.substring(1, templateResourcePath.length() - 5);
    ClassOrInterfaceDeclaration classSource = cu.getClassByName(className).orElseThrow(() -> new IllegalArgumentException("Cannot find class by name " + className));
    classSource.setName(cuClass);
    MethodDeclaration lookupMethod = cu.findFirst(MethodDeclaration.class).orElseThrow(() -> new RuntimeException("Something unexpected changed in the template."));
    lookupMethod.setComment(new JavadocComment("   FEEL: " + feelExpression + "   "));
    ReturnStmt returnStmt = lookupMethod.findFirst(ReturnStmt.class).orElseThrow(() -> new RuntimeException("Something unexpected changed in the template."));
    Expression expr;
    if (clazz.equals(CompiledFEELUnaryTests.class)) {
        expr = new CastExpr(StaticJavaParser.parseType("java.util.List"), new EnclosedExpr(theExpression));
    } else {
        expr = theExpression;
    }
    returnStmt.setExpression(expr);
    List<ClassOrInterfaceDeclaration> classDecls = cu.findAll(ClassOrInterfaceDeclaration.class);
    if (classDecls.size() != 1) {
        throw new RuntimeException("Something unexpected changed in the template.");
    }
    ClassOrInterfaceDeclaration classDecl = classDecls.get(0);
    fieldDeclarations.stream().filter(fd -> !isUnaryTest(fd)).sorted(new SortFieldDeclarationStrategy()).forEach(classDecl::addMember);
    fieldDeclarations.stream().filter(fd -> fd.getVariable(0).getName().asString().startsWith("UT")).sorted(new SortFieldDeclarationStrategy()).forEach(classDecl::addMember);
    if (generateClassListener != null) {
        generateClassListener.generatedClass(cu);
    }
    LOG.debug("{}", cu);
    return cu;
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) JavadocComment(com.github.javaparser.ast.comments.JavadocComment) Expression(com.github.javaparser.ast.expr.Expression) CastExpr(com.github.javaparser.ast.expr.CastExpr) EnclosedExpr(com.github.javaparser.ast.expr.EnclosedExpr) ReturnStmt(com.github.javaparser.ast.stmt.ReturnStmt)

Example 33 with ClassOrInterfaceDeclaration

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

the class KiePMMLModelFactoryUtilsTest method populateGetCreatedKiePMMLTargetsMethod.

@Test
public void populateGetCreatedKiePMMLTargetsMethod() throws IOException {
    Random random = new Random();
    List<TargetField> kiePMMLTargets = IntStream.range(0, 3).mapToObj(i -> new TargetField(Collections.emptyList(), OP_TYPE.byName(getRandomOpType().value()), "Target-" + i, CAST_INTEGER.byName(getRandomCastInteger().value()), (double) random.nextInt(20), (double) random.nextInt(60) + 20, (double) random.nextInt(100) / 100, (double) random.nextInt(100) / 100)).collect(Collectors.toList());
    String opType0 = OP_TYPE.class.getCanonicalName() + "." + kiePMMLTargets.get(0).getOpType().toString();
    String castInteger0 = CAST_INTEGER.class.getCanonicalName() + "." + kiePMMLTargets.get(0).getCastInteger().toString();
    String opType1 = OP_TYPE.class.getCanonicalName() + "." + kiePMMLTargets.get(1).getOpType().toString();
    String castInteger1 = CAST_INTEGER.class.getCanonicalName() + "." + kiePMMLTargets.get(1).getCastInteger().toString();
    String opType2 = OP_TYPE.class.getCanonicalName() + "." + kiePMMLTargets.get(2).getOpType().toString();
    String castInteger2 = CAST_INTEGER.class.getCanonicalName() + "." + kiePMMLTargets.get(2).getCastInteger().toString();
    KiePMMLModelFactoryUtils.populateGetCreatedKiePMMLTargetsMethod(classOrInterfaceDeclaration, kiePMMLTargets);
    final MethodDeclaration retrieved = classOrInterfaceDeclaration.getMethodsByName(GET_CREATED_KIEPMMLTARGETS).get(0);
    String text = getFileContent(TEST_10_SOURCE);
    MethodDeclaration expected = JavaParserUtils.parseMethod(String.format(text, kiePMMLTargets.get(0).getName(), opType0, castInteger0, kiePMMLTargets.get(0).getMin(), kiePMMLTargets.get(0).getMax(), kiePMMLTargets.get(0).getRescaleConstant(), kiePMMLTargets.get(0).getRescaleFactor(), kiePMMLTargets.get(1).getName(), opType1, castInteger1, kiePMMLTargets.get(1).getMin(), kiePMMLTargets.get(1).getMax(), kiePMMLTargets.get(1).getRescaleConstant(), kiePMMLTargets.get(1).getRescaleFactor(), kiePMMLTargets.get(2).getName(), opType2, castInteger2, kiePMMLTargets.get(2).getMin(), kiePMMLTargets.get(2).getMax(), kiePMMLTargets.get(2).getRescaleConstant(), kiePMMLTargets.get(2).getRescaleFactor()));
    assertTrue(JavaParserUtils.equalsNode(expected, retrieved));
}
Also used : RESULT_FEATURE(org.kie.pmml.api.enums.RESULT_FEATURE) Arrays(java.util.Arrays) Spliterators(java.util.Spliterators) Random(java.util.Random) OP_TYPE(org.kie.pmml.api.enums.OP_TYPE) FIELD_USAGE_TYPE(org.kie.pmml.api.enums.FIELD_USAGE_TYPE) GET_CREATED_MININGFIELDS(org.kie.pmml.compiler.commons.codegenfactories.KiePMMLModelFactoryUtils.GET_CREATED_MININGFIELDS) KiePMMLUtil(org.kie.pmml.compiler.commons.utils.KiePMMLUtil) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) NullLiteralExpr(com.github.javaparser.ast.expr.NullLiteralExpr) GET_CREATED_LOCAL_TRANSFORMATIONS(org.kie.pmml.compiler.commons.codegenfactories.KiePMMLModelFactoryUtils.GET_CREATED_LOCAL_TRANSFORMATIONS) GET_CREATED_TRANSFORMATION_DICTIONARY(org.kie.pmml.compiler.commons.codegenfactories.KiePMMLModelFactoryUtils.GET_CREATED_TRANSFORMATION_DICTIONARY) ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) GET_CREATED_OUTPUTFIELDS(org.kie.pmml.compiler.commons.codegenfactories.KiePMMLModelFactoryUtils.GET_CREATED_OUTPUTFIELDS) GET_CREATED_KIEPMMLOUTPUTFIELDS(org.kie.pmml.compiler.commons.codegenfactories.KiePMMLModelFactoryUtils.GET_CREATED_KIEPMMLOUTPUTFIELDS) Expression(com.github.javaparser.ast.expr.Expression) Assert.fail(org.junit.Assert.fail) CompilationUnit(com.github.javaparser.ast.CompilationUnit) Interval(org.kie.pmml.api.models.Interval) ModelUtils(org.kie.pmml.compiler.api.utils.ModelUtils) NodeList(com.github.javaparser.ast.NodeList) PMML(org.dmg.pmml.PMML) CommonCodegenUtils(org.kie.pmml.compiler.commons.utils.CommonCodegenUtils) KiePMMLTargetValue(org.kie.pmml.commons.model.KiePMMLTargetValue) GET_CREATED_KIEPMMLTARGETS(org.kie.pmml.compiler.commons.codegenfactories.KiePMMLModelFactoryUtils.GET_CREATED_KIEPMMLTARGETS) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr) TreeModel(org.dmg.pmml.tree.TreeModel) Collectors(java.util.stream.Collectors) ExplicitConstructorInvocationStmt(com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt) FileUtils.getFileContent(org.kie.test.util.filesystem.FileUtils.getFileContent) List(java.util.List) Stream(java.util.stream.Stream) CommonCompilationDTO(org.kie.pmml.compiler.api.dto.CommonCompilationDTO) Optional(java.util.Optional) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) Spliterator(java.util.Spliterator) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) IntStream(java.util.stream.IntStream) ExpressionStmt(com.github.javaparser.ast.stmt.ExpressionStmt) BeforeClass(org.junit.BeforeClass) OutputField(org.kie.pmml.api.models.OutputField) JavaParserUtils.getFromFileName(org.kie.pmml.compiler.commons.utils.JavaParserUtils.getFromFileName) TargetField(org.kie.pmml.api.models.TargetField) MiningField(org.kie.pmml.api.models.MiningField) CAST_INTEGER(org.kie.pmml.api.enums.CAST_INTEGER) StreamSupport(java.util.stream.StreamSupport) GET_CREATED_KIEPMMLMININGFIELDS(org.kie.pmml.compiler.commons.codegenfactories.KiePMMLModelFactoryUtils.GET_CREATED_KIEPMMLMININGFIELDS) MISSING_VALUE_TREATMENT_METHOD(org.kie.pmml.api.enums.MISSING_VALUE_TREATMENT_METHOD) Before(org.junit.Before) INVALID_VALUE_TREATMENT_METHOD(org.kie.pmml.api.enums.INVALID_VALUE_TREATMENT_METHOD) CompilationDTO(org.kie.pmml.compiler.api.dto.CompilationDTO) JavaParserUtils(org.kie.pmml.compiler.commons.utils.JavaParserUtils) PACKAGE_NAME(org.kie.pmml.commons.Constants.PACKAGE_NAME) CommonCodegenUtils.getChainedMethodCallExprFrom(org.kie.pmml.compiler.commons.utils.CommonCodegenUtils.getChainedMethodCallExprFrom) Assert.assertNotNull(org.junit.Assert.assertNotNull) PMMLModelTestUtils.getRandomOpType(org.kie.pmml.compiler.api.testutils.PMMLModelTestUtils.getRandomOpType) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) Test(org.junit.Test) NameExpr(com.github.javaparser.ast.expr.NameExpr) PMMLModelTestUtils.getRandomDataField(org.kie.pmml.compiler.api.testutils.PMMLModelTestUtils.getRandomDataField) Statement(com.github.javaparser.ast.stmt.Statement) DATA_TYPE(org.kie.pmml.api.enums.DATA_TYPE) PMMLModelTestUtils.getRandomOutputField(org.kie.pmml.compiler.api.testutils.PMMLModelTestUtils.getRandomOutputField) PMMLModelTestUtils.getRandomTarget(org.kie.pmml.compiler.api.testutils.PMMLModelTestUtils.getRandomTarget) KiePMMLTarget(org.kie.pmml.commons.model.KiePMMLTarget) FileUtils.getFileInputStream(org.kie.test.util.filesystem.FileUtils.getFileInputStream) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) CodegenTestUtils.commonValidateCompilationWithImports(org.kie.pmml.compiler.commons.testutils.CodegenTestUtils.commonValidateCompilationWithImports) PMMLModelTestUtils.getRandomCastInteger(org.kie.pmml.compiler.api.testutils.PMMLModelTestUtils.getRandomCastInteger) PMMLModelTestUtils.getRandomMiningField(org.kie.pmml.compiler.api.testutils.PMMLModelTestUtils.getRandomMiningField) HasClassLoaderMock(org.kie.pmml.compiler.commons.mocks.HasClassLoaderMock) GET_MODEL(org.kie.pmml.commons.Constants.GET_MODEL) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) TargetValue(org.kie.pmml.api.models.TargetValue) Random(java.util.Random) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) TargetField(org.kie.pmml.api.models.TargetField) Test(org.junit.Test)

Example 34 with ClassOrInterfaceDeclaration

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

the class KiePMMLDroolsModelFactoryUtils method getKiePMMLModelCompilationUnit.

/**
 * @param droolsCompilationDTO
 * @param javaTemplate the name of the <b>file</b> to be used as template source
 * @param modelClassName the name of the class used in the provided template
 * @return
 */
public static <T extends Model> CompilationUnit getKiePMMLModelCompilationUnit(final DroolsCompilationDTO<T> droolsCompilationDTO, final String javaTemplate, final String modelClassName) {
    logger.trace("getKiePMMLModelCompilationUnit {} {} {}", droolsCompilationDTO.getFields(), droolsCompilationDTO.getModel(), droolsCompilationDTO.getPackageName());
    String className = droolsCompilationDTO.getSimpleClassName();
    CompilationUnit cloneCU = JavaParserUtils.getKiePMMLModelCompilationUnit(className, droolsCompilationDTO.getPackageName(), javaTemplate, modelClassName);
    ClassOrInterfaceDeclaration modelTemplate = cloneCU.getClassByName(className).orElseThrow(() -> new KiePMMLException(MAIN_CLASS_NOT_FOUND + ": " + className));
    MINING_FUNCTION miningFunction = droolsCompilationDTO.getMINING_FUNCTION();
    final ConstructorDeclaration constructorDeclaration = modelTemplate.getDefaultConstructor().orElseThrow(() -> new KiePMMLInternalException(String.format(MISSING_DEFAULT_CONSTRUCTOR, modelTemplate.getName())));
    String targetField = droolsCompilationDTO.getTargetFieldName();
    setConstructor(droolsCompilationDTO.getModel(), constructorDeclaration, modelTemplate.getName(), targetField, miningFunction, droolsCompilationDTO.getPackageName());
    addFieldTypeMapPopulation(constructorDeclaration.getBody(), droolsCompilationDTO.getFieldTypeMap());
    return cloneCU;
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) KiePMMLException(org.kie.pmml.api.exceptions.KiePMMLException) KiePMMLInternalException(org.kie.pmml.api.exceptions.KiePMMLInternalException) MINING_FUNCTION(org.kie.pmml.api.enums.MINING_FUNCTION)

Example 35 with ClassOrInterfaceDeclaration

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

the class KiePMMLTreeModelFactoryTest method setConstructor.

@Test
public void setConstructor() {
    final String targetField = "whatIdo";
    final ClassOrInterfaceDeclaration modelTemplate = classOrInterfaceDeclaration.clone();
    KnowledgeBuilderImpl knowledgeBuilder = new KnowledgeBuilderImpl();
    final CommonCompilationDTO<TreeModel> compilationDTO = CommonCompilationDTO.fromGeneratedPackageNameAndFields(PACKAGE_NAME, pmml, treeModel, new HasKnowledgeBuilderMock(knowledgeBuilder));
    final DroolsCompilationDTO<TreeModel> droolsCompilationDTO = DroolsCompilationDTO.fromCompilationDTO(compilationDTO, new HashMap<>());
    KiePMMLTreeModelFactory.setConstructor(droolsCompilationDTO, modelTemplate);
    Map<Integer, Expression> superInvocationExpressionsMap = new HashMap<>();
    superInvocationExpressionsMap.put(0, new NameExpr(String.format("\"%s\"", treeModel.getModelName())));
    superInvocationExpressionsMap.put(2, new NameExpr(String.format("\"%s\"", treeModel.getAlgorithmName())));
    MINING_FUNCTION miningFunction = MINING_FUNCTION.byName(treeModel.getMiningFunction().value());
    PMML_MODEL pmmlModel = PMML_MODEL.byName(treeModel.getClass().getSimpleName());
    Map<String, Expression> assignExpressionMap = new HashMap<>();
    assignExpressionMap.put("targetField", new StringLiteralExpr(targetField));
    assignExpressionMap.put("miningFunction", new NameExpr(miningFunction.getClass().getName() + "." + miningFunction.name()));
    assignExpressionMap.put("pmmlMODEL", new NameExpr(pmmlModel.getClass().getName() + "." + pmmlModel.name()));
    ConstructorDeclaration constructorDeclaration = modelTemplate.getDefaultConstructor().get();
    assertTrue(commonEvaluateConstructor(constructorDeclaration, getSanitizedClassName(treeModel.getModelName()), superInvocationExpressionsMap, assignExpressionMap));
}
Also used : HasKnowledgeBuilderMock(org.kie.pmml.models.drools.commons.implementations.HasKnowledgeBuilderMock) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) HashMap(java.util.HashMap) NameExpr(com.github.javaparser.ast.expr.NameExpr) StringLiteralExpr(com.github.javaparser.ast.expr.StringLiteralExpr) KiePMMLTreeModel(org.kie.pmml.models.drools.tree.model.KiePMMLTreeModel) TreeModel(org.dmg.pmml.tree.TreeModel) Expression(com.github.javaparser.ast.expr.Expression) KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) PMML_MODEL(org.kie.pmml.api.enums.PMML_MODEL) MINING_FUNCTION(org.kie.pmml.api.enums.MINING_FUNCTION) Test(org.junit.Test)

Aggregations

ClassOrInterfaceDeclaration (com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)261 Test (org.junit.Test)174 CompilationUnit (com.github.javaparser.ast.CompilationUnit)164 MethodDeclaration (com.github.javaparser.ast.body.MethodDeclaration)84 ReflectionTypeSolver (com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver)79 AbstractResolutionTest (com.github.javaparser.symbolsolver.resolution.AbstractResolutionTest)71 MethodCallExpr (com.github.javaparser.ast.expr.MethodCallExpr)52 Context (com.github.javaparser.symbolsolver.core.resolution.Context)39 ClassOrInterfaceDeclarationContext (com.github.javaparser.symbolsolver.javaparsermodel.contexts.ClassOrInterfaceDeclarationContext)38 CompilationUnitContext (com.github.javaparser.symbolsolver.javaparsermodel.contexts.CompilationUnitContext)37 ResolvedType (com.github.javaparser.resolution.types.ResolvedType)36 Expression (com.github.javaparser.ast.expr.Expression)33 TypeSolver (com.github.javaparser.symbolsolver.model.resolution.TypeSolver)28 JavaParserFacade (com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade)27 MemoryTypeSolver (com.github.javaparser.symbolsolver.resolution.typesolvers.MemoryTypeSolver)24 HashMap (java.util.HashMap)21 VariableDeclarator (com.github.javaparser.ast.body.VariableDeclarator)20 ResolvedMethodDeclaration (com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration)20 KiePMMLException (org.kie.pmml.api.exceptions.KiePMMLException)20 BlockStmt (com.github.javaparser.ast.stmt.BlockStmt)19