From a59a15e1d13dc2eedb836b222c3b17f833dac295 Mon Sep 17 00:00:00 2001 From: Daniele Zonca Date: Mon, 21 Dec 2020 11:09:16 +0100 Subject: [PATCH] [KOGITO-3972] Make TemplateGenerator use KogitoBuildContext (#934) * WIP * [KOGITO-3974] PredictionModels and DecisionModels are now using templates + Created AbstractPredictionModels and AbstractDecisionModels with common code * [KOGITO-3975] WIP, compile but integration broken tests * [KOGITO-3975] Fix tests * [KOGITO-3974] Revert ApplicationContainerGenerator changes and postpone ApplicationTemplate to a different PR * [KOGITO-3975] Minor * [KOGITO-3974] Fix missing conf use case * [KOGITO-3975] Fix missing conf use case * [KOGITO-3974] Fix test * [KOGITO-3974] Reviewed DecisionModels/PredictionModels templates to move all the code to abstract * [KOGITO-3974] Fix test * [KOGITO-3975] update * [KOGITO-3975] Minor * [KOGITO-3972] Updated TemplatedGenerator to use KogitoBuildContext + Now TemplatedGenerator is only used as delegator + Created AbstractConfigGenerator to simplify ConfigGenerator logic * [KOGITO-3972] Fix DMN hot reload * Fix DMN hot reload * Moved packageName, annotator and addonsConfig to AbstractGenerator + Renamed ApplicationGenerator.withGenerator as ApplicationGenerator.registerAndInitGenerator * Added comment * Fix tests * Fix after merge * Revert ApplicationGenerator.registerAndInitGenerator to ApplicationGenerator.withGenerator * WIP commit * Postponing moduleGenerator initialization when used (compilationUnit() module) + ApplicationSection.classDeclaration renamed compilationUnit to return the whole template * Minor fixes * Fix post merge * Fix AbstractConfigGenerator to handle missing templates * Minor * Created JavaKogitoBuildContext for non-DI context + Moved DependencyInjectionAnnotator reference inside KogitoBuildContext to prevent inconsistent configuration + Removed all withDependencyInjectionAnnotator (no more needed) + Created a common hasDI() method inside KogitoBuildContext and removed all custom useInjection methods * Introduced static AtomicReference in AbstractPredictionModels to make DMN+PMML integration works even if DecisionModels is loaded first + Fix native-image check * After merge fix * Minor * Fix code smell * Fix code smell * Update DMNCompilationProvider.java * Update ApplicationContainerGenerator.java * Minor changes * Minor fixes * Make TemplatedGenerator final --- kogito-codegen/README.md | 7 +- .../codegen/AbstractApplicationSection.java | 6 +- .../codegen/AbstractConfigGenerator.java | 43 +++++ .../kie/kogito/codegen/AbstractGenerator.java | 9 +- .../codegen/ApplicationConfigGenerator.java | 92 +++++++-- .../ApplicationContainerGenerator.java | 59 +++--- .../kogito/codegen/ApplicationGenerator.java | 41 ++-- .../org/kie/kogito/codegen/CodegenUtils.java | 18 -- .../kogito/codegen/ConfigBeanGenerator.java | 17 +- .../kie/kogito/codegen/ConfigGenerator.java | 175 ------------------ .../org/kie/kogito/codegen/Generator.java | 8 +- .../kie/kogito/codegen/GeneratorContext.java | 9 +- .../codegen/ResourceGeneratorFactory.java | 5 +- .../kogito/codegen/TemplatedGenerator.java | 54 +++--- .../context/AbstractKogitoBuildContext.java | 46 +++++ .../context/JavaKogitoBuildContext.java | 40 ++++ .../codegen/context/KogitoBuildContext.java | 18 ++ .../context/QuarkusKogitoBuildContext.java | 13 +- .../context/SpringBootKogitoBuildContext.java | 14 +- .../codegen/decision/DecisionCodegen.java | 25 +-- .../decision/DecisionContainerGenerator.java | 20 +- ...cisionModelResourcesProviderGenerator.java | 18 +- .../DecisionRestResourceGenerator.java | 62 ++++--- .../config/DecisionConfigGenerator.java | 19 +- .../SpringDependencyInjectionAnnotator.java | 1 - .../prediction/PMMLRestResourceGenerator.java | 29 +-- .../codegen/prediction/PredictionCodegen.java | 13 +- .../prediction/PredictionModelsGenerator.java | 18 +- .../config/PredictionConfigGenerator.java | 30 ++- .../process/AbstractResourceGenerator.java | 29 ++- .../process/MessageConsumerGenerator.java | 23 +-- .../process/MessageDataEventGenerator.java | 13 +- .../process/MessageProducerGenerator.java | 21 +-- .../codegen/process/ProcessCodegen.java | 34 ++-- .../process/ProcessContainerGenerator.java | 20 +- .../codegen/process/ProcessGenerator.java | 39 ++-- .../config/ProcessConfigGenerator.java | 19 +- .../CloudEventsMessageProducerGenerator.java | 25 ++- .../events/CloudEventsResourceGenerator.java | 36 ++-- .../TopicsInformationResourceGenerator.java | 26 ++- .../persistence/PersistenceGenerator.java | 47 ++--- .../codegen/rules/DeclaredTypeCodegen.java | 6 +- .../codegen/rules/IncrementalRuleCodegen.java | 37 ++-- .../codegen/rules/QueryEndpointGenerator.java | 23 +-- .../rules/RuleUnitContainerGenerator.java | 27 +-- .../codegen/rules/RuleUnitGenerator.java | 20 +- .../rules/config/RuleConfigGenerator.java | 19 +- .../kogito/codegen/AbstractCodegenTest.java | 32 ++-- ...va => ApplicationConfigGeneratorTest.java} | 23 ++- .../codegen/ApplicationGeneratorTest.java | 30 +-- .../PMMLRestResourceGeneratorTest.java | 34 +--- .../PredictionContainerGeneratorTest.java | 3 +- .../config/PredictionConfigGeneratorTest.java | 37 ++-- ...oudEventsMessageProducerGeneratorTest.java | 11 +- .../CloudEventsResourceGeneratorTest.java | 16 +- ...opicsInformationResourceGeneratorTest.java | 11 +- .../MongoDBPersistenceGeneratorTest.java | 12 +- .../rules/IncrementalRuleCodegenTest.java | 1 + .../spring/BusinessRuleTaskSpringTest.java | 4 +- .../spring/BusinessRuleUnitSpringTest.java | 4 +- .../spring/CallActivityTaskSpringTest.java | 4 +- .../spring/EmbeddedSubProcessSpringTest.java | 4 +- .../spring/EventSubProcessSpringTest.java | 4 +- .../tests/spring/GatewaySpringTest.java | 4 +- .../spring/InvalidProcessSpringTest.java | 4 +- .../MessageIntermediateEventSpringTest.java | 4 +- .../spring/MessageStartEventSpringTest.java | 4 +- .../tests/spring/PublishEventSpringTest.java | 4 +- .../tests/spring/ServiceTaskSpringTest.java | 4 +- .../tests/spring/SignalEventSpringTest.java | 4 +- .../tests/spring/TimerEventSpringTest.java | 4 +- .../tests/spring/UserTaskSpringTest.java | 4 +- .../kogito/maven/plugin/AbstractKieMojo.java | 14 +- .../maven/plugin/GenerateDeclaredTypes.java | 6 +- .../maven/plugin/GenerateModelMojo.java | 8 +- .../maven/plugin/ProcessClassesMojo.java | 2 - .../deployment/KogitoAssetsProcessor.java | 10 +- .../deployment/KogitoCompilationProvider.java | 5 +- 78 files changed, 760 insertions(+), 924 deletions(-) create mode 100644 kogito-codegen/src/main/java/org/kie/kogito/codegen/AbstractConfigGenerator.java delete mode 100644 kogito-codegen/src/main/java/org/kie/kogito/codegen/ConfigGenerator.java create mode 100644 kogito-codegen/src/main/java/org/kie/kogito/codegen/context/AbstractKogitoBuildContext.java create mode 100644 kogito-codegen/src/main/java/org/kie/kogito/codegen/context/JavaKogitoBuildContext.java rename kogito-codegen/src/test/java/org/kie/kogito/codegen/{ConfigGeneratorTest.java => ApplicationConfigGeneratorTest.java} (57%) diff --git a/kogito-codegen/README.md b/kogito-codegen/README.md index 8724ab76511..f53e8f53001 100644 --- a/kogito-codegen/README.md +++ b/kogito-codegen/README.md @@ -9,8 +9,7 @@ configure its global behavior. ```java ApplicationGenerator appGen = - new ApplicationGenerator(appPackageName, targetDirectory) - .withDependencyInjection(...) + new ApplicationGenerator(context, appPackageName, targetDirectory) .withAddons(...); ``` @@ -22,11 +21,11 @@ configure its global behavior. - Each `Generator` may come with its own specific configuration ```java - appGen.withGenerator(RuleCodegen.ofPath(ruleSourceDirectory)) + appGen.setupGenerator(RuleCodegen.ofPath(ruleSourceDirectory)) .withKModule(getKModuleModel()) .withClassLoader(...); - appGen.withGenerator(ProcessCodegen.ofPath(processSourceDirectory)) + appGen.setupGenerator(ProcessCodegen.ofPath(processSourceDirectory)) .withAddons(...); ``` diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/AbstractApplicationSection.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/AbstractApplicationSection.java index b0c80c68c87..99178c9ef9e 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/AbstractApplicationSection.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/AbstractApplicationSection.java @@ -15,6 +15,8 @@ package org.kie.kogito.codegen; +import org.kie.kogito.codegen.context.KogitoBuildContext; + /** * Base implementation for an {@link ApplicationSection}. *

@@ -24,10 +26,12 @@ */ public abstract class AbstractApplicationSection implements ApplicationSection { + protected final KogitoBuildContext buildContext; private final String sectionClassName; - public AbstractApplicationSection(String sectionClassName) { + public AbstractApplicationSection(KogitoBuildContext buildContext, String sectionClassName) { this.sectionClassName = sectionClassName; + this.buildContext = buildContext; } @Override diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/AbstractConfigGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/AbstractConfigGenerator.java new file mode 100644 index 00000000000..61effb38dda --- /dev/null +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/AbstractConfigGenerator.java @@ -0,0 +1,43 @@ +/* + * Copyright 2020 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.kie.kogito.codegen; + +import com.github.javaparser.ast.CompilationUnit; +import org.kie.kogito.codegen.context.KogitoBuildContext; + +import java.util.Optional; + +public class AbstractConfigGenerator { + + private final TemplatedGenerator templatedGenerator; + + public AbstractConfigGenerator(KogitoBuildContext buildContext, String packageName, String targetTypeName, String resourceCdi, String resourceSpring) { + this.templatedGenerator = new TemplatedGenerator( + buildContext, + packageName, + targetTypeName, + resourceCdi, + resourceSpring); + } + + public Optional generate() { + Optional compilationUnit = templatedGenerator.compilationUnit(); + return compilationUnit.map(cu -> + new GeneratedFile(GeneratedFile.Type.APPLICATION_CONFIG, + templatedGenerator.generatedFilePath(), + cu.toString())); + } +} diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/AbstractGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/AbstractGenerator.java index c8d7133cd86..9e0d32669ce 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/AbstractGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/AbstractGenerator.java @@ -21,15 +21,13 @@ import java.util.List; import java.util.Map; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; import org.kie.kogito.codegen.metadata.DefaultLabeler; import org.kie.kogito.codegen.metadata.Labeler; public abstract class AbstractGenerator implements Generator { protected Path projectDirectory; - protected GeneratorContext context; - protected DependencyInjectionAnnotator annotator; + protected GeneratorContext context = GeneratorContext.emptyContext(); protected String packageName = ApplicationGenerator.DEFAULT_PACKAGE_NAME; protected AddonsConfig addonsConfig = AddonsConfig.DEFAULT; @@ -70,11 +68,6 @@ public final Map getLabels() { return labels; } - @Override - public void setDependencyInjection(DependencyInjectionAnnotator annotator) { - this.annotator = annotator; - } - @Override public void setPackageName(String packageName) { this.packageName = packageName; diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/ApplicationConfigGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/ApplicationConfigGenerator.java index e50917590ed..a60dc3d7766 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/ApplicationConfigGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/ApplicationConfigGenerator.java @@ -15,9 +15,9 @@ package org.kie.kogito.codegen; +import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.Optional; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; @@ -26,33 +26,86 @@ import com.github.javaparser.ast.expr.ObjectCreationExpr; import com.github.javaparser.ast.expr.StringLiteralExpr; import org.kie.kogito.Addons; +import org.kie.kogito.codegen.context.KogitoBuildContext; +import org.kie.kogito.codegen.decision.config.DecisionConfigGenerator; +import org.kie.kogito.codegen.prediction.config.PredictionConfigGenerator; +import org.kie.kogito.codegen.process.config.ProcessConfigGenerator; +import org.kie.kogito.codegen.rules.config.RuleConfigGenerator; +import static java.util.Arrays.asList; +import static java.util.Optional.ofNullable; import static org.kie.kogito.codegen.CodegenUtils.newObject; -public class ApplicationConfigGenerator extends TemplatedGenerator { +public class ApplicationConfigGenerator { private static final String CLASS_NAME = "ApplicationConfig"; private static final String RESOURCE_DEFAULT = "/class-templates/config/ApplicationConfigTemplate.java"; private static final String RESOURCE_CDI = "/class-templates/config/CdiApplicationConfigTemplate.java"; private static final String RESOURCE_SPRING = "/class-templates/config/SpringApplicationConfigTemplate.java"; + private final TemplatedGenerator templatedGenerator; + private Collection addons = Collections.emptyList(); - public ApplicationConfigGenerator(String packageName) { - super(packageName, - CLASS_NAME, - RESOURCE_CDI, - RESOURCE_SPRING, - RESOURCE_DEFAULT); + private ProcessConfigGenerator processConfig; + private RuleConfigGenerator ruleConfig; + private DecisionConfigGenerator decisionConfig; + private PredictionConfigGenerator predictionConfig; + private ConfigBeanGenerator configBean; + + public ApplicationConfigGenerator(KogitoBuildContext buildContext, String packageName) { + this.templatedGenerator = new TemplatedGenerator( + buildContext, + packageName, + CLASS_NAME, + RESOURCE_CDI, + RESOURCE_SPRING, + RESOURCE_DEFAULT); + + this.configBean = new ConfigBeanGenerator(buildContext, packageName); + } + + public ApplicationConfigGenerator withProcessConfig(ProcessConfigGenerator cfg) { + this.processConfig = cfg; + return this; + } + + public ApplicationConfigGenerator withRuleConfig(RuleConfigGenerator cfg) { + this.ruleConfig = cfg; + return this; + } + + public ApplicationConfigGenerator withDecisionConfig(DecisionConfigGenerator cfg) { + this.decisionConfig = cfg; + return this; + } + + public ApplicationConfigGenerator withPredictionConfig(PredictionConfigGenerator cfg) { + this.predictionConfig = cfg; + return this; } - @Override - public Optional compilationUnit() { - Optional compilationUnit = super.compilationUnit(); - compilationUnit - .flatMap(u -> u.findFirst(ClassOrInterfaceDeclaration.class)) + public Collection generate() { + ArrayList generatedFiles = new ArrayList<>(); + generatedFiles.add(generateApplicationConfigDescriptor()); + + asList(processConfig, ruleConfig, predictionConfig, decisionConfig, configBean) + .forEach(configGenerator -> ofNullable(configGenerator) + .flatMap(AbstractConfigGenerator::generate) + .ifPresent(generatedFiles::add)); + + return generatedFiles; + } + + private GeneratedFile generateApplicationConfigDescriptor() { + CompilationUnit compilationUnit = templatedGenerator.compilationUnitOrThrow(); + + compilationUnit.findFirst(ClassOrInterfaceDeclaration.class) .ifPresent(this::replaceAddonPlaceHolder); - return compilationUnit; + + return new GeneratedFile(GeneratedFile.Type.APPLICATION_CONFIG, + templatedGenerator.generatedFilePath(), + compilationUnit.toString()); } private void replaceAddonPlaceHolder(ClassOrInterfaceDeclaration cls) { @@ -60,15 +113,15 @@ private void replaceAddonPlaceHolder(ClassOrInterfaceDeclaration cls) { NameExpr addonsPlaceHolder = cls.findFirst(NameExpr.class, e -> e.getNameAsString().equals("$Addons$")). orElseThrow(() -> new InvalidTemplateException( - typeName(), - templatePath(), + templatedGenerator.typeName(), + templatedGenerator.templatePath(), "Missing $Addons$ placeholder")); ObjectCreationExpr addonsList = generateAddonsList(); addonsPlaceHolder.getParentNode() .orElseThrow(() -> new InvalidTemplateException( - typeName(), - templatePath(), + templatedGenerator.typeName(), + templatedGenerator.templatePath(), "Cannot replace $Addons$ placeholder")) .replace(addonsPlaceHolder, addonsList); } @@ -82,8 +135,7 @@ private ObjectCreationExpr generateAddonsList() { return newObject(Addons.class, asListOfAddons); } - public ApplicationConfigGenerator withAddons(Collection addons) { + public void withAddons(Collection addons) { this.addons = addons; - return this; } } diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/ApplicationContainerGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/ApplicationContainerGenerator.java index 7bc6bca6a40..4d97f1887a4 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/ApplicationContainerGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/ApplicationContainerGenerator.java @@ -21,31 +21,38 @@ import com.github.javaparser.ast.expr.MethodCallExpr; import com.github.javaparser.ast.expr.ObjectCreationExpr; import com.github.javaparser.ast.expr.ThisExpr; +import org.kie.kogito.codegen.context.JavaKogitoBuildContext; +import org.kie.kogito.codegen.context.KogitoBuildContext; import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.Optional; import static java.util.function.Function.identity; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; -public class ApplicationContainerGenerator extends TemplatedGenerator { +public class ApplicationContainerGenerator { public static final String APPLICATION_CLASS_NAME = "Application"; private static final String RESOURCE_CDI = "/class-templates/CdiApplicationTemplate.java"; private static final String RESOURCE_SPRING = "/class-templates/SpringApplicationTemplate.java"; private static final String RESOURCE_DEFAULT = "/class-templates/ApplicationTemplate.java"; + private final TemplatedGenerator templatedGenerator; private List sections = new ArrayList<>(); - - public ApplicationContainerGenerator(String packageName) { - super(packageName, - APPLICATION_CLASS_NAME, - RESOURCE_CDI, - RESOURCE_SPRING, - RESOURCE_DEFAULT); + private KogitoBuildContext buildContext; + + public ApplicationContainerGenerator(KogitoBuildContext buildContext, String packageName) { + this.templatedGenerator = new TemplatedGenerator( + buildContext, + packageName, + APPLICATION_CLASS_NAME, + RESOURCE_CDI, + RESOURCE_SPRING, + RESOURCE_DEFAULT); + + this.buildContext = buildContext; } public ApplicationContainerGenerator withSections(List sections) { @@ -53,45 +60,37 @@ public ApplicationContainerGenerator withSections(List sections) { return this; } - public CompilationUnit getCompilationUnitOrThrow() { - return compilationUnit() - .orElseThrow(() -> new InvalidTemplateException( - APPLICATION_CLASS_NAME, - templatePath(), - "Cannot find template for " + super.typeName())); - } - - @Override - public Optional compilationUnit() { - Optional optionalCompilationUnit = super.compilationUnit(); - CompilationUnit compilationUnit = - optionalCompilationUnit - .orElseThrow(() -> new InvalidTemplateException( - APPLICATION_CLASS_NAME, - templatePath(), - "Cannot find template for " + super.typeName())); + protected CompilationUnit getCompilationUnitOrThrow() { + CompilationUnit compilationUnit = templatedGenerator.compilationUnitOrThrow("Cannot find template for " + templatedGenerator.typeName()); ClassOrInterfaceDeclaration cls = compilationUnit .findFirst(ClassOrInterfaceDeclaration.class) .orElseThrow(() -> new InvalidTemplateException( APPLICATION_CLASS_NAME, - templatePath(), + templatedGenerator.templatePath(), "Compilation unit doesn't contain a class or interface declaration!")); // ApplicationTemplate (no CDI/Spring) has placeholders to replace - if (annotator == null) { + if (buildContext == null || buildContext instanceof JavaKogitoBuildContext) { replacePlaceholder(getLoadEnginesMethod(cls), sections); } cls.getMembers().sort(new BodyDeclarationComparator()); - return optionalCompilationUnit; + + return compilationUnit; + } + + public GeneratedFile generate() { + return new GeneratedFile(GeneratedFile.Type.APPLICATION, + templatedGenerator.generatedFilePath(), + getCompilationUnitOrThrow().toString()); } private MethodCallExpr getLoadEnginesMethod(ClassOrInterfaceDeclaration cls) { return cls.findFirst(MethodCallExpr.class, mtd -> "loadEngines".equals(mtd.getNameAsString())) .orElseThrow(() -> new InvalidTemplateException( APPLICATION_CLASS_NAME, - templatePath(), + templatedGenerator.templatePath(), "Impossible to find loadEngines invocation")); } diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/ApplicationGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/ApplicationGenerator.java index 0a295e4c543..9d214304777 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/ApplicationGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/ApplicationGenerator.java @@ -29,9 +29,7 @@ import java.util.Objects; import java.util.stream.Collectors; -import com.github.javaparser.ast.CompilationUnit; import org.drools.core.util.StringUtils; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; import org.kie.kogito.codegen.metadata.Labeler; import org.kie.kogito.codegen.metadata.MetaDataWriter; import org.kie.kogito.codegen.metadata.PrometheusLabeler; @@ -49,10 +47,8 @@ public class ApplicationGenerator { private final String packageName; private final File targetDirectory; - private DependencyInjectionAnnotator annotator; - private final ApplicationContainerGenerator applicationMainGenerator; - private ConfigGenerator configGenerator; + private ApplicationConfigGenerator configGenerator; private List generators = new ArrayList<>(); private Map labelers = new HashMap<>(); @@ -60,14 +56,14 @@ public class ApplicationGenerator { private ClassLoader classLoader; private AddonsConfig addonsConfig = AddonsConfig.DEFAULT; - public ApplicationGenerator(String packageName, File targetDirectory) { - + public ApplicationGenerator(GeneratorContext context, String packageName, File targetDirectory) { + this.context = context; this.packageName = packageName; this.targetDirectory = targetDirectory; this.classLoader = Thread.currentThread().getContextClassLoader(); - this.applicationMainGenerator = new ApplicationContainerGenerator(packageName); + this.applicationMainGenerator = new ApplicationContainerGenerator(context.getBuildContext(), packageName); - this.configGenerator = new ConfigGenerator(packageName); + this.configGenerator = new ApplicationConfigGenerator(context.getBuildContext(), packageName); this.configGenerator.withAddons(loadAddonList()); } @@ -79,18 +75,6 @@ private String getFilePath(String className) { return (this.packageName + "." + className).replace('.', '/') + ".java"; } - public ApplicationGenerator withDependencyInjection(DependencyInjectionAnnotator annotator) { - this.annotator = annotator; - this.applicationMainGenerator.withDependencyInjection(annotator); - this.configGenerator.withDependencyInjection(annotator); - return this; - } - - public ApplicationGenerator withGeneratorContext(GeneratorContext context) { - this.context = context; - return this; - } - public ApplicationGenerator withAddons(AddonsConfig addonsConfig) { if (addonsConfig.usePrometheusMonitoring()) { this.labelers.put(PrometheusLabeler.class, new PrometheusLabeler()); @@ -130,10 +114,7 @@ public GeneratedFile generateApplicationDescriptor() { .collect(Collectors.toList()); applicationMainGenerator.withSections(sections); - CompilationUnit compilationUnit = applicationMainGenerator.getCompilationUnitOrThrow(); - return new GeneratedFile(GeneratedFile.Type.APPLICATION, - applicationMainGenerator.generatedFilePath(), - compilationUnit.toString()); + return applicationMainGenerator.generate(); } private List generateApplicationSections() { @@ -161,7 +142,6 @@ private List generateApplicationSections() { public G setupGenerator(G generator) { this.generators.add(generator); generator.setPackageName(packageName); - generator.setDependencyInjection(annotator); generator.setProjectDirectory(targetDirectory.getParentFile().toPath()); generator.setContext(context); generator.setAddonsConfig(addonsConfig); @@ -192,12 +172,13 @@ private Collection loadAddonList() { private void logGeneratedFiles(Collection files) { if (LOGGER.isDebugEnabled()) { + String separator = "====="; for (GeneratedFile file : files) { - LOGGER.debug("====="); - LOGGER.debug(file.getType() + ": " + file.relativePath()); - LOGGER.debug("====="); + LOGGER.debug(separator); + LOGGER.debug("{}: {}", file.getType(), file.relativePath()); + LOGGER.debug(separator); LOGGER.debug(new String(file.contents())); - LOGGER.debug("====="); + LOGGER.debug(separator); } } } diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/CodegenUtils.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/CodegenUtils.java index d160ef9d066..74eebd94330 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/CodegenUtils.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/CodegenUtils.java @@ -24,15 +24,11 @@ import com.github.javaparser.ast.body.MethodDeclaration; import com.github.javaparser.ast.body.Parameter; import com.github.javaparser.ast.expr.Expression; -import com.github.javaparser.ast.expr.NameExpr; import com.github.javaparser.ast.expr.ObjectCreationExpr; import com.github.javaparser.ast.expr.SimpleName; import com.github.javaparser.ast.stmt.BlockStmt; -import com.github.javaparser.ast.stmt.IfStmt; -import com.github.javaparser.ast.stmt.ReturnStmt; import com.github.javaparser.ast.type.ClassOrInterfaceType; import com.github.javaparser.ast.type.Type; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; public class CodegenUtils { @@ -120,18 +116,4 @@ public static boolean isApplicationField(FieldDeclaration fd) { public static boolean isObjectMapperField(FieldDeclaration fd) { return fd.getElementType().asClassOrInterfaceType().getNameAsString().equals("ObjectMapper"); } - - public static MethodDeclaration extractOptionalInjection(String type, String fieldName, String defaultMethod, DependencyInjectionAnnotator annotator) { - BlockStmt body = new BlockStmt(); - MethodDeclaration extractMethod = new MethodDeclaration() - .addModifier(Modifier.Keyword.PROTECTED) - .setName("extract_" + fieldName) - .setType(type) - .setBody(body); - Expression condition = annotator.optionalInstanceExists(fieldName); - IfStmt valueExists = new IfStmt(condition, new ReturnStmt(annotator.getOptionalInstance(fieldName)), new ReturnStmt(new NameExpr(defaultMethod))); - body.addStatement(valueExists); - return extractMethod; - } - } diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/ConfigBeanGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/ConfigBeanGenerator.java index 11e597f356a..04d3fc15255 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/ConfigBeanGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/ConfigBeanGenerator.java @@ -14,16 +14,15 @@ */ package org.kie.kogito.codegen; -public class ConfigBeanGenerator extends TemplatedGenerator { +import org.kie.kogito.codegen.context.KogitoBuildContext; - private static final String RESOURCE_CDI = "/class-templates/config/CdiConfigBeanTemplate.java"; - private static final String RESOURCE_SPRING = "/class-templates/config/SpringConfigBeanTemplate.java"; +public class ConfigBeanGenerator extends AbstractConfigGenerator { - public ConfigBeanGenerator(String packageName) { - super(packageName, - "ConfigBean", - RESOURCE_CDI, - RESOURCE_SPRING); + public ConfigBeanGenerator(KogitoBuildContext buildContext, String packageName) { + super(buildContext, + packageName, + "ConfigBean", + "/class-templates/config/CdiConfigBeanTemplate.java", + "/class-templates/config/SpringConfigBeanTemplate.java"); } - } diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/ConfigGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/ConfigGenerator.java deleted file mode 100644 index 62709d36538..00000000000 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/ConfigGenerator.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright 2019 Red Hat, Inc. and/or its affiliates. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.kie.kogito.codegen; - -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Optional; - -import com.github.javaparser.ast.CompilationUnit; -import com.github.javaparser.ast.expr.ObjectCreationExpr; -import org.kie.kogito.codegen.decision.config.DecisionConfigGenerator; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; -import org.kie.kogito.codegen.prediction.config.PredictionConfigGenerator; -import org.kie.kogito.codegen.process.config.ProcessConfigGenerator; -import org.kie.kogito.codegen.rules.config.RuleConfigGenerator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ConfigGenerator { - - private static final Logger LOGGER = LoggerFactory.getLogger(ConfigGenerator.class); - private final ApplicationConfigGenerator applicationConfigGenerator; - - private DependencyInjectionAnnotator annotator; - private ProcessConfigGenerator processConfig; - private RuleConfigGenerator ruleConfig; - private DecisionConfigGenerator decisionConfig; - private PredictionConfigGenerator predictionConfig; - - private String packageName; - private final String targetTypeName; - private final String targetCanonicalName; - - public ConfigGenerator(String packageName) { - this.packageName = packageName; - this.targetTypeName = "ApplicationConfig"; - this.targetCanonicalName = this.packageName + "." + targetTypeName; - this.applicationConfigGenerator = new ApplicationConfigGenerator(packageName); - } - - public ConfigGenerator withProcessConfig(ProcessConfigGenerator cfg) { - this.processConfig = cfg; - if (this.processConfig != null) { - this.processConfig.withDependencyInjection(annotator); - } - return this; - } - - public ConfigGenerator withRuleConfig(RuleConfigGenerator cfg) { - this.ruleConfig = cfg; - if (this.ruleConfig != null) { - this.ruleConfig.withDependencyInjection(annotator); - } - return this; - } - - public ConfigGenerator withDecisionConfig(DecisionConfigGenerator cfg) { - this.decisionConfig = cfg; - if (this.decisionConfig != null) { - this.decisionConfig.withDependencyInjection(annotator); - } - return this; - } - - public ConfigGenerator withPredictionConfig(PredictionConfigGenerator cfg) { - this.predictionConfig = cfg; - if (this.predictionConfig != null) { - this.predictionConfig.withDependencyInjection(annotator); - } - return this; - } - - public ConfigGenerator withDependencyInjection(DependencyInjectionAnnotator annotator) { - this.annotator = annotator; - this.applicationConfigGenerator.withDependencyInjection(annotator); - return this; - } - - public ObjectCreationExpr newInstance() { - return new ObjectCreationExpr() - .setType(targetCanonicalName); - } - - public Collection generate() { - ArrayList generatedFiles = new ArrayList<>(); - generatedFiles.add(generateApplicationConfigDescriptor()); - - generateProcessConfigDescriptor().ifPresent(generatedFiles::add); - generateRuleConfigDescriptor().ifPresent(generatedFiles::add); - generatePredictionConfigDescriptor().ifPresent(generatedFiles::add); - generateDecisionConfigDescriptor().ifPresent(generatedFiles::add); - generateBeanConfig().ifPresent(generatedFiles::add); - - return generatedFiles; - } - - private GeneratedFile generateApplicationConfigDescriptor() { - CompilationUnit compilationUnit = applicationConfigGenerator.compilationUnit() - .orElseThrow(() -> new InvalidTemplateException( - applicationConfigGenerator.typeName(), - applicationConfigGenerator.templatePath(), - "Missing template")); - return new GeneratedFile(GeneratedFile.Type.APPLICATION_CONFIG, - applicationConfigGenerator.generatedFilePath(), - compilationUnit.toString()); - } - - private Optional generateProcessConfigDescriptor() { - if (processConfig == null) { - return Optional.empty(); - } - Optional compilationUnit = processConfig.compilationUnit(); - return compilationUnit.map(c -> new GeneratedFile(GeneratedFile.Type.APPLICATION_CONFIG, - processConfig.generatedFilePath(), - c.toString())); - } - - private Optional generateRuleConfigDescriptor() { - if (ruleConfig == null) { - return Optional.empty(); - } - Optional compilationUnit = ruleConfig.compilationUnit(); - return compilationUnit.map(c -> new GeneratedFile(GeneratedFile.Type.APPLICATION_CONFIG, - ruleConfig.generatedFilePath(), - c.toString())); - } - - private Optional generateDecisionConfigDescriptor() { - if (decisionConfig == null) { - return Optional.empty(); - } - Optional compilationUnit = decisionConfig.compilationUnit(); - return compilationUnit.map(c -> new GeneratedFile(GeneratedFile.Type.APPLICATION_CONFIG, - decisionConfig.generatedFilePath(), - c.toString())); - } - - private Optional generatePredictionConfigDescriptor() { - if (predictionConfig == null) { - return Optional.empty(); - } - Optional compilationUnit = predictionConfig.compilationUnit(); - return compilationUnit.map(c -> new GeneratedFile(GeneratedFile.Type.APPLICATION_CONFIG, - predictionConfig.generatedFilePath(), - c.toString())); - } - - private Optional generateBeanConfig() { - ConfigBeanGenerator configBeanGenerator = new ConfigBeanGenerator(packageName); - configBeanGenerator.withDependencyInjection(annotator); - - Optional compilationUnit = configBeanGenerator.compilationUnit(); - return compilationUnit.map(c -> new GeneratedFile(GeneratedFile.Type.APPLICATION_CONFIG, - configBeanGenerator.generatedFilePath(), - c.toString())); - } - - public void withAddons(Collection addons) { - this.applicationConfigGenerator.withAddons(addons); - } -} diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/Generator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/Generator.java index 5e506cb15bf..fae80c3e714 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/Generator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/Generator.java @@ -20,8 +20,6 @@ import java.util.Collections; import java.util.Map; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; - /** * A code generator for a part of the platform, e.g. rules, processes, etc. */ @@ -41,17 +39,15 @@ public interface Generator { Collection generate(); /** - * Consumes the given ConfigGenerator so that it can enrich it with + * Consumes the given ApplicationConfigGenerator so that it can enrich it with * further, Generator-specific details. * * This is automatically called by the ApplicationGenerator. */ - void updateConfig(ConfigGenerator cfg); + void updateConfig(ApplicationConfigGenerator cfg); void setPackageName(String packageName); - void setDependencyInjection(DependencyInjectionAnnotator annotator); - void setProjectDirectory(Path projectDirectory); void setContext(GeneratorContext context); diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/GeneratorContext.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/GeneratorContext.java index 0ac6c7c00d1..3ef0edbc68d 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/GeneratorContext.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/GeneratorContext.java @@ -19,9 +19,11 @@ import java.io.FileReader; import java.io.IOException; import java.util.Collection; +import java.util.Objects; import java.util.Optional; import java.util.Properties; +import org.kie.kogito.codegen.context.JavaKogitoBuildContext; import org.kie.kogito.codegen.context.KogitoBuildContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -32,6 +34,10 @@ public class GeneratorContext { private static final String APPLICATION_PROPERTIES_FILE_NAME = "application.properties"; + public static GeneratorContext emptyContext() { + return ofResourcePath().withBuildContext(new JavaKogitoBuildContext()); + } + public static GeneratorContext ofResourcePath(File... resourcePaths) { Properties applicationProperties = new Properties(); @@ -50,7 +56,7 @@ public static GeneratorContext ofProperties(Properties props) { return new GeneratorContext(props); } - private KogitoBuildContext buildContext; + private KogitoBuildContext buildContext = new JavaKogitoBuildContext(); private Properties applicationProperties = new Properties(); @@ -59,6 +65,7 @@ private GeneratorContext(Properties properties) { } public GeneratorContext withBuildContext(KogitoBuildContext buildContext) { + Objects.requireNonNull(buildContext, "KogitoBuildContext cannot be null"); this.buildContext = buildContext; return this; } diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/ResourceGeneratorFactory.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/ResourceGeneratorFactory.java index 83ffd1c50af..aff935976e2 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/ResourceGeneratorFactory.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/ResourceGeneratorFactory.java @@ -22,6 +22,7 @@ import java.util.Optional; import org.kie.api.definition.process.WorkflowProcess; +import org.kie.kogito.codegen.context.JavaKogitoBuildContext; import org.kie.kogito.codegen.context.KogitoBuildContext; import org.kie.kogito.codegen.context.QuarkusKogitoBuildContext; import org.kie.kogito.codegen.context.SpringBootKogitoBuildContext; @@ -36,7 +37,8 @@ enum GeneratorType { SPRING(SpringBootKogitoBuildContext.class, false), QUARKUS(QuarkusKogitoBuildContext.class, false), SPRING_REACTIVE(SpringBootKogitoBuildContext.class, true), - QUARKUS_REACTIVE(QuarkusKogitoBuildContext.class, true); + QUARKUS_REACTIVE(QuarkusKogitoBuildContext.class, true), + JAVA(JavaKogitoBuildContext.class, false); Class buildContextClass; boolean reactive; @@ -76,6 +78,7 @@ public Optional create(GeneratorContext context, modelfqcn, processfqcn, appCanonicalName); + case JAVA: case QUARKUS: return new ResourceGenerator(context, process, diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/TemplatedGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/TemplatedGenerator.java index 7177fdfd0ed..7c261f3e12f 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/TemplatedGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/TemplatedGenerator.java @@ -22,13 +22,17 @@ import com.github.javaparser.ParseProblemException; import com.github.javaparser.ast.CompilationUnit; -import org.kie.kogito.codegen.di.CDIDependencyInjectionAnnotator; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; -import org.kie.kogito.codegen.di.SpringDependencyInjectionAnnotator; +import org.kie.kogito.codegen.context.JavaKogitoBuildContext; +import org.kie.kogito.codegen.context.KogitoBuildContext; +import org.kie.kogito.codegen.context.QuarkusKogitoBuildContext; +import org.kie.kogito.codegen.context.SpringBootKogitoBuildContext; import static com.github.javaparser.StaticJavaParser.parse; -public class TemplatedGenerator { +/** + * Utility class to handle multi platform template generation + */ +public final class TemplatedGenerator { private final String packageName; private final String sourceFilePath; @@ -37,10 +41,11 @@ public class TemplatedGenerator { private final String resourceSpring; private final String resourceDefault; - protected DependencyInjectionAnnotator annotator; private final String targetTypeName; + private final KogitoBuildContext buildContext; public TemplatedGenerator( + KogitoBuildContext buildContext, String packageName, String targetTypeName, String resourceCdi, @@ -55,6 +60,7 @@ public TemplatedGenerator( "Package name \"{0}\" is not valid. It should be a valid Java package name.", packageName)); } + this.buildContext = buildContext; this.packageName = packageName; this.targetTypeName = targetTypeName; String targetCanonicalName = this.packageName + "." + this.targetTypeName; @@ -65,11 +71,13 @@ public TemplatedGenerator( } public TemplatedGenerator( + KogitoBuildContext buildContext, String packageName, String targetTypeName, String resourceCdi, String resourceSpring) { - this(packageName, + this(buildContext, + packageName, targetTypeName, resourceCdi, resourceSpring, @@ -88,15 +96,6 @@ public String typeName() { return targetTypeName; } - protected String packageName() { - return this.packageName; - } - - public TemplatedGenerator withDependencyInjection(DependencyInjectionAnnotator annotator) { - this.annotator = annotator; - return this; - } - public Optional compilationUnit() { String selectedResource = selectResource(); if (selectedResource == null) { @@ -114,19 +113,26 @@ public Optional compilationUnit() { } } + public CompilationUnit compilationUnitOrThrow(String errorMessage) { + return compilationUnit().orElseThrow(() -> new InvalidTemplateException( + typeName(), + templatePath(), + errorMessage)); + } + + public CompilationUnit compilationUnitOrThrow() { + return compilationUnitOrThrow("Missing template"); + } + private String selectResource() { - if (annotator == null) { - if (resourceDefault == null) { - return null; - } else { - return resourceDefault; - } - } else if (annotator instanceof CDIDependencyInjectionAnnotator) { + if (buildContext == null || buildContext instanceof JavaKogitoBuildContext) { + return resourceDefault; + } else if (buildContext instanceof QuarkusKogitoBuildContext) { return resourceCdi; - } else if (annotator instanceof SpringDependencyInjectionAnnotator) { + } else if (buildContext instanceof SpringBootKogitoBuildContext) { return resourceSpring; } else { - throw new IllegalArgumentException("Unknown annotator " + annotator); + throw new IllegalArgumentException("Unknown buildContext " + buildContext); } } } diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/context/AbstractKogitoBuildContext.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/context/AbstractKogitoBuildContext.java new file mode 100644 index 00000000000..ae5142e6732 --- /dev/null +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/context/AbstractKogitoBuildContext.java @@ -0,0 +1,46 @@ +/* + * Copyright 2020 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.kie.kogito.codegen.context; + +import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; + +import java.util.function.Predicate; + +public abstract class AbstractKogitoBuildContext implements KogitoBuildContext { + + protected final Predicate classAvailabilityResolver; + protected DependencyInjectionAnnotator dependencyInjectionAnnotator; + + public AbstractKogitoBuildContext(Predicate classAvailabilityResolver, DependencyInjectionAnnotator dependencyInjectionAnnotator) { + this.classAvailabilityResolver = classAvailabilityResolver; + this.dependencyInjectionAnnotator = dependencyInjectionAnnotator; + } + + @Override + public boolean hasClassAvailable(String fqcn) { + return classAvailabilityResolver.test(fqcn); + } + + @Override + public DependencyInjectionAnnotator getDependencyInjectionAnnotator() { + return dependencyInjectionAnnotator; + } + + @Override + public void setDependencyInjectionAnnotator(DependencyInjectionAnnotator dependencyInjectionAnnotator) { + this.dependencyInjectionAnnotator = dependencyInjectionAnnotator; + } +} \ No newline at end of file diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/context/JavaKogitoBuildContext.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/context/JavaKogitoBuildContext.java new file mode 100644 index 00000000000..5644051957d --- /dev/null +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/context/JavaKogitoBuildContext.java @@ -0,0 +1,40 @@ +/* + * Copyright 2020 Red Hat, Inc. and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.kie.kogito.codegen.context; + +import java.util.function.Predicate; + +public class JavaKogitoBuildContext extends AbstractKogitoBuildContext { + + public JavaKogitoBuildContext() { + this(Thread.currentThread().getContextClassLoader()); + } + + public JavaKogitoBuildContext(final ClassLoader classLoader) { + this(className -> { + try { + classLoader.loadClass(className); + return true; + } catch (ClassNotFoundException e) { + return false; + } + }); + } + + public JavaKogitoBuildContext(Predicate classAvailabilityResolver) { + super(classAvailabilityResolver, null); + } +} \ No newline at end of file diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/context/KogitoBuildContext.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/context/KogitoBuildContext.java index d93b9aec8ba..e547322e86c 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/context/KogitoBuildContext.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/context/KogitoBuildContext.java @@ -16,10 +16,28 @@ package org.kie.kogito.codegen.context; import org.kie.kogito.codegen.KogitoCodeGenConstants; +import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; public interface KogitoBuildContext { boolean hasClassAvailable(String fqcn); + + /** + * Return DependencyInjectionAnnotator if available or null + * @return + */ + DependencyInjectionAnnotator getDependencyInjectionAnnotator(); + + /** + * Method to override default dependency injection annotator + * @param dependencyInjectionAnnotator + * @return + */ + void setDependencyInjectionAnnotator(DependencyInjectionAnnotator dependencyInjectionAnnotator); + + default boolean hasDI() { + return getDependencyInjectionAnnotator() != null; + } default boolean isValidationSupported() { return hasClassAvailable(KogitoCodeGenConstants.VALIDATION_CLASS); diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/context/QuarkusKogitoBuildContext.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/context/QuarkusKogitoBuildContext.java index bcb6b1ebd3f..885478f52f2 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/context/QuarkusKogitoBuildContext.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/context/QuarkusKogitoBuildContext.java @@ -15,18 +15,13 @@ package org.kie.kogito.codegen.context; -import java.util.function.Predicate; +import org.kie.kogito.codegen.di.CDIDependencyInjectionAnnotator; -public class QuarkusKogitoBuildContext implements KogitoBuildContext { +import java.util.function.Predicate; - private Predicate classAvailabilityResolver; +public class QuarkusKogitoBuildContext extends AbstractKogitoBuildContext { public QuarkusKogitoBuildContext(Predicate classAvailabilityResolver) { - this.classAvailabilityResolver = classAvailabilityResolver; - } - - @Override - public boolean hasClassAvailable(String fqcn) { - return classAvailabilityResolver.test(fqcn); + super(classAvailabilityResolver, new CDIDependencyInjectionAnnotator()); } } \ No newline at end of file diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/context/SpringBootKogitoBuildContext.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/context/SpringBootKogitoBuildContext.java index c8eff87f4b6..f96495c6f9f 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/context/SpringBootKogitoBuildContext.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/context/SpringBootKogitoBuildContext.java @@ -15,19 +15,13 @@ package org.kie.kogito.codegen.context; +import org.kie.kogito.codegen.di.SpringDependencyInjectionAnnotator; + import java.util.function.Predicate; -public class SpringBootKogitoBuildContext implements KogitoBuildContext { +public class SpringBootKogitoBuildContext extends AbstractKogitoBuildContext { - private Predicate classAvailabilityResolver; - public SpringBootKogitoBuildContext(Predicate classAvailabilityResolver) { - this.classAvailabilityResolver = classAvailabilityResolver; + super(classAvailabilityResolver, new SpringDependencyInjectionAnnotator()); } - - @Override - public boolean hasClassAvailable(String fqcn) { - return classAvailabilityResolver.test(fqcn); - } - } \ No newline at end of file diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/decision/DecisionCodegen.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/decision/DecisionCodegen.java index 8151954ba2f..f05dfb91b0c 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/decision/DecisionCodegen.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/decision/DecisionCodegen.java @@ -47,7 +47,7 @@ import org.kie.dmn.typesafe.DMNTypeSafeTypeGenerator; import org.kie.kogito.codegen.AbstractGenerator; import org.kie.kogito.codegen.ApplicationSection; -import org.kie.kogito.codegen.ConfigGenerator; +import org.kie.kogito.codegen.ApplicationConfigGenerator; import org.kie.kogito.codegen.DashboardGeneratedFileUtils; import org.kie.kogito.codegen.GeneratedFile; import org.kie.kogito.codegen.decision.config.DecisionConfigGenerator; @@ -144,10 +144,10 @@ private void generateAndStoreRestResources() { if (stronglyTypedEnabled) { generateStronglyTypedInput(model); } - DecisionRestResourceGenerator resourceGenerator = new DecisionRestResourceGenerator(model, applicationCanonicalName()).withDependencyInjection(annotator) - .withAddons(addonsConfig) - .withStronglyTyped(stronglyTypedEnabled) - .withOASResult(oasResult, isMPAnnotationsPresent(), isIOSwaggerOASv3AnnotationsPresent()); + DecisionRestResourceGenerator resourceGenerator = new DecisionRestResourceGenerator(context.getBuildContext(), model, applicationCanonicalName()) + .withAddons(addonsConfig) + .withStronglyTyped(stronglyTypedEnabled) + .withOASResult(oasResult, isMPAnnotationsPresent(), isIOSwaggerOASv3AnnotationsPresent()); rgs.add(resourceGenerator); } @@ -178,10 +178,10 @@ private void generateAndStoreRestResources() { } private void generateAndStoreDecisionModelResourcesProvider() { - final DecisionModelResourcesProviderGenerator generator = new DecisionModelResourcesProviderGenerator(packageName, + final DecisionModelResourcesProviderGenerator generator = new DecisionModelResourcesProviderGenerator(context.getBuildContext(), + packageName, applicationCanonicalName(), resources) - .withDependencyInjection(annotator) .withAddons(addonsConfig); storeFile(GeneratedFile.Type.CLASS, generator.generatedFilePath(), generator.generate()); } @@ -250,9 +250,9 @@ private void generateAndStoreGrafanaDashboards(DecisionRestResourceGenerator res } @Override - public void updateConfig(ConfigGenerator cfg) { + public void updateConfig(ApplicationConfigGenerator cfg) { if (!cResources.isEmpty()) { - cfg.withDecisionConfig(new DecisionConfigGenerator(packageName)); + cfg.withDecisionConfig(new DecisionConfigGenerator(context().getBuildContext(), packageName)); } } @@ -266,8 +266,11 @@ public List getGeneratedFiles() { @Override public ApplicationSection section() { - DecisionContainerGenerator decisionContainerGenerator = new DecisionContainerGenerator(packageName, applicationCanonicalName(), this.cResources); - decisionContainerGenerator.withDependencyInjection(annotator); + DecisionContainerGenerator decisionContainerGenerator = new DecisionContainerGenerator( + context.getBuildContext(), + packageName, + applicationCanonicalName(), + this.cResources); decisionContainerGenerator.withAddons(addonsConfig); return decisionContainerGenerator; } diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/decision/DecisionContainerGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/decision/DecisionContainerGenerator.java index 8ed120fbc9e..ef3df5ac7a8 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/decision/DecisionContainerGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/decision/DecisionContainerGenerator.java @@ -28,7 +28,7 @@ import org.kie.kogito.codegen.AddonsConfig; import org.kie.kogito.codegen.InvalidTemplateException; import org.kie.kogito.codegen.TemplatedGenerator; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; +import org.kie.kogito.codegen.context.KogitoBuildContext; import org.kie.kogito.codegen.io.CollectedResource; import org.kie.kogito.dmn.DmnExecutionIdSupplier; @@ -47,11 +47,12 @@ public class DecisionContainerGenerator extends AbstractApplicationSection { private AddonsConfig addonsConfig = AddonsConfig.DEFAULT; private final TemplatedGenerator templatedGenerator; - public DecisionContainerGenerator(String packageName, String applicationCanonicalName, List cResources) { - super(SECTION_CLASS_NAME); + public DecisionContainerGenerator(KogitoBuildContext buildContext, String packageName, String applicationCanonicalName, List cResources) { + super(buildContext, SECTION_CLASS_NAME); this.applicationCanonicalName = applicationCanonicalName; this.resources = cResources; this.templatedGenerator = new TemplatedGenerator( + buildContext, packageName, SECTION_CLASS_NAME, RESOURCE_CDI, @@ -64,18 +65,11 @@ public DecisionContainerGenerator withAddons(AddonsConfig addonsConfig) { return this; } - public DecisionContainerGenerator withDependencyInjection(DependencyInjectionAnnotator annotator) { - this.templatedGenerator.withDependencyInjection(annotator); - return this; - } - @Override public CompilationUnit compilationUnit() { - CompilationUnit compilationUnit = templatedGenerator.compilationUnit() - .orElseThrow(() -> new InvalidTemplateException( - SECTION_CLASS_NAME, - templatedGenerator.templatePath(), - "Invalid Template: No CompilationUnit")); + CompilationUnit compilationUnit = templatedGenerator.compilationUnitOrThrow("Invalid Template: No CompilationUnit"); + + ClassOrInterfaceType applicationClass = StaticJavaParser.parseClassOrInterfaceType(applicationCanonicalName); final InitializerDeclaration staticDeclaration = compilationUnit diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/decision/DecisionModelResourcesProviderGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/decision/DecisionModelResourcesProviderGenerator.java index aa995ac9394..8ccdee497fe 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/decision/DecisionModelResourcesProviderGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/decision/DecisionModelResourcesProviderGenerator.java @@ -17,7 +17,6 @@ import java.util.List; import java.util.NoSuchElementException; -import java.util.Objects; import com.github.javaparser.StaticJavaParser; import com.github.javaparser.ast.CompilationUnit; @@ -33,7 +32,7 @@ import com.github.javaparser.ast.type.ClassOrInterfaceType; import org.kie.api.management.GAV; import org.kie.kogito.codegen.AddonsConfig; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; +import org.kie.kogito.codegen.context.KogitoBuildContext; import org.kie.kogito.decision.DecisionModelType; import org.kie.kogito.dmn.DefaultDecisionModelResource; @@ -45,26 +44,23 @@ public class DecisionModelResourcesProviderGenerator { private static final String TEMPLATE_JAVA = "/class-templates/DecisionModelResourcesProviderTemplate.java"; + private final KogitoBuildContext buildContext; private final String packageName; private final String applicationCanonicalName; private final List resources; - private DependencyInjectionAnnotator annotator; private AddonsConfig addonsConfig = AddonsConfig.DEFAULT; - public DecisionModelResourcesProviderGenerator(final String packageName, + public DecisionModelResourcesProviderGenerator(final KogitoBuildContext buildContext, + final String packageName, final String applicationCanonicalName, final List resources) { + this.buildContext = buildContext; this.packageName = packageName; this.applicationCanonicalName = applicationCanonicalName; this.resources = resources; } - public DecisionModelResourcesProviderGenerator withDependencyInjection(final DependencyInjectionAnnotator annotator) { - this.annotator = annotator; - return this; - } - public DecisionModelResourcesProviderGenerator withAddons(final AddonsConfig addonsConfig) { this.addonsConfig = addonsConfig; return this; @@ -79,8 +75,8 @@ public String generate() { .findFirst(ClassOrInterfaceDeclaration.class) .orElseThrow(() -> new NoSuchElementException("Compilation unit doesn't contain a class or interface declaration!")); - if (Objects.nonNull(this.annotator)) { - annotator.withSingletonComponent(clazz); + if (buildContext.hasDI()) { + buildContext.getDependencyInjectionAnnotator().withSingletonComponent(clazz); } if (addonsConfig.useTracing()) { diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/decision/DecisionRestResourceGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/decision/DecisionRestResourceGenerator.java index e8c97b31d1c..9435392eb05 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/decision/DecisionRestResourceGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/decision/DecisionRestResourceGenerator.java @@ -15,7 +15,10 @@ package org.kie.kogito.codegen.decision; +import java.io.UncheckedIOException; +import java.io.UnsupportedEncodingException; import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.NoSuchElementException; import java.util.function.Supplier; @@ -33,7 +36,6 @@ import com.github.javaparser.ast.expr.NormalAnnotationExpr; import com.github.javaparser.ast.expr.ObjectCreationExpr; import com.github.javaparser.ast.expr.SimpleName; -import com.github.javaparser.ast.expr.SingleMemberAnnotationExpr; import com.github.javaparser.ast.expr.StringLiteralExpr; import com.github.javaparser.ast.stmt.BlockStmt; import com.github.javaparser.ast.stmt.ExpressionStmt; @@ -50,16 +52,21 @@ import org.kie.kogito.codegen.AddonsConfig; import org.kie.kogito.codegen.BodyDeclarationComparator; import org.kie.kogito.codegen.CodegenUtils; -import org.kie.kogito.codegen.InvalidTemplateException; import org.kie.kogito.codegen.TemplatedGenerator; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; +import org.kie.kogito.codegen.context.KogitoBuildContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import static com.github.javaparser.StaticJavaParser.parseStatement; public class DecisionRestResourceGenerator { - public static final String CDI_TEMPLATE = "/class-templates/DecisionRestResourceTemplate.java"; - public static final String SPRING_TEMPLATE = "/class-templates/spring/SpringDecisionRestResourceTemplate.java"; + private static final Logger LOGGER = LoggerFactory.getLogger(DecisionRestResourceGenerator.class); + + private static final String CDI_TEMPLATE = "/class-templates/DecisionRestResourceTemplate.java"; + private static final String SPRING_TEMPLATE = "/class-templates/spring/SpringDecisionRestResourceTemplate.java"; + + private final KogitoBuildContext buildContext; private final DMNModel dmnModel; private final String decisionName; private final String nameURL; @@ -68,7 +75,6 @@ public class DecisionRestResourceGenerator { private final String relativePath; private final String resourceClazzName; private final String appCanonicalName; - private DependencyInjectionAnnotator annotator; private AddonsConfig addonsConfig = AddonsConfig.DEFAULT; private boolean isStronglyTyped = false; private DMNOASResult withOASResult; @@ -78,23 +84,32 @@ public class DecisionRestResourceGenerator { private static final Supplier TEMPLATE_WAS_MODIFIED = () -> new RuntimeException("Template was modified!"); - public DecisionRestResourceGenerator(DMNModel model, String appCanonicalName) { + public DecisionRestResourceGenerator(KogitoBuildContext buildContext, DMNModel model, String appCanonicalName) { + this.buildContext = buildContext; this.dmnModel = model; this.packageName = CodegenStringUtil.escapeIdentifier(model.getNamespace()); this.decisionId = model.getDefinitions().getId(); this.decisionName = CodegenStringUtil.escapeIdentifier(model.getName()); - this.nameURL = URLEncoder.encode(model.getName()).replace("+", " "); + this.nameURL = encodeNameUrl(model.getName()); this.appCanonicalName = appCanonicalName; String classPrefix = StringUtils.ucFirst(decisionName); this.resourceClazzName = classPrefix + "Resource"; this.relativePath = packageName.replace(".", "/") + "/" + resourceClazzName + ".java"; - generator = new TemplatedGenerator(packageName, "DecisionRestResource",CDI_TEMPLATE, SPRING_TEMPLATE, CDI_TEMPLATE); + generator = new TemplatedGenerator(buildContext, packageName, "DecisionRestResource",CDI_TEMPLATE, SPRING_TEMPLATE, CDI_TEMPLATE); + } + + private String encodeNameUrl(String name) { + try { + return URLEncoder.encode(name, StandardCharsets.UTF_8.name()) + .replace("+", " "); + } catch (UnsupportedEncodingException e) { + LOGGER.warn("Error while encoding name URL " + e.toString(), e); + throw new UncheckedIOException(e); + } } public String generate() { - CompilationUnit clazz = generator.compilationUnit() - .orElseThrow(() -> new InvalidTemplateException(resourceClazzName, generator.templatePath(), "Cannot " + - "generate Decision REST Resource")); + CompilationUnit clazz = generator.compilationUnitOrThrow("Cannot generate Decision REST Resource"); ClassOrInterfaceDeclaration template = clazz .findFirst(ClassOrInterfaceDeclaration.class) @@ -111,9 +126,9 @@ public String generate() { modifyDmnMethodForStronglyTyped(template); chooseMethodForStronglyTyped(template); - if (useInjection()) { + if (buildContext.hasDI()) { template.findAll(FieldDeclaration.class, - CodegenUtils::isApplicationField).forEach(fd -> annotator.withInjection(fd)); + CodegenUtils::isApplicationField).forEach(fd -> buildContext.getDependencyInjectionAnnotator().withInjection(fd)); } else { template.findAll(FieldDeclaration.class, CodegenUtils::isApplicationField).forEach(this::initializeApplicationField); @@ -121,7 +136,10 @@ public String generate() { MethodDeclaration dmnMethod = template.findAll(MethodDeclaration.class, x -> x.getName().toString().equals("dmn")).get(0); processOASAnn(dmnMethod, null); - template.addMember(cloneForDMNResult(dmnMethod, "dmn_dmnresult", "dmnresult", "$dmnMethodUrl$")); + + final String dmnMethodUrlPlaceholder = "$dmnMethodUrl$"; + + template.addMember(cloneForDMNResult(dmnMethod, "dmn_dmnresult", "dmnresult", dmnMethodUrlPlaceholder)); for (DecisionService ds : dmnModel.getDefinitions().getDecisionService()) { if (ds.getAdditionalAttributes().keySet().stream().anyMatch(qn -> qn.getLocalPart().equals("dynamicDecisionService"))) { continue; @@ -139,7 +157,7 @@ public String generate() { //insert request path final String path = ds.getName(); - interpolateRequestPath(path, "$dmnMethodUrl$", clonedMethod); + interpolateRequestPath(path, dmnMethodUrlPlaceholder, clonedMethod); ReturnStmt returnStmt = clonedMethod.findFirst(ReturnStmt.class).orElseThrow(TEMPLATE_WAS_MODIFIED); if (ds.getOutputDecision().size() == 1) { @@ -158,7 +176,7 @@ public String generate() { } //set the root path for the dmnMethod itself - interpolateRequestPath("", "$dmnMethodUrl$", dmnMethod); + interpolateRequestPath("", dmnMethodUrlPlaceholder, dmnMethod); interpolateOutputType(template); @@ -337,12 +355,6 @@ public DMNModel getDmnModel() { return this.dmnModel; } - public DecisionRestResourceGenerator withDependencyInjection(DependencyInjectionAnnotator annotator) { - this.annotator = annotator; - this.generator.withDependencyInjection(annotator); - return this; - } - public DecisionRestResourceGenerator withAddons(AddonsConfig addonsConfig) { this.addonsConfig = addonsConfig; return this; @@ -404,10 +416,6 @@ public String generatedFilePath() { return relativePath; } - protected boolean useInjection() { - return this.annotator != null; - } - public DecisionRestResourceGenerator withStronglyTyped(boolean stronglyTyped) { this.isStronglyTyped = stronglyTyped; return this; diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/decision/config/DecisionConfigGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/decision/config/DecisionConfigGenerator.java index e318b9d36a1..d44b41daa28 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/decision/config/DecisionConfigGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/decision/config/DecisionConfigGenerator.java @@ -15,17 +15,16 @@ package org.kie.kogito.codegen.decision.config; -import org.kie.kogito.codegen.TemplatedGenerator; +import org.kie.kogito.codegen.AbstractConfigGenerator; +import org.kie.kogito.codegen.context.KogitoBuildContext; -public class DecisionConfigGenerator extends TemplatedGenerator { +public class DecisionConfigGenerator extends AbstractConfigGenerator { - private static final String RESOURCE_CDI = "/class-templates/config/CdiDecisionConfigTemplate.java"; - private static final String RESOURCE_SPRING = "/class-templates/config/SpringDecisionConfigTemplate.java"; - - public DecisionConfigGenerator(String packageName) { - super(packageName, - "DecisionConfig", - RESOURCE_CDI, - RESOURCE_SPRING); + public DecisionConfigGenerator(KogitoBuildContext buildContext, String packageName) { + super(buildContext, + packageName, + "DecisionConfig", + "/class-templates/config/CdiDecisionConfigTemplate.java", + "/class-templates/config/SpringDecisionConfigTemplate.java"); } } diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/di/SpringDependencyInjectionAnnotator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/di/SpringDependencyInjectionAnnotator.java index 58f1b1c5aaf..7f984ab4adc 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/di/SpringDependencyInjectionAnnotator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/di/SpringDependencyInjectionAnnotator.java @@ -40,7 +40,6 @@ import static com.github.javaparser.StaticJavaParser.parse; - public class SpringDependencyInjectionAnnotator implements DependencyInjectionAnnotator { @Override diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/prediction/PMMLRestResourceGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/prediction/PMMLRestResourceGenerator.java index e7580a36fbe..1565ad7dba2 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/prediction/PMMLRestResourceGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/prediction/PMMLRestResourceGenerator.java @@ -27,12 +27,10 @@ import org.kie.dmn.feel.codegen.feel11.CodegenStringUtil; import org.kie.kogito.codegen.BodyDeclarationComparator; import org.kie.kogito.codegen.CodegenUtils; -import org.kie.kogito.codegen.InvalidTemplateException; import org.kie.kogito.codegen.TemplatedGenerator; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; +import org.kie.kogito.codegen.context.KogitoBuildContext; import org.kie.pmml.commons.model.KiePMMLModel; -import static com.github.javaparser.StaticJavaParser.parse; import static org.kie.pmml.commons.utils.KiePMMLModelUtils.getSanitizedClassName; public class PMMLRestResourceGenerator { @@ -43,13 +41,14 @@ public class PMMLRestResourceGenerator { private final String nameURL; final String packageName; final String appCanonicalName; - DependencyInjectionAnnotator annotator; private final String resourceClazzName; private final String relativePath; + private final KogitoBuildContext buildContext; private final KiePMMLModel kiePMMLModel; private final TemplatedGenerator generator; - public PMMLRestResourceGenerator(KiePMMLModel model, String appCanonicalName) { + public PMMLRestResourceGenerator(KogitoBuildContext buildContext, KiePMMLModel model, String appCanonicalName) { + this.buildContext = buildContext; this.kiePMMLModel = model; this.packageName = "org.kie.kogito." + CodegenStringUtil.escapeIdentifier(model.getClass().getPackage().getName()); String classPrefix = getSanitizedClassName(model.getName()); @@ -57,13 +56,11 @@ public PMMLRestResourceGenerator(KiePMMLModel model, String appCanonicalName) { this.appCanonicalName = appCanonicalName; this.resourceClazzName = classPrefix + "Resource"; this.relativePath = packageName.replace(".", "/") + "/" + resourceClazzName + ".java"; - this.generator = new TemplatedGenerator(packageName, "DecisionRestResource",CDI_TEMPLATE, SPRING_TEMPLATE, CDI_TEMPLATE); + this.generator = new TemplatedGenerator(buildContext, packageName, "DecisionRestResource",CDI_TEMPLATE, SPRING_TEMPLATE, CDI_TEMPLATE); } public String generate() { - CompilationUnit clazz = generator.compilationUnit() - .orElseThrow(() -> new InvalidTemplateException(resourceClazzName, generator.templatePath(), "Cannot " + - "generate Prediction REST Resource")); + CompilationUnit clazz = generator.compilationUnitOrThrow("Cannot generate Prediction REST Resource"); ClassOrInterfaceDeclaration template = clazz .findFirst(ClassOrInterfaceDeclaration.class) @@ -75,9 +72,9 @@ public String generate() { setPathValue(template); setPredictionModelName(template); - if (useInjection()) { + if (buildContext.hasDI()) { template.findAll(FieldDeclaration.class, - CodegenUtils::isApplicationField).forEach(fd -> annotator.withInjection(fd)); + CodegenUtils::isApplicationField).forEach(fd -> buildContext.getDependencyInjectionAnnotator().withInjection(fd)); } else { template.findAll(FieldDeclaration.class, CodegenUtils::isApplicationField).forEach(this::initializeApplicationField); @@ -95,12 +92,6 @@ public KiePMMLModel getKiePMMLModel() { return this.kiePMMLModel; } - public PMMLRestResourceGenerator withDependencyInjection(DependencyInjectionAnnotator annotator) { - this.annotator = annotator; - this.generator.withDependencyInjection(annotator); - return this; - } - public String className() { return resourceClazzName; } @@ -109,10 +100,6 @@ public String generatedFilePath() { return relativePath; } - protected boolean useInjection() { - return this.annotator != null; - } - void setPathValue(ClassOrInterfaceDeclaration template) { template.findFirst(SingleMemberAnnotationExpr.class).orElseThrow(() -> new RuntimeException("")).setMemberValue(new StringLiteralExpr(nameURL)); } diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/prediction/PredictionCodegen.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/prediction/PredictionCodegen.java index 28ddc7e6868..5b5c9e14d05 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/prediction/PredictionCodegen.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/prediction/PredictionCodegen.java @@ -38,7 +38,7 @@ import org.kie.internal.builder.CompositeKnowledgeBuilder; import org.kie.kogito.codegen.AbstractGenerator; import org.kie.kogito.codegen.ApplicationSection; -import org.kie.kogito.codegen.ConfigGenerator; +import org.kie.kogito.codegen.ApplicationConfigGenerator; import org.kie.kogito.codegen.GeneratedFile; import org.kie.kogito.codegen.KogitoPackageSources; import org.kie.kogito.codegen.io.CollectedResource; @@ -96,16 +96,15 @@ private static List parsePredictions(Path path, List res } @Override - public void updateConfig(ConfigGenerator cfg) { + public void updateConfig(ApplicationConfigGenerator cfg) { if (!resources.isEmpty()) { - cfg.withPredictionConfig(new PredictionConfigGenerator(packageName)); + cfg.withPredictionConfig(new PredictionConfigGenerator(context().getBuildContext(), packageName)); } } @Override public ApplicationSection section() { - PredictionModelsGenerator moduleGenerator = new PredictionModelsGenerator(packageName, applicationCanonicalName(), resources); - moduleGenerator.withDependencyInjection(annotator); + PredictionModelsGenerator moduleGenerator = new PredictionModelsGenerator(context.getBuildContext(), packageName, applicationCanonicalName(), resources); moduleGenerator.withAddons(addonsConfig); return moduleGenerator; } @@ -155,9 +154,7 @@ private void addModels(final List kiepmmlModels, final PMMLResourc batch.add( new DescrResource( packageDescr ), ResourceType.DESCR ); } if (!(model instanceof KiePMMLFactoryModel)) { - PMMLRestResourceGenerator resourceGenerator = new PMMLRestResourceGenerator(model, - applicationCanonicalName()) - .withDependencyInjection(annotator); + PMMLRestResourceGenerator resourceGenerator = new PMMLRestResourceGenerator(context.getBuildContext(), model, applicationCanonicalName()); storeFile(GeneratedFile.Type.PMML, resourceGenerator.generatedFilePath(), resourceGenerator.generate()); } if (model instanceof HasNestedModels) { diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/prediction/PredictionModelsGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/prediction/PredictionModelsGenerator.java index 778a345a0a1..f3bf4fa7440 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/prediction/PredictionModelsGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/prediction/PredictionModelsGenerator.java @@ -23,7 +23,7 @@ import org.kie.kogito.codegen.AddonsConfig; import org.kie.kogito.codegen.InvalidTemplateException; import org.kie.kogito.codegen.TemplatedGenerator; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; +import org.kie.kogito.codegen.context.KogitoBuildContext; import java.util.List; @@ -39,12 +39,13 @@ public class PredictionModelsGenerator extends AbstractApplicationSection { protected AddonsConfig addonsConfig = AddonsConfig.DEFAULT; protected final TemplatedGenerator templatedGenerator; - public PredictionModelsGenerator(String packageName, String applicationCanonicalName, List resources) { - super(SECTION_CLASS_NAME); + public PredictionModelsGenerator(KogitoBuildContext buildContext, String packageName, String applicationCanonicalName, List resources) { + super(buildContext, SECTION_CLASS_NAME); this.applicationCanonicalName = applicationCanonicalName; this.resources = resources; this.templatedGenerator = new TemplatedGenerator( + buildContext, packageName, SECTION_CLASS_NAME, RESOURCE_CDI, @@ -57,18 +58,9 @@ public PredictionModelsGenerator withAddons(AddonsConfig addonsConfig) { return this; } - public PredictionModelsGenerator withDependencyInjection(DependencyInjectionAnnotator annotator) { - this.templatedGenerator.withDependencyInjection(annotator); - return this; - } - @Override public CompilationUnit compilationUnit() { - CompilationUnit compilationUnit = templatedGenerator.compilationUnit() - .orElseThrow(() -> new InvalidTemplateException( - SECTION_CLASS_NAME, - templatedGenerator.templatePath(), - "Invalid Template: No CompilationUnit")); + CompilationUnit compilationUnit = templatedGenerator.compilationUnitOrThrow("Invalid Template: No CompilationUnit"); populateStaticKieRuntimeFactoryFunctionInit(compilationUnit); return compilationUnit; } diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/prediction/config/PredictionConfigGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/prediction/config/PredictionConfigGenerator.java index c343fe38a76..a798a729aff 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/prediction/config/PredictionConfigGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/prediction/config/PredictionConfigGenerator.java @@ -15,34 +15,26 @@ package org.kie.kogito.codegen.prediction.config; +import com.github.javaparser.ast.body.BodyDeclaration; +import org.kie.kogito.codegen.AbstractConfigGenerator; +import org.kie.kogito.codegen.context.KogitoBuildContext; + import java.util.ArrayList; import java.util.List; -import com.github.javaparser.ast.body.BodyDeclaration; -import com.github.javaparser.ast.expr.ObjectCreationExpr; -import org.kie.kogito.codegen.TemplatedGenerator; -import org.kie.kogito.pmml.config.StaticPredictionConfig; - -public class PredictionConfigGenerator extends TemplatedGenerator { +public class PredictionConfigGenerator extends AbstractConfigGenerator { private List> members = new ArrayList<>(); - private static final String RESOURCE_CDI = "/class-templates/config/CdiPredictionConfigTemplate.java"; - private static final String RESOURCE_SPRING = "/class-templates/config/SpringPredictionConfigTemplate.java"; - - public PredictionConfigGenerator(String packageName) { - super(packageName, - "PredictionConfig", - RESOURCE_CDI, - RESOURCE_SPRING); - } - - public ObjectCreationExpr newInstance() { - return new ObjectCreationExpr().setType(StaticPredictionConfig.class.getCanonicalName()); + public PredictionConfigGenerator(KogitoBuildContext buildContext, String packageName) { + super(buildContext, + packageName, + "PredictionConfig", + "/class-templates/config/CdiPredictionConfigTemplate.java", + "/class-templates/config/SpringPredictionConfigTemplate.java"); } public List> members() { - return members; } diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/AbstractResourceGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/AbstractResourceGenerator.java index fe3a7ebd096..e79814e399a 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/AbstractResourceGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/AbstractResourceGenerator.java @@ -37,7 +37,6 @@ import org.kie.kogito.codegen.CodegenUtils; import org.kie.kogito.codegen.GeneratorContext; import org.kie.kogito.codegen.context.KogitoBuildContext; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; import java.util.HashMap; import java.util.List; @@ -67,7 +66,6 @@ public abstract class AbstractResourceGenerator { private String processId; private String dataClazzName; private String modelfqcn; - private DependencyInjectionAnnotator annotator; private boolean startable; private boolean dynamic; @@ -93,11 +91,6 @@ public AbstractResourceGenerator( this.processClazzName = processfqcn; } - public AbstractResourceGenerator withDependencyInjection(DependencyInjectionAnnotator annotator) { - this.annotator = annotator; - return this; - } - public AbstractResourceGenerator withUserTasks(List userTasks) { this.userTasks = userTasks; return this; @@ -230,12 +223,14 @@ public String generate() { template.findAll(ClassOrInterfaceType.class).forEach(cls -> interpolateTypes(cls, typeInterpolations)); template.findAll(MethodDeclaration.class).forEach(this::interpolateMethods); - if (useInjection()) { + KogitoBuildContext buildContext = context.getBuildContext(); + + if (buildContext.hasDI()) { template.findAll(FieldDeclaration.class, - CodegenUtils::isProcessField).forEach(fd -> annotator.withNamedInjection(fd, processId)); + CodegenUtils::isProcessField).forEach(fd -> buildContext.getDependencyInjectionAnnotator().withNamedInjection(fd, processId)); template.findAll(FieldDeclaration.class, - CodegenUtils::isApplicationField).forEach(fd -> annotator.withInjection(fd)); + CodegenUtils::isApplicationField).forEach(fd -> buildContext.getDependencyInjectionAnnotator().withInjection(fd)); } else { template.findAll(FieldDeclaration.class, CodegenUtils::isProcessField).forEach(this::initializeProcessField); @@ -250,8 +245,8 @@ public String generate() { createResourceMethod.ifPresent(template::remove); } - if (useInjection()) { - annotator.withApplicationComponent(template); + if (buildContext.hasDI()) { + buildContext.getDependencyInjectionAnnotator().withApplicationComponent(template); } enableValidation(template); @@ -265,9 +260,11 @@ public String generate() { public abstract String getUserTaskResourceTemplate(); private void securityAnnotated(ClassOrInterfaceDeclaration template) { - if (useInjection() && process.getMetaData().containsKey("securityRoles")) { + KogitoBuildContext buildContext = context.getBuildContext(); + if (buildContext.hasDI() && process.getMetaData().containsKey("securityRoles")) { String[] roles = ((String) process.getMetaData().get("securityRoles")).split(","); - template.findAll(MethodDeclaration.class).stream().filter(this::requiresSecurity).forEach(md -> annotator.withSecurityRoles(md, roles)); + template.findAll(MethodDeclaration.class).stream().filter(this::requiresSecurity) + .forEach(md -> buildContext.getDependencyInjectionAnnotator().withSecurityRoles(md, roles)); } } @@ -365,10 +362,6 @@ public String generatedFilePath() { return relativePath; } - protected boolean useInjection() { - return this.annotator != null; - } - protected boolean isPublic() { return WorkflowProcess.PUBLIC_VISIBILITY.equalsIgnoreCase(process.getVisibility()); } diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/MessageConsumerGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/MessageConsumerGenerator.java index 69a621f5627..3206b4a26d2 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/MessageConsumerGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/MessageConsumerGenerator.java @@ -28,9 +28,8 @@ import org.jbpm.compiler.canonical.TriggerMetaData; import org.kie.api.definition.process.WorkflowProcess; import org.kie.kogito.codegen.BodyDeclarationComparator; -import org.kie.kogito.codegen.InvalidTemplateException; import org.kie.kogito.codegen.TemplatedGenerator; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; +import org.kie.kogito.codegen.context.KogitoBuildContext; import static org.kie.kogito.codegen.CodegenUtils.interpolateTypes; import static org.kie.kogito.codegen.CodegenUtils.isApplicationField; @@ -46,6 +45,7 @@ public class MessageConsumerGenerator { private static final String OBJECT_MAPPER_CANONICAL_NAME = ObjectMapper.class.getCanonicalName(); private final TemplatedGenerator generator; + private KogitoBuildContext buildContext; private WorkflowProcess process; private final String packageName; private final String resourceClazzName; @@ -55,17 +55,18 @@ public class MessageConsumerGenerator { private final String processName; private final String appCanonicalName; private final String messageDataEventClassName; - private DependencyInjectionAnnotator annotator; private TriggerMetaData trigger; public MessageConsumerGenerator( + KogitoBuildContext buildContext, WorkflowProcess process, String modelfqcn, String processfqcn, String appCanonicalName, String messageDataEventClassName, TriggerMetaData trigger) { + this.buildContext = buildContext; this.process = process; this.trigger = trigger; this.packageName = process.getPackageName(); @@ -79,6 +80,7 @@ public MessageConsumerGenerator( this.messageDataEventClassName = messageDataEventClassName; this.generator = new TemplatedGenerator( + buildContext, packageName, resourceClazzName, RESOURCE_CDI, @@ -86,12 +88,6 @@ public MessageConsumerGenerator( RESOURCE); } - public MessageConsumerGenerator withDependencyInjection(DependencyInjectionAnnotator annotator) { - this.annotator = annotator; - this.generator.withDependencyInjection(annotator); - return this; - } - public String className() { return resourceClazzName; } @@ -100,13 +96,8 @@ public String generatedFilePath() { return generator.generatedFilePath(); } - protected boolean useInjection() { - return this.annotator != null; - } - public String generate() { - CompilationUnit clazz = generator.compilationUnit() - .orElseThrow(() -> new InvalidTemplateException(resourceClazzName, generator.templatePath(), "Cannot generate message consumer")); + CompilationUnit clazz = generator.compilationUnitOrThrow("Cannot generate message consumer"); clazz.setPackageDeclaration(process.getPackageName()); ClassOrInterfaceDeclaration template = clazz.findFirst(ClassOrInterfaceDeclaration.class).get(); @@ -121,7 +112,7 @@ public String generate() { template.findAll(MethodCallExpr.class).forEach(this::interpolateStrings); // legacy: force initialize fields - if (!useInjection()) { + if (!buildContext.hasDI()) { template.findAll(FieldDeclaration.class, fd -> isProcessField(fd)).forEach(fd -> initializeProcessField(fd)); template.findAll(FieldDeclaration.class, diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/MessageDataEventGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/MessageDataEventGenerator.java index 098179c2110..d3f0d29b5e1 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/MessageDataEventGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/MessageDataEventGenerator.java @@ -24,7 +24,6 @@ import org.jbpm.compiler.canonical.TriggerMetaData; import org.kie.api.definition.process.WorkflowProcess; import org.kie.kogito.codegen.BodyDeclarationComparator; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; import static com.github.javaparser.StaticJavaParser.parse; import static org.kie.kogito.codegen.CodegenUtils.interpolateTypes; @@ -37,7 +36,6 @@ public class MessageDataEventGenerator { private final String resourceClazzName; private String processId; private final String processName; - private DependencyInjectionAnnotator annotator; private TriggerMetaData trigger; @@ -54,11 +52,6 @@ public MessageDataEventGenerator( this.relativePath = packageName.replace(".", "/") + "/" + resourceClazzName + ".java"; } - public MessageDataEventGenerator withDependencyInjection(DependencyInjectionAnnotator annotator) { - this.annotator = annotator; - return this; - } - public String className() { return resourceClazzName; } @@ -66,11 +59,7 @@ public String className() { public String generatedFilePath() { return relativePath; } - - protected boolean useInjection() { - return this.annotator != null; - } - + public String generate() { CompilationUnit clazz = parse( this.getClass().getResourceAsStream("/class-templates/MessageDataEventTemplate.java")); diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/MessageProducerGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/MessageProducerGenerator.java index bf3a11707f3..018cafbe4c7 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/MessageProducerGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/MessageProducerGenerator.java @@ -24,9 +24,8 @@ import org.jbpm.compiler.canonical.TriggerMetaData; import org.kie.api.definition.process.WorkflowProcess; import org.kie.kogito.codegen.BodyDeclarationComparator; -import org.kie.kogito.codegen.InvalidTemplateException; import org.kie.kogito.codegen.TemplatedGenerator; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; +import org.kie.kogito.codegen.context.KogitoBuildContext; import static org.kie.kogito.codegen.CodegenUtils.interpolateTypes; @@ -43,18 +42,20 @@ public class MessageProducerGenerator { protected final String resourceClazzName; private final String processName; protected final String messageDataEventClassName; + protected final KogitoBuildContext buildContext; protected WorkflowProcess process; private String processId; - protected DependencyInjectionAnnotator annotator; protected TriggerMetaData trigger; public MessageProducerGenerator( + KogitoBuildContext buildContext, WorkflowProcess process, String modelfqcn, String processfqcn, String messageDataEventClassName, TriggerMetaData trigger) { + this.buildContext = buildContext; this.process = process; this.trigger = trigger; this.packageName = process.getPackageName(); @@ -65,6 +66,7 @@ public MessageProducerGenerator( this.messageDataEventClassName = messageDataEventClassName; this.generator = new TemplatedGenerator( + buildContext, packageName, resourceClazzName, RESOURCE_CDI, @@ -72,15 +74,8 @@ public MessageProducerGenerator( RESOURCE); } - public MessageProducerGenerator withDependencyInjection(DependencyInjectionAnnotator annotator) { - this.annotator = annotator; - generator.withDependencyInjection(annotator); - return this; - } - public String generate() { - CompilationUnit clazz = generator.compilationUnit() - .orElseThrow(() -> new InvalidTemplateException(resourceClazzName, generator.templatePath(), "Cannot generate message producer")); + CompilationUnit clazz = generator.compilationUnitOrThrow("Cannot generate message producer"); clazz.setPackageDeclaration(process.getPackageName()); ClassOrInterfaceDeclaration template = clazz.findFirst(ClassOrInterfaceDeclaration.class).get(); @@ -104,8 +99,4 @@ public String className() { public String generatedFilePath() { return generator.generatedFilePath(); } - - protected boolean useInjection() { - return this.annotator != null; - } } diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/ProcessCodegen.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/ProcessCodegen.java index c680565a11c..01351b17bec 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/ProcessCodegen.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/ProcessCodegen.java @@ -47,7 +47,7 @@ import org.kie.api.io.Resource; import org.kie.kogito.codegen.AbstractGenerator; import org.kie.kogito.codegen.ApplicationSection; -import org.kie.kogito.codegen.ConfigGenerator; +import org.kie.kogito.codegen.ApplicationConfigGenerator; import org.kie.kogito.codegen.GeneratedFile; import org.kie.kogito.codegen.GeneratedFile.Type; import org.kie.kogito.codegen.ResourceGeneratorFactory; @@ -267,13 +267,13 @@ public Set generate() { processIdToModelGenerator.get(execModelGen.getProcessId()); ProcessGenerator p = new ProcessGenerator( + context.getBuildContext(), workFlowProcess, execModelGen, classPrefix, modelClassGenerator.className(), applicationCanonicalName() ) - .withDependencyInjection(annotator) .withAddons(addonsConfig); ProcessInstanceGenerator pi = new ProcessInstanceGenerator( @@ -290,7 +290,6 @@ public Set generate() { execModelGen.className(), applicationCanonicalName()) .map(r -> r - .withDependencyInjection(annotator) .withUserTasks(processIdToUserTaskModel.get(workFlowProcess.getId())) .withSignals(metaData.getSignals()) .withTriggers(metaData.isStartable(), metaData.isDynamic())) @@ -304,23 +303,21 @@ public Set generate() { if (trigger.getType().equals(TriggerMetaData.TriggerType.ConsumeMessage)) { MessageDataEventGenerator msgDataEventGenerator = new MessageDataEventGenerator(workFlowProcess, - trigger) - .withDependencyInjection(annotator); + trigger); mdegs.add(msgDataEventGenerator); megs.add(new MessageConsumerGenerator( + context.getBuildContext(), workFlowProcess, modelClassGenerator.className(), execModelGen.className(), applicationCanonicalName(), msgDataEventGenerator.className(), - trigger) - .withDependencyInjection(annotator)); + trigger)); } else if (trigger.getType().equals(TriggerMetaData.TriggerType.ProduceMessage)) { MessageDataEventGenerator msgDataEventGenerator = new MessageDataEventGenerator(workFlowProcess, - trigger) - .withDependencyInjection(annotator); + trigger); mdegs.add(msgDataEventGenerator); // this is not cool, we should have a way to process addons @@ -328,20 +325,20 @@ public Set generate() { // see: https://issues.redhat.com/browse/KOGITO-1767 if (addonsConfig.useKnativeEventing()) { mpgs.add(new CloudEventsMessageProducerGenerator( + context.getBuildContext(), workFlowProcess, modelClassGenerator.className(), execModelGen.className(), msgDataEventGenerator.className(), - trigger) - .withDependencyInjection(annotator)); + trigger)); } else { mpgs.add(new MessageProducerGenerator( + context.getBuildContext(), workFlowProcess, modelClassGenerator.className(), execModelGen.className(), msgDataEventGenerator.className(), - trigger) - .withDependencyInjection(annotator)); + trigger)); } } } @@ -414,12 +411,12 @@ public Set generate() { if (this.addonsConfig.useKnativeEventing()) { LOGGER.info("Knative Eventing addon enabled, generating CloudEvent HTTP listener"); final CloudEventsResourceGenerator ceGenerator = - new CloudEventsResourceGenerator(packageName, processExecutableModelGenerators, annotator); + new CloudEventsResourceGenerator(context.getBuildContext(), packageName, processExecutableModelGenerators); storeFile(Type.REST, ceGenerator.generatedFilePath(), ceGenerator.generate()); } final TopicsInformationResourceGenerator topicsGenerator = - new TopicsInformationResourceGenerator(packageName, processExecutableModelGenerators, annotator, addonsConfig); + new TopicsInformationResourceGenerator(context.getBuildContext(), packageName, processExecutableModelGenerators, addonsConfig); storeFile(Type.REST, topicsGenerator.generatedFilePath(), topicsGenerator.generate()); @@ -438,9 +435,9 @@ public Set generate() { } @Override - public void updateConfig(ConfigGenerator cfg) { + public void updateConfig(ApplicationConfigGenerator cfg) { if (!processes.isEmpty()) { - cfg.withProcessConfig(new ProcessConfigGenerator(packageName)); + cfg.withProcessConfig(new ProcessConfigGenerator(context().getBuildContext(), packageName)); } } @@ -458,8 +455,7 @@ public Set getGeneratedFiles() { @Override public ApplicationSection section() { - ProcessContainerGenerator moduleGenerator = new ProcessContainerGenerator(packageName); - moduleGenerator.withDependencyInjection(annotator); + ProcessContainerGenerator moduleGenerator = new ProcessContainerGenerator(context.getBuildContext(), packageName); processGenerators.forEach(moduleGenerator::addProcess); return moduleGenerator; } diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/ProcessContainerGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/ProcessContainerGenerator.java index a2842a4a353..58c14554738 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/ProcessContainerGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/ProcessContainerGenerator.java @@ -39,7 +39,7 @@ import org.kie.kogito.codegen.AbstractApplicationSection; import org.kie.kogito.codegen.InvalidTemplateException; import org.kie.kogito.codegen.TemplatedGenerator; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; +import org.kie.kogito.codegen.context.KogitoBuildContext; import static com.github.javaparser.ast.NodeList.nodeList; @@ -54,19 +54,18 @@ public class ProcessContainerGenerator extends AbstractApplicationSection { private final List processes; private final List> factoryMethods; - private DependencyInjectionAnnotator annotator; - private BlockStmt byProcessIdBody = new BlockStmt(); private BlockStmt processesBody = new BlockStmt(); private final TemplatedGenerator templatedGenerator; - public ProcessContainerGenerator(String packageName) { - super(SECTION_CLASS_NAME); + public ProcessContainerGenerator(KogitoBuildContext buildContext, String packageName) { + super(buildContext, SECTION_CLASS_NAME); this.packageName = packageName; this.processes = new ArrayList<>(); this.factoryMethods = new ArrayList<>(); this.templatedGenerator = new TemplatedGenerator( + buildContext, packageName, SECTION_CLASS_NAME, RESOURCE_CDI, @@ -94,16 +93,9 @@ public void addProcessToApplication(ProcessGenerator r) { byProcessIdBody.addStatement(byProcessId); } - public ProcessContainerGenerator withDependencyInjection(DependencyInjectionAnnotator annotator) { - this.annotator = annotator; - this.templatedGenerator.withDependencyInjection(annotator); - return this; - } - @Override public CompilationUnit compilationUnit() { - CompilationUnit compilationUnit = templatedGenerator.compilationUnit() - .orElseThrow(() -> new IllegalArgumentException("Invalid Template: No CompilationUnit")); + CompilationUnit compilationUnit = templatedGenerator.compilationUnitOrThrow("Invalid Template: No CompilationUnit"); registerProcessesExplicitly(compilationUnit); return compilationUnit; @@ -111,7 +103,7 @@ public CompilationUnit compilationUnit() { private void registerProcessesExplicitly(CompilationUnit compilationUnit) { // only for non-DI cases - if (annotator == null) { + if (!buildContext.hasDI()) { setupProcessById(compilationUnit); setupProcessIds(compilationUnit); } diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/ProcessGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/ProcessGenerator.java index 0639a3e484e..2b6b4faf00c 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/ProcessGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/ProcessGenerator.java @@ -63,7 +63,7 @@ import org.kie.kogito.Model; import org.kie.kogito.codegen.AddonsConfig; import org.kie.kogito.codegen.BodyDeclarationComparator; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; +import org.kie.kogito.codegen.context.KogitoBuildContext; import org.kie.kogito.process.ProcessInstancesFactory; import org.kie.kogito.process.Processes; import org.kie.kogito.process.impl.AbstractProcess; @@ -92,18 +92,20 @@ public class ProcessGenerator { private final String generatedFilePath; private final String completePath; private final String targetCanonicalName; + private final KogitoBuildContext buildContext; private final String appCanonicalName; private String targetTypeName; - private DependencyInjectionAnnotator annotator; private AddonsConfig addonsConfig = AddonsConfig.DEFAULT; private List additionalClasses = new ArrayList<>(); - public ProcessGenerator(WorkflowProcess process, + public ProcessGenerator(KogitoBuildContext buildContext, + WorkflowProcess process, ProcessExecutableModelGenerator processGenerator, String typeName, String modelTypeName, String appCanonicalName) { + this.buildContext = buildContext; this.appCanonicalName = appCanonicalName; @@ -357,10 +359,10 @@ public ClassOrInterfaceDeclaration classDeclaration() { .addStatement(superMethod) .addStatement(new MethodCallExpr("activate"))); - if (useInjection()) { - annotator.withNamedApplicationComponent(cls, process.getId()); - annotator.withEagerStartup(cls); - annotator.withInjection(constructor); + if (buildContext.hasDI()) { + buildContext.getDependencyInjectionAnnotator().withNamedApplicationComponent(cls, process.getId()); + buildContext.getDependencyInjectionAnnotator().withEagerStartup(cls); + buildContext.getDependencyInjectionAnnotator().withInjection(constructor); } Map handlers = processMetaData.getGeneratedHandlers(); @@ -394,9 +396,9 @@ public ClassOrInterfaceDeclaration classDeclaration() { ClassOrInterfaceType clazzNameType = parseClassOrInterfaceType(clazzName); Parameter parameter = new Parameter(clazzNameType, varName); - if (useInjection()) { - annotator.withApplicationComponent(handlerClazz); - annotator + if (buildContext.hasDI()) { + buildContext.getDependencyInjectionAnnotator().withApplicationComponent(handlerClazz); + buildContext.getDependencyInjectionAnnotator() .withInjection( handlerClazz .getConstructors() @@ -453,10 +455,10 @@ public ClassOrInterfaceDeclaration classDeclaration() { String fieldName = "process" + subProcess.getKey(); ClassOrInterfaceType modelType = new ClassOrInterfaceType(null, new SimpleName(org.kie.kogito.process.Process.class.getCanonicalName()), NodeList.nodeList(new ClassOrInterfaceType(null, StringUtils.ucFirst(subProcess.getKey() + "Model")))); - if (useInjection()) { + if (buildContext.hasDI()) { subprocessFieldDeclaration .addVariable(new VariableDeclarator(modelType, fieldName)); - annotator.withInjection(subprocessFieldDeclaration); + buildContext.getDependencyInjectionAnnotator().withInjection(subprocessFieldDeclaration); } else { // app.get(org.kie.kogito.process.Processes.class).processById() MethodCallExpr initSubProcessField = new MethodCallExpr( @@ -485,8 +487,8 @@ public ClassOrInterfaceDeclaration classDeclaration() { .addVariable(new VariableDeclarator(new ClassOrInterfaceType(null, producerFieldType), producerFielName)); cls.addMember(producerFieldieldDeclaration); - if (useInjection()) { - annotator.withInjection(producerFieldieldDeclaration); + if (buildContext.hasDI()) { + buildContext.getDependencyInjectionAnnotator().withInjection(producerFieldieldDeclaration); } else { AssignExpr assignExpr = new AssignExpr( @@ -526,18 +528,9 @@ public String processId() { public List getAdditionalClasses() { return additionalClasses; } - - public ProcessGenerator withDependencyInjection(DependencyInjectionAnnotator annotator) { - this.annotator = annotator; - return this; - } public ProcessGenerator withAddons(AddonsConfig addonsConfig) { this.addonsConfig = addonsConfig; return this; } - - protected boolean useInjection() { - return this.annotator != null; - } } diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/config/ProcessConfigGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/config/ProcessConfigGenerator.java index 3dd66d7b7b1..fc7cb392357 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/config/ProcessConfigGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/config/ProcessConfigGenerator.java @@ -15,17 +15,16 @@ package org.kie.kogito.codegen.process.config; -import org.kie.kogito.codegen.TemplatedGenerator; +import org.kie.kogito.codegen.AbstractConfigGenerator; +import org.kie.kogito.codegen.context.KogitoBuildContext; -public class ProcessConfigGenerator extends TemplatedGenerator { +public class ProcessConfigGenerator extends AbstractConfigGenerator { - private static final String RESOURCE_CDI = "/class-templates/config/CdiProcessConfigTemplate.java"; - private static final String RESOURCE_SPRING = "/class-templates/config/SpringProcessConfigTemplate.java"; - - public ProcessConfigGenerator(String packageName) { - super(packageName, - "ProcessConfig", - RESOURCE_CDI, - RESOURCE_SPRING); + public ProcessConfigGenerator(KogitoBuildContext buildContext, String packageName) { + super(buildContext, + packageName, + "ProcessConfig", + "/class-templates/config/CdiProcessConfigTemplate.java", + "/class-templates/config/SpringProcessConfigTemplate.java"); } } diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/events/CloudEventsMessageProducerGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/events/CloudEventsMessageProducerGenerator.java index 9ea67532fa7..d1ac289641c 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/events/CloudEventsMessageProducerGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/events/CloudEventsMessageProducerGenerator.java @@ -30,6 +30,7 @@ import org.kie.api.definition.process.WorkflowProcess; import org.kie.kogito.codegen.BodyDeclarationComparator; import org.kie.kogito.codegen.TemplateInstantiationException; +import org.kie.kogito.codegen.context.KogitoBuildContext; import org.kie.kogito.codegen.process.MessageProducerGenerator; import static com.github.javaparser.StaticJavaParser.parse; @@ -41,8 +42,13 @@ @Deprecated public class CloudEventsMessageProducerGenerator extends MessageProducerGenerator { - public CloudEventsMessageProducerGenerator(WorkflowProcess process, String modelfqcn, String processfqcn, String messageDataEventClassName, TriggerMetaData trigger) { - super(process, modelfqcn, processfqcn, messageDataEventClassName, trigger); + public CloudEventsMessageProducerGenerator(KogitoBuildContext buildContext, + WorkflowProcess process, + String modelfqcn, + String processfqcn, + String messageDataEventClassName, + TriggerMetaData trigger) { + super(buildContext, process, modelfqcn, processfqcn, messageDataEventClassName, trigger); } public String generate() { @@ -66,22 +72,22 @@ public String generate() { md.findAll(ClassOrInterfaceType.class).forEach(t -> t.setName(t.getNameAsString().replace("$DataEventType$", messageDataEventClassName))); }); - if (useInjection()) { - annotator.withApplicationComponent(template); + if (buildContext.hasDI()) { + buildContext.getDependencyInjectionAnnotator().withApplicationComponent(template); FieldDeclaration emitterField = template.findFirst(FieldDeclaration.class) .filter(fd -> fd.getVariables().stream().anyMatch(v -> v.getNameAsString().equals("emitter"))) .orElseThrow(() -> new IllegalStateException("Cannot find emitter field in MessageProducerTemplate")); - annotator.withInjection(emitterField); - annotator.withOutgoingMessage(emitterField, trigger.getName()); - emitterField.getVariable(0).setType(annotator.emitterType("String")); + buildContext.getDependencyInjectionAnnotator().withInjection(emitterField); + buildContext.getDependencyInjectionAnnotator().withOutgoingMessage(emitterField, trigger.getName()); + emitterField.getVariable(0).setType(buildContext.getDependencyInjectionAnnotator().emitterType("String")); MethodDeclaration produceMethod = template.findAll(MethodDeclaration.class).stream() .filter(md -> md.getNameAsString().equals("produce")) .findFirst().orElseThrow(() -> new IllegalStateException("Cannot find produce methods in MessageProducerTemplate")); MethodCallExpr sendMethodCall = new MethodCallExpr(new NameExpr("emitter"), "send"); - annotator.withMessageProducer( + buildContext.getDependencyInjectionAnnotator().withMessageProducer( sendMethodCall, trigger.getName(), new MethodCallExpr(new ThisExpr(), "marshall") @@ -91,7 +97,8 @@ public String generate() { this.generateProduceMethodBody(produceMethod, sendMethodCall); template.findAll(FieldDeclaration.class, - fd -> fd.getVariable(0).getNameAsString().equals("useCloudEvents")).forEach(fd -> annotator.withConfigInjection(fd, "kogito.messaging.as-cloudevents")); + fd -> fd.getVariable(0).getNameAsString().equals("useCloudEvents")) + .forEach(fd -> buildContext.getDependencyInjectionAnnotator().withConfigInjection(fd, "kogito.messaging.as-cloudevents")); } template.getMembers().sort(new BodyDeclarationComparator()); diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/events/CloudEventsResourceGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/events/CloudEventsResourceGenerator.java index 4fcb34347d2..6eb9d08c173 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/events/CloudEventsResourceGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/events/CloudEventsResourceGenerator.java @@ -25,12 +25,9 @@ import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; import com.github.javaparser.ast.body.FieldDeclaration; import org.jbpm.compiler.canonical.TriggerMetaData; -import org.kie.kogito.codegen.ApplicationGenerator; import org.kie.kogito.codegen.BodyDeclarationComparator; -import org.kie.kogito.codegen.InvalidTemplateException; import org.kie.kogito.codegen.TemplatedGenerator; -import org.kie.kogito.codegen.di.CDIDependencyInjectionAnnotator; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; +import org.kie.kogito.codegen.context.KogitoBuildContext; import org.kie.kogito.codegen.process.ProcessExecutableModelGenerator; public class CloudEventsResourceGenerator extends AbstractEventResourceGenerator { @@ -39,16 +36,21 @@ public class CloudEventsResourceGenerator extends AbstractEventResourceGenerator private static final String CDI_TEMPLATE = "/class-templates/events/CloudEventsListenerResource.java"; private static final String CLASS_NAME = "CloudEventListenerResource"; - // even if we only support Quarkus for now, this will come in handy when we add SpringBoot support. - private final DependencyInjectionAnnotator annotator; + private final KogitoBuildContext buildContext; private final List triggers; - public CloudEventsResourceGenerator(final String packageName, final List generators, final DependencyInjectionAnnotator annotator) { - super(new TemplatedGenerator(packageName, CLASS_NAME, CDI_TEMPLATE, - null, CDI_TEMPLATE) - .withDependencyInjection(annotator)); + public CloudEventsResourceGenerator(final KogitoBuildContext buildContext, + final String packageName, + final List generators) { + super(new TemplatedGenerator( + buildContext, + packageName, + CLASS_NAME, + CDI_TEMPLATE, + null, + CDI_TEMPLATE)); + this.buildContext = buildContext; this.triggers = this.filterTriggers(generators); - this.annotator = annotator; } /** @@ -66,9 +68,7 @@ List getTriggers() { * @return */ public String generate() { - final CompilationUnit clazz = generator.compilationUnit() - .orElseThrow(() -> new InvalidTemplateException(CLASS_NAME, generator.templatePath(), - "Cannot generate CloudEvents REST Resource")); + final CompilationUnit clazz = generator.compilationUnitOrThrow("Cannot generate CloudEvents REST Resource"); final ClassOrInterfaceDeclaration template = clazz .findFirst(ClassOrInterfaceDeclaration.class) .orElseThrow(() -> new NoSuchElementException("Compilation unit doesn't contain a class or interface declaration!")); @@ -98,9 +98,11 @@ private List filterTriggers(final List fd.getVariables().get(0).getNameAsString().contains(EMITTER_PREFIX)) - .forEach(annotator::withInjection); + if(buildContext.hasDI()) { + buildContext.getDependencyInjectionAnnotator().withApplicationComponent(template); + template.findAll(FieldDeclaration.class, fd -> fd.getVariables().get(0).getNameAsString().contains(EMITTER_PREFIX)) + .forEach(buildContext.getDependencyInjectionAnnotator()::withInjection); + } } String sanitizeEmitterName(String triggerName) { diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/events/TopicsInformationResourceGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/events/TopicsInformationResourceGenerator.java index 8387a86c7bc..70159431fa1 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/events/TopicsInformationResourceGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/events/TopicsInformationResourceGenerator.java @@ -31,9 +31,8 @@ import org.jbpm.compiler.canonical.TriggerMetaData; import org.kie.kogito.codegen.AddonsConfig; import org.kie.kogito.codegen.BodyDeclarationComparator; -import org.kie.kogito.codegen.InvalidTemplateException; import org.kie.kogito.codegen.TemplatedGenerator; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; +import org.kie.kogito.codegen.context.KogitoBuildContext; import org.kie.kogito.codegen.process.ProcessExecutableModelGenerator; import org.kie.kogito.event.EventKind; import org.kie.kogito.services.event.DataEventAttrBuilder; @@ -44,19 +43,18 @@ public class TopicsInformationResourceGenerator extends AbstractEventResourceGen private static final String SPRING_TEMPLATE = "/class-templates/events/SpringTopicsInformationResourceTemplate.java"; private static final String CLASS_NAME = "TopicsInformationResource"; - private final DependencyInjectionAnnotator annotator; + private final KogitoBuildContext buildContext; private final Map> triggers; private final AddonsConfig addonsConfig; - public TopicsInformationResourceGenerator(final String packageName, + public TopicsInformationResourceGenerator(final KogitoBuildContext buildContext, + final String packageName, final List generators, - final DependencyInjectionAnnotator annotator, final AddonsConfig addonsConfig) { - super(new TemplatedGenerator(packageName, CLASS_NAME, - CDI_TEMPLATE, SPRING_TEMPLATE, CDI_TEMPLATE) - .withDependencyInjection(annotator)); + super(new TemplatedGenerator(buildContext, packageName, CLASS_NAME, + CDI_TEMPLATE, SPRING_TEMPLATE, CDI_TEMPLATE)); + this.buildContext = buildContext; this.triggers = this.filterTriggers(generators); - this.annotator = annotator; this.addonsConfig = addonsConfig; } @@ -65,9 +63,7 @@ Map> getTriggers() { } public String generate() { - final CompilationUnit clazz = generator.compilationUnit() - .orElseThrow(() -> new InvalidTemplateException(CLASS_NAME, generator.templatePath(), - "Cannot generate TopicInformation REST Resource")); + final CompilationUnit clazz = generator.compilationUnitOrThrow("Cannot generate TopicInformation REST Resource"); final ClassOrInterfaceDeclaration template = clazz .findFirst(ClassOrInterfaceDeclaration.class) .orElseThrow(() -> new NoSuchElementException("Compilation unit doesn't contain a class or interface declaration!")); @@ -75,10 +71,10 @@ public String generate() { this.addEventsMeta(template); // in case we don't have the bean in the classpath, just ignore the injection that the generated class will use NoOp instead - if (annotator != null && addonsConfig.useCloudEvents()) { - annotator.withApplicationComponent(template); + if (buildContext.hasDI() && addonsConfig.useCloudEvents()) { + buildContext.getDependencyInjectionAnnotator().withApplicationComponent(template); template.findAll(FieldDeclaration.class, fd -> fd.getVariables().get(0).getNameAsString().contains("discovery")) - .forEach(annotator::withInjection); + .forEach(buildContext.getDependencyInjectionAnnotator()::withInjection); } else { template.findFirst(MethodDeclaration.class, md -> md.getName().toString().equals("getTopics")) .orElseThrow(() -> new NoSuchElementException("Compilation unit doesn't contain method getTopics!")) diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/persistence/PersistenceGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/persistence/PersistenceGenerator.java index 0942ce66e8d..e8f988b0616 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/persistence/PersistenceGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/process/persistence/PersistenceGenerator.java @@ -50,11 +50,11 @@ import org.kie.kogito.codegen.AbstractGenerator; import org.kie.kogito.codegen.ApplicationSection; import org.kie.kogito.codegen.BodyDeclarationComparator; -import org.kie.kogito.codegen.ConfigGenerator; +import org.kie.kogito.codegen.ApplicationConfigGenerator; import org.kie.kogito.codegen.GeneratedFile; -import org.kie.kogito.codegen.di.CDIDependencyInjectionAnnotator; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; -import org.kie.kogito.codegen.di.SpringDependencyInjectionAnnotator; +import org.kie.kogito.codegen.context.KogitoBuildContext; +import org.kie.kogito.codegen.context.QuarkusKogitoBuildContext; +import org.kie.kogito.codegen.context.SpringBootKogitoBuildContext; import org.kie.kogito.codegen.metadata.MetaDataWriter; import org.kie.kogito.codegen.metadata.PersistenceLabeler; import org.kie.kogito.codegen.metadata.PersistenceProtoFilesLabeler; @@ -142,11 +142,8 @@ public Collection generate() { } @Override - public void updateConfig(ConfigGenerator cfg) { - } - - protected boolean useInjection() { - return this.annotator != null; + public void updateConfig(ApplicationConfigGenerator cfg) { + // Persistence has no custom/additional config } @SuppressWarnings({"rawtypes", "unchecked"}) @@ -191,14 +188,15 @@ protected void infinispanBasedPersistence(List generatedFiles) { ConstructorDeclaration constructor = createConstructorForClazz(persistenceProviderClazz); - if (useInjection()) { - annotator.withApplicationComponent(persistenceProviderClazz); - annotator.withInjection(constructor); + KogitoBuildContext buildContext = context.getBuildContext(); + if (buildContext.hasDI()) { + buildContext.getDependencyInjectionAnnotator().withApplicationComponent(persistenceProviderClazz); + buildContext.getDependencyInjectionAnnotator().withInjection(constructor); FieldDeclaration templateNameField = new FieldDeclaration().addVariable(new VariableDeclarator() .setType(new ClassOrInterfaceType(null, new SimpleName(Optional.class.getCanonicalName()), NodeList.nodeList(new ClassOrInterfaceType(null, String.class.getCanonicalName())))) .setName(TEMPLATE_NAME)); - annotator.withConfigInjection(templateNameField, "kogito.persistence.infinispan.template"); + buildContext.getDependencyInjectionAnnotator().withConfigInjection(templateNameField, "kogito.persistence.infinispan.template"); // allow to inject template name for the cache BlockStmt templateMethodBody = new BlockStmt(); templateMethodBody.addStatement(new ReturnStmt(new MethodCallExpr(new NameExpr(TEMPLATE_NAME), OR_ELSE).addArgument(new StringLiteralExpr("")))); @@ -285,13 +283,14 @@ protected void fileSystemBasedPersistence(List generatedFiles) { CompilationUnit compilationUnit = new CompilationUnit(KOGITO_PROCESS_INSTANCE_PACKAGE); compilationUnit.getTypes().add(persistenceProviderClazz); - if (useInjection()) { - annotator.withApplicationComponent(persistenceProviderClazz); + KogitoBuildContext buildContext = context.getBuildContext(); + if (buildContext.hasDI()) { + buildContext.getDependencyInjectionAnnotator().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); + buildContext.getDependencyInjectionAnnotator().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), OR_ELSE).addArgument(new StringLiteralExpr("/tmp")))); @@ -320,9 +319,11 @@ private void mongodbBasedPersistence(List generatedFiles) { persistenceProviderClazz.addConstructor(Keyword.PUBLIC).setBody(new BlockStmt().addStatement(new ExplicitConstructorInvocationStmt(false, null, NodeList.nodeList(new NullLiteralExpr())))); ConstructorDeclaration constructor = createConstructorForClazz(persistenceProviderClazz); - if (useInjection()) { - annotator.withApplicationComponent(persistenceProviderClazz); - annotator.withInjection(constructor); + + KogitoBuildContext buildContext = context.getBuildContext(); + if (buildContext.hasDI()) { + buildContext.getDependencyInjectionAnnotator().withApplicationComponent(persistenceProviderClazz); + buildContext.getDependencyInjectionAnnotator().withInjection(constructor); FieldDeclaration dbNameField = new FieldDeclaration().addVariable(new VariableDeclarator() .setType(new ClassOrInterfaceType(null, new SimpleName(Optional.class.getCanonicalName()), NodeList.nodeList( @@ -330,10 +331,10 @@ private void mongodbBasedPersistence(List generatedFiles) { String.class.getCanonicalName())))) .setName(MONGODB_DB_NAME)); //injecting dbName from quarkus/springboot properties else default kogito - if (annotator instanceof CDIDependencyInjectionAnnotator) { - annotator.withConfigInjection(dbNameField, QUARKUS_PERSISTENCE_MONGODB_NAME_PROP); - } else if (annotator instanceof SpringDependencyInjectionAnnotator) { - annotator.withConfigInjection(dbNameField, SPRINGBOOT_PERSISTENCE_MONGODB_NAME_PROP); + if (buildContext instanceof QuarkusKogitoBuildContext) { + buildContext.getDependencyInjectionAnnotator().withConfigInjection(dbNameField, QUARKUS_PERSISTENCE_MONGODB_NAME_PROP); + } else if (buildContext instanceof SpringBootKogitoBuildContext) { + buildContext.getDependencyInjectionAnnotator().withConfigInjection(dbNameField, SPRINGBOOT_PERSISTENCE_MONGODB_NAME_PROP); } BlockStmt dbNameMethodBody = new BlockStmt(); diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/rules/DeclaredTypeCodegen.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/rules/DeclaredTypeCodegen.java index b6a8751e17d..7c4801cc6f7 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/rules/DeclaredTypeCodegen.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/rules/DeclaredTypeCodegen.java @@ -42,7 +42,7 @@ import org.kie.internal.builder.CompositeKnowledgeBuilder; import org.kie.kogito.codegen.AbstractGenerator; import org.kie.kogito.codegen.ApplicationSection; -import org.kie.kogito.codegen.ConfigGenerator; +import org.kie.kogito.codegen.ApplicationConfigGenerator; import org.kie.kogito.codegen.KogitoPackageSources; import org.kie.kogito.codegen.rules.config.RuleConfigGenerator; import org.slf4j.Logger; @@ -159,8 +159,8 @@ protected void compileKnowledgePackages(PackageDescr packageDescr, PackageRegist } @Override - public void updateConfig(ConfigGenerator cfg) { - cfg.withRuleConfig(new RuleConfigGenerator("defaultpkg")); + public void updateConfig(ApplicationConfigGenerator cfg) { + cfg.withRuleConfig(new RuleConfigGenerator(context().getBuildContext(), "defaultpkg")); } public DeclaredTypeCodegen withClassLoader(ClassLoader projectClassLoader) { diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/rules/IncrementalRuleCodegen.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/rules/IncrementalRuleCodegen.java index ef0906e939b..0dbbeae8b53 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/rules/IncrementalRuleCodegen.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/rules/IncrementalRuleCodegen.java @@ -55,10 +55,11 @@ import org.kie.internal.ruleunit.RuleUnitDescription; import org.kie.kogito.codegen.AbstractGenerator; import org.kie.kogito.codegen.ApplicationSection; -import org.kie.kogito.codegen.ConfigGenerator; +import org.kie.kogito.codegen.ApplicationConfigGenerator; import org.kie.kogito.codegen.DashboardGeneratedFileUtils; import org.kie.kogito.codegen.GeneratorContext; import org.kie.kogito.codegen.KogitoPackageSources; +import org.kie.kogito.codegen.context.KogitoBuildContext; import org.kie.kogito.codegen.io.CollectedResource; import org.kie.kogito.codegen.rules.config.NamedRuleUnitConfig; import org.kie.kogito.codegen.rules.config.RuleConfigGenerator; @@ -83,11 +84,11 @@ public class IncrementalRuleCodegen extends AbstractGenerator { private static final Logger LOGGER = LoggerFactory.getLogger(IncrementalRuleCodegen.class); public static IncrementalRuleCodegen ofCollectedResources(Collection resources) { - List dmnResources = resources.stream() + List generatedRules = resources.stream() .map(CollectedResource::resource) .filter(r -> r.getResourceType() == ResourceType.DRL || r.getResourceType() == ResourceType.DTABLE || r.getResourceType() == ResourceType.PROPERTIES) .collect(toList()); - return ofResources(dmnResources); + return ofResources(generatedRules); } public static IncrementalRuleCodegen ofJavaResources(Collection resources) { @@ -141,8 +142,7 @@ public void setContext(GeneratorContext context) { @Override public ApplicationSection section() { - RuleUnitContainerGenerator moduleGenerator = new RuleUnitContainerGenerator(packageName); - moduleGenerator.withDependencyInjection(annotator); + RuleUnitContainerGenerator moduleGenerator = new RuleUnitContainerGenerator(context.getBuildContext(), packageName); ruleUnitGenerators.forEach(moduleGenerator::addRuleUnit); return moduleGenerator; } @@ -196,7 +196,7 @@ public List generate() { if (hasRuleUnits) { generateRuleUnits( errors, generatedFiles ); } else { - if (annotator != null && !hotReloadMode) { + if (context.getBuildContext().hasDI() && !hotReloadMode) { generateSessionUnits( generatedFiles ); } generateProject( dummyReleaseId, modelsByUnit, generatedFiles ); @@ -253,8 +253,7 @@ private boolean generateModels( ModelBuilderImpl modelBuil hasRuleUnits = true; for (RuleUnitDescription ruleUnit : ruleUnits) { String canonicalName = ruleUnit.getCanonicalName(); - RuleUnitGenerator ruSource = new RuleUnitGenerator(ruleUnit, pkgSources.getRulesFileName()) - .withDependencyInjection(annotator) + RuleUnitGenerator ruSource = new RuleUnitGenerator(ruleUnit, pkgSources.getRulesFileName(), context.getBuildContext()) .withQueries(pkgSources.getQueriesInRuleUnit(canonicalName)) .withAddons(addonsConfig) .mergeConfig(configs.get(canonicalName)); @@ -283,8 +282,9 @@ private void generateProject( ReleaseIdImpl dummyReleaseId, Map modelSourceClass.generate())); ProjectSourceClass projectSourceClass = new ProjectSourceClass(modelSourceClass.getModelMethod()); - if (annotator != null) { - projectSourceClass.withDependencyInjection("@" + annotator.applicationComponentType()); + KogitoBuildContext buildContext = context.getBuildContext(); + if (buildContext.hasDI()) { + projectSourceClass.withDependencyInjection("@" + buildContext.getDependencyInjectionAnnotator().applicationComponentType()); } generatedFiles.add(new org.kie.kogito.codegen.GeneratedFile( @@ -296,9 +296,10 @@ private void generateProject( ReleaseIdImpl dummyReleaseId, Map private void generateRuleUnits( List errors, List generatedFiles ) { RuleUnitHelper ruleUnitHelper = new RuleUnitHelper(); - if (annotator != null) { + if (context.getBuildContext().hasDI()) { generatedFiles.add( new org.kie.kogito.codegen.GeneratedFile( org.kie.kogito.codegen.GeneratedFile.Type.JSON_MAPPER, - packageName.replace('.', '/') + "/KogitoObjectMapper.java", annotator.objectMapperInjectorSource(packageName) ) ); + packageName.replace('.', '/') + "/KogitoObjectMapper.java", + context.getBuildContext().getDependencyInjectionAnnotator().objectMapperInjectorSource(packageName) ) ); } for (RuleUnitGenerator ruleUnit : ruleUnitGenerators) { @@ -325,7 +326,7 @@ private List generateQueriesEndpoint( List errors, List ge for (String sessionName : kBaseModel.getKieSessionModels().keySet()) { CompilationUnit cu = parse( getClass().getResourceAsStream( "/class-templates/SessionRuleUnitTemplate.java" ) ); ClassOrInterfaceDeclaration template = cu.findFirst( ClassOrInterfaceDeclaration.class ).get(); - annotator.withNamedSingletonComponent(template, "$SessionName$"); + context.getBuildContext().getDependencyInjectionAnnotator().withNamedSingletonComponent(template, "$SessionName$"); template.setName( "SessionRuleUnit_" + sessionName ); - template.findAll( FieldDeclaration.class).stream().filter( fd -> fd.getVariable(0).getNameAsString().equals("runtimeBuilder")).forEach( fd -> annotator.withInjection(fd)); + template.findAll( FieldDeclaration.class).stream() + .filter( fd -> fd.getVariable(0).getNameAsString().equals("runtimeBuilder")) + .forEach( fd -> context.getBuildContext().getDependencyInjectionAnnotator().withInjection(fd)); template.findAll( StringLiteralExpr.class ).forEach( s -> s.setString( s.getValue().replace( "$SessionName$", sessionName ) ) ); generatedFiles.add(new org.kie.kogito.codegen.GeneratedFile( @@ -416,8 +419,8 @@ private String ruleUnit2KieSessionName(String ruleUnit) { } @Override - public void updateConfig(ConfigGenerator cfg) { - cfg.withRuleConfig(new RuleConfigGenerator(packageName)); + public void updateConfig(ApplicationConfigGenerator cfg) { + cfg.withRuleConfig(new RuleConfigGenerator(context().getBuildContext(), packageName)); } public IncrementalRuleCodegen withKModule(KieModuleModel model) { diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/rules/QueryEndpointGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/rules/QueryEndpointGenerator.java index 1384f6721a2..577b4240bed 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/rules/QueryEndpointGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/rules/QueryEndpointGenerator.java @@ -48,9 +48,8 @@ import org.kie.kogito.codegen.AddonsConfig; import org.kie.kogito.codegen.BodyDeclarationComparator; import org.kie.kogito.codegen.FileGenerator; -import org.kie.kogito.codegen.TemplateInstantiationException; import org.kie.kogito.codegen.TemplatedGenerator; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; +import org.kie.kogito.codegen.context.KogitoBuildContext; import static com.github.javaparser.StaticJavaParser.parseClassOrInterfaceType; import static com.github.javaparser.StaticJavaParser.parseStatement; @@ -64,9 +63,9 @@ public class QueryEndpointGenerator implements FileGenerator { private final RuleUnitDescription ruleUnit; private final QueryModel query; - private final DependencyInjectionAnnotator annotator; private final String name; + private final KogitoBuildContext buildContext; private final String endpointName; private final String queryClassName; private final String targetCanonicalName; @@ -74,20 +73,22 @@ public class QueryEndpointGenerator implements FileGenerator { private final AddonsConfig addonsConfig; private final TemplatedGenerator generator; - public QueryEndpointGenerator(RuleUnitDescription ruleUnit, QueryModel query, DependencyInjectionAnnotator annotator, AddonsConfig addonsConfig) { + public QueryEndpointGenerator(RuleUnitDescription ruleUnit, + QueryModel query, + KogitoBuildContext buildContext, + AddonsConfig addonsConfig) { this.ruleUnit = ruleUnit; this.query = query; this.name = toCamelCase(query.getName()); + this.buildContext = buildContext; this.endpointName = toKebabCase(name); - this.annotator = annotator; this.queryClassName = ruleUnit.getSimpleName() + "Query" + name; this.targetCanonicalName = queryClassName + "Endpoint"; this.generatedFilePath = (query.getNamespace() + "." + targetCanonicalName).replace('.', '/') + ".java"; this.addonsConfig = addonsConfig; this.generator = - new TemplatedGenerator(query.getNamespace(), targetCanonicalName, RESOURCE_CDI, RESOURCE_SPRING, RESOURCE_DEFAULT) - .withDependencyInjection(annotator); + new TemplatedGenerator(buildContext, query.getNamespace(), targetCanonicalName, RESOURCE_CDI, RESOURCE_SPRING, RESOURCE_DEFAULT); } public QueryGenerator getQueryGenerator() { @@ -134,11 +135,7 @@ public int[] getLines() { @Override public String generate() { - CompilationUnit cu = generator.compilationUnit() - .orElseThrow(() -> { - throw new TemplateInstantiationException( - generator.typeName(), generator.templatePath(), "Could not create CompilationUnit"); - }); + CompilationUnit cu = generator.compilationUnitOrThrow("Could not create CompilationUnit"); cu.setPackageDeclaration(query.getNamespace()); ClassOrInterfaceDeclaration clazz = cu @@ -174,7 +171,7 @@ private void generateConstructors(ClassOrInterfaceDeclaration clazz) { } private void generateQueryMethods(CompilationUnit cu, ClassOrInterfaceDeclaration clazz, String returnType) { - boolean hasDI = annotator != null; + boolean hasDI = buildContext.hasDI(); MethodDeclaration queryMethod = clazz.getMethodsByName("executeQuery").get(0); queryMethod.getParameter(0).setType(ruleUnit.getCanonicalName() + (hasDI ? "" : "DTO")); setGeneric(queryMethod.getType(), returnType); diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/rules/RuleUnitContainerGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/rules/RuleUnitContainerGenerator.java index 5ac7059b12c..d8ffd7f1ce1 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/rules/RuleUnitContainerGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/rules/RuleUnitContainerGenerator.java @@ -20,9 +20,8 @@ import com.github.javaparser.ast.CompilationUnit; import org.kie.kogito.codegen.AbstractApplicationSection; -import org.kie.kogito.codegen.InvalidTemplateException; import org.kie.kogito.codegen.TemplatedGenerator; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; +import org.kie.kogito.codegen.context.KogitoBuildContext; import com.github.javaparser.ast.body.BodyDeclaration; import com.github.javaparser.ast.body.MethodDeclaration; @@ -44,13 +43,13 @@ public class RuleUnitContainerGenerator extends AbstractApplicationSection { private final List ruleUnits; private final TemplatedGenerator templatedGenerator; - private DependencyInjectionAnnotator annotator; private List> factoryMethods = new ArrayList<>(); - public RuleUnitContainerGenerator(String packageName) { - super(SECTION_CLASS_NAME); + public RuleUnitContainerGenerator(KogitoBuildContext buildContext, String packageName) { + super(buildContext, SECTION_CLASS_NAME); this.ruleUnits = new ArrayList<>(); this.templatedGenerator = new TemplatedGenerator( + buildContext, packageName, SECTION_CLASS_NAME, RESOURCE_CDI, @@ -86,13 +85,9 @@ private BlockStmt factoryByIdBody() { @Override public CompilationUnit compilationUnit() { - CompilationUnit compilationUnit = templatedGenerator.compilationUnit() - .orElseThrow(() -> new InvalidTemplateException( - SECTION_CLASS_NAME, - templatedGenerator.templatePath(), - "No CompilationUnit")); + CompilationUnit compilationUnit = templatedGenerator.compilationUnitOrThrow("No CompilationUnit"); - if (annotator == null) { + if (!buildContext.hasDI()) { // only in a non DI context compilationUnit.findFirst(MethodDeclaration.class, m -> m.getNameAsString().equals("create")) .ifPresent(m -> m.setBody(factoryByIdBody())); // ignore if missing @@ -100,14 +95,4 @@ public CompilationUnit compilationUnit() { return compilationUnit; } - - public RuleUnitContainerGenerator withDependencyInjection(DependencyInjectionAnnotator annotator) { - this.annotator = annotator; - this.templatedGenerator.withDependencyInjection(annotator); - return this; - } - - List getRuleUnits() { - return ruleUnits; - } } diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/rules/RuleUnitGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/rules/RuleUnitGenerator.java index 60a36c48972..7359fb434bf 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/rules/RuleUnitGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/rules/RuleUnitGenerator.java @@ -37,7 +37,7 @@ import org.kie.kogito.codegen.AddonsConfig; import org.kie.kogito.codegen.ApplicationGenerator; import org.kie.kogito.codegen.FileGenerator; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; +import org.kie.kogito.codegen.context.KogitoBuildContext; import org.kie.kogito.conf.ClockType; import org.kie.kogito.conf.EventProcessingType; import org.kie.kogito.rules.RuleUnit; @@ -59,20 +59,21 @@ public class RuleUnitGenerator implements FileGenerator { private final String packageName; private final String typeName; private final String generatedSourceFile; + private KogitoBuildContext buildContext; private final String generatedFilePath; private final String targetCanonicalName; private RuleUnitConfig config; private String targetTypeName; - private DependencyInjectionAnnotator annotator; private Collection queries; private String applicationPackageName; private AddonsConfig addonsConfig = AddonsConfig.DEFAULT; - public RuleUnitGenerator(RuleUnitDescription ruleUnit, String generatedSourceFile) { + public RuleUnitGenerator(RuleUnitDescription ruleUnit, String generatedSourceFile, KogitoBuildContext buildContext) { this.ruleUnit = ruleUnit; this.packageName = ruleUnit.getPackageName(); this.typeName = ruleUnit.getSimpleName(); this.generatedSourceFile = generatedSourceFile; + this.buildContext = buildContext; this.targetTypeName = typeName + "RuleUnit"; this.targetCanonicalName = packageName + "." + targetTypeName; this.generatedFilePath = targetCanonicalName.replace('.', '/') + ".java"; @@ -95,7 +96,7 @@ public RuleUnitInstanceGenerator instance(RuleUnitHelper ruleUnitHelper, List queries() { return queries.stream() .filter(query -> !query.hasParameters()) - .map(query -> new QueryEndpointGenerator(ruleUnit, query, annotator, addonsConfig)) + .map(query -> new QueryEndpointGenerator(ruleUnit, query, buildContext, addonsConfig)) .collect(toList()); } @@ -158,10 +159,10 @@ public void classDeclaration(ClassOrInterfaceDeclaration cls) { .setModifiers(Modifier.Keyword.PUBLIC) .getExtendedTypes().get(0).setTypeArguments(nodeList(new ClassOrInterfaceType(null, typeName))); - if (annotator != null) { - annotator.withSingletonComponent(cls); + if (buildContext.hasDI()) { + buildContext.getDependencyInjectionAnnotator().withSingletonComponent(cls); cls.findFirst(ConstructorDeclaration.class, c -> !c.getParameters().isEmpty()) // non-empty constructor - .ifPresent(annotator::withInjection); + .ifPresent(buildContext.getDependencyInjectionAnnotator()::withInjection); } String ruleUnitInstanceFQCN = RuleUnitInstanceGenerator.qualifiedName(packageName, typeName); @@ -215,11 +216,6 @@ private void setClassName(ConstructorDeclaration constructorDeclaration) { constructorDeclaration.setName(targetTypeName); } - public RuleUnitGenerator withDependencyInjection(DependencyInjectionAnnotator annotator) { - this.annotator = annotator; - return this; - } - public RuleUnitGenerator withQueries(Collection queries) { this.queries = queries; return this; diff --git a/kogito-codegen/src/main/java/org/kie/kogito/codegen/rules/config/RuleConfigGenerator.java b/kogito-codegen/src/main/java/org/kie/kogito/codegen/rules/config/RuleConfigGenerator.java index 0d24e40accf..cb4b2add284 100644 --- a/kogito-codegen/src/main/java/org/kie/kogito/codegen/rules/config/RuleConfigGenerator.java +++ b/kogito-codegen/src/main/java/org/kie/kogito/codegen/rules/config/RuleConfigGenerator.java @@ -15,17 +15,16 @@ package org.kie.kogito.codegen.rules.config; -import org.kie.kogito.codegen.TemplatedGenerator; +import org.kie.kogito.codegen.AbstractConfigGenerator; +import org.kie.kogito.codegen.context.KogitoBuildContext; -public class RuleConfigGenerator extends TemplatedGenerator { +public class RuleConfigGenerator extends AbstractConfigGenerator { - private static final String RESOURCE_CDI = "/class-templates/config/CdiRuleConfigTemplate.java"; - private static final String RESOURCE_SPRING = "/class-templates/config/SpringRuleConfigTemplate.java"; - - public RuleConfigGenerator(String packageName) { - super(packageName, - "RuleConfig", - RESOURCE_CDI, - RESOURCE_SPRING); + public RuleConfigGenerator(KogitoBuildContext buildContext, String packageName) { + super(buildContext, + packageName, + "RuleConfig", + "/class-templates/config/CdiRuleConfigTemplate.java", + "/class-templates/config/SpringRuleConfigTemplate.java"); } } diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/AbstractCodegenTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/AbstractCodegenTest.java index c72945ed3cf..3113e28d07b 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/AbstractCodegenTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/AbstractCodegenTest.java @@ -30,11 +30,11 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; -import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; +import org.kie.kogito.codegen.context.JavaKogitoBuildContext; import org.kie.memorycompiler.CompilationResult; import org.kie.memorycompiler.JavaCompiler; import org.kie.memorycompiler.JavaCompilerFactory; @@ -78,6 +78,8 @@ protected enum TYPE { private static final Map, Generator>> generatorTypeMap = new HashMap<>(); + private KogitoBuildContext buildContext = new JavaKogitoBuildContext(this.getClass().getClassLoader()); + private static final String DUMMY_PROCESS_RUNTIME = "package org.drools.project.model;\n" + "\n" + @@ -143,10 +145,20 @@ private static List toFiles(List strings, String path) { .collect(Collectors.toList()); } - private boolean withSpringContext; - public void withSpringContext(boolean withSpringContext){ - this.withSpringContext = withSpringContext; + public void withSpringContext() { + this.buildContext = new SpringBootKogitoBuildContext(className -> true); + throw new UnsupportedOperationException("To be fixed KOGITO-4000"); + } + + public void withQuarkusContext() { + this.buildContext = new QuarkusKogitoBuildContext(className -> true); + throw new UnsupportedOperationException("To be fixed KOGITO-4000"); + } + + public void withJavaContext() { + this.buildContext = new JavaKogitoBuildContext(className -> true); + throw new UnsupportedOperationException("To be fixed KOGITO-4000"); } protected Application generateCodeProcessesOnly(String... processes) throws Exception { @@ -174,16 +186,10 @@ protected Application generateCode(Map> resourcesTypeMap) thr protected Application generateCode(Map> resourcesTypeMap, String packageName) throws Exception { GeneratorContext context = GeneratorContext.ofResourcePath(new File(TEST_RESOURCES)); - //Testing based on Quarkus as Default - context.withBuildContext(Optional.ofNullable(withSpringContext) - .filter(Boolean.TRUE::equals) - .map(t -> new SpringBootKogitoBuildContext((className -> true))) - .orElse(new QuarkusKogitoBuildContext((className -> true)))); + context.withBuildContext(buildContext); ApplicationGenerator appGen = - new ApplicationGenerator(packageName, new File("target/codegen-tests")) - .withGeneratorContext(context) - .withDependencyInjection(null); + new ApplicationGenerator(context, packageName, new File("target/codegen-tests")); // Hack just to avoid test breaking Set generatedTypes = new HashSet<>(); @@ -195,7 +201,7 @@ protected Application generateCode(Map> resourcesTypeMap, Str } // Hack just to avoid test breaking if (generatedTypes.contains(TYPE.DECISION) && !generatedTypes.contains(TYPE.PREDICTION)) { - appGen.setupGenerator(generatorTypeMap.get(TYPE.PREDICTION).apply(Collections.EMPTY_LIST)); + appGen.setupGenerator(generatorTypeMap.get(TYPE.PREDICTION).apply(Collections.emptyList())); } Collection generatedFiles = appGen.generate(); diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/ConfigGeneratorTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/ApplicationConfigGeneratorTest.java similarity index 57% rename from kogito-codegen/src/test/java/org/kie/kogito/codegen/ConfigGeneratorTest.java rename to kogito-codegen/src/test/java/org/kie/kogito/codegen/ApplicationConfigGeneratorTest.java index 5bcb53720f2..781baf9280b 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/ConfigGeneratorTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/ApplicationConfigGeneratorTest.java @@ -21,26 +21,25 @@ import org.kie.kogito.codegen.process.config.ProcessConfigGenerator; import org.mockito.Mockito; -import com.github.javaparser.ast.expr.NullLiteralExpr; -import com.github.javaparser.ast.expr.ObjectCreationExpr; - -public class ConfigGeneratorTest { +public class ApplicationConfigGeneratorTest { @Test public void withProcessConfig() { - final ConfigGenerator generator = new ConfigGenerator("org.kie.kogito.test"); + final ApplicationConfigGenerator generator = new ApplicationConfigGenerator(null, "org.kie.kogito.test"); final ProcessConfigGenerator processConfigGenerator = Mockito.mock(ProcessConfigGenerator.class); - final ConfigGenerator returnedConfigGenerator = generator.withProcessConfig(processConfigGenerator); - assertThat(returnedConfigGenerator).isNotNull(); - assertThat(returnedConfigGenerator).isSameAs(generator); + final ApplicationConfigGenerator returnedConfigGenerator = generator.withProcessConfig(processConfigGenerator); + assertThat(returnedConfigGenerator) + .isNotNull() + .isSameAs(generator); } @Test public void withProcessConfigNull() { - final ConfigGenerator generator = new ConfigGenerator("org.kie.kogito.test"); - final ConfigGenerator returnedConfigGenerator = generator.withProcessConfig(null); - assertThat(returnedConfigGenerator).isNotNull(); - assertThat(returnedConfigGenerator).isSameAs(generator); + final ApplicationConfigGenerator generator = new ApplicationConfigGenerator(null, "org.kie.kogito.test"); + final ApplicationConfigGenerator returnedConfigGenerator = generator.withProcessConfig(null); + assertThat(returnedConfigGenerator) + .isNotNull() + .isSameAs(generator); } } diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/ApplicationGeneratorTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/ApplicationGeneratorTest.java index 9f5154c088d..ac5785a27da 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/ApplicationGeneratorTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/ApplicationGeneratorTest.java @@ -36,7 +36,7 @@ import com.github.javaparser.ast.expr.Expression; import com.github.javaparser.ast.expr.MethodCallExpr; import org.junit.jupiter.api.Test; -import org.kie.kogito.codegen.di.CDIDependencyInjectionAnnotator; +import org.kie.kogito.codegen.context.QuarkusKogitoBuildContext; import org.kie.kogito.codegen.metadata.MetaDataWriter; import org.kie.kogito.codegen.metadata.PrometheusLabeler; @@ -47,29 +47,32 @@ public class ApplicationGeneratorTest { private static final String PACKAGE_NAME = "org.drools.test"; private static final String EXPECTED_APPLICATION_NAME = PACKAGE_NAME + ".Application"; + private static final GeneratorContext context = GeneratorContext.emptyContext(); @Test public void targetCanonicalName() { - final ApplicationGenerator appGenerator = new ApplicationGenerator(PACKAGE_NAME, new File("")); + final ApplicationGenerator appGenerator = new ApplicationGenerator(context, PACKAGE_NAME, new File("")); assertThat(appGenerator.targetCanonicalName()).isNotNull(); assertThat(appGenerator.targetCanonicalName()).isEqualTo(EXPECTED_APPLICATION_NAME); } @Test public void packageNameNull() { - assertThatThrownBy(() -> new ApplicationGenerator(null, new File(""))) + final File testFile = new File(""); + assertThatThrownBy(() -> new ApplicationGenerator(context, null, testFile)) .isInstanceOf(IllegalArgumentException.class); } @Test public void packageNameInvalid() { - assertThatThrownBy(() -> new ApplicationGenerator("i.am.an-invalid.package-name.sorry", new File(""))) + final File testFile = new File(""); + assertThatThrownBy(() -> new ApplicationGenerator(context, "i.am.an-invalid.package-name.sorry", testFile)) .isInstanceOf(IllegalArgumentException.class); } @Test public void generatedFilePath() { - final ApplicationGenerator appGenerator = new ApplicationGenerator(PACKAGE_NAME, new File("")); + final ApplicationGenerator appGenerator = new ApplicationGenerator(context, PACKAGE_NAME, new File("")); String path = appGenerator.generateApplicationDescriptor().relativePath(); assertThat(path).isNotNull(); assertThat(path).isEqualTo(EXPECTED_APPLICATION_NAME.replace(".", "/") + ".java"); @@ -77,21 +80,21 @@ public void generatedFilePath() { @Test public void compilationUnit() { - final ApplicationContainerGenerator appGenerator = new ApplicationContainerGenerator(PACKAGE_NAME); + final ApplicationContainerGenerator appGenerator = new ApplicationContainerGenerator(context.getBuildContext(), PACKAGE_NAME); assertCompilationUnit(appGenerator.getCompilationUnitOrThrow(), false); } @Test public void compilationUnitWithCDI() { - final ApplicationContainerGenerator appGenerator = new ApplicationContainerGenerator(PACKAGE_NAME); - appGenerator.withDependencyInjection(new CDIDependencyInjectionAnnotator()); + final ApplicationContainerGenerator appGenerator = new ApplicationContainerGenerator(new QuarkusKogitoBuildContext(s -> false), PACKAGE_NAME); assertCompilationUnit(appGenerator.getCompilationUnitOrThrow(), true); } @Test public void generateWithMonitoring() throws IOException { final Path targetDirectory = Paths.get("target"); - final ApplicationGenerator appGenerator = new ApplicationGenerator(PACKAGE_NAME, targetDirectory.toFile()).withAddons(new AddonsConfig().withPrometheusMonitoring(true)); + final ApplicationGenerator appGenerator = new ApplicationGenerator(context, PACKAGE_NAME, targetDirectory.toFile()) + .withAddons(new AddonsConfig().withPrometheusMonitoring(true)); appGenerator.generate(); assertImageMetadata(targetDirectory, new PrometheusLabeler().generateLabels()); } @@ -99,7 +102,7 @@ public void generateWithMonitoring() throws IOException { @Test public void writeLabelsImageMetadata() throws IOException { final Path targetDirectory = Paths.get("target"); - final ApplicationGenerator appGenerator = new ApplicationGenerator(PACKAGE_NAME, targetDirectory.toFile()); + final ApplicationGenerator appGenerator = new ApplicationGenerator(context, PACKAGE_NAME, targetDirectory.toFile()); final Map labels = new HashMap<>(); labels.put("testKey1", "testValue1"); @@ -112,7 +115,7 @@ public void writeLabelsImageMetadata() throws IOException { @Test public void applicationSectionReplace() { - final ApplicationContainerGenerator appGenerator = new ApplicationContainerGenerator(PACKAGE_NAME); + final ApplicationContainerGenerator appGenerator = new ApplicationContainerGenerator(context.getBuildContext(), PACKAGE_NAME); assertApplicationPlaceholderReplace(appGenerator, 0); appGenerator.withSections(Arrays.asList("Processes", "DecisionModels")); @@ -179,10 +182,9 @@ private void assertGeneratedFiles(final Collection generatedFiles } private void assertApplicationPlaceholderReplace(ApplicationContainerGenerator appGenerator, long expectedParams) { - Optional compilationUnit = appGenerator.compilationUnit(); - assertThat(compilationUnit).isPresent(); + CompilationUnit compilationUnit = appGenerator.getCompilationUnitOrThrow(); - Optional> expressions = compilationUnit.get().findFirst(MethodCallExpr.class, mtd -> "loadEngines".equals(mtd.getNameAsString())) + Optional> expressions = compilationUnit.findFirst(MethodCallExpr.class, mtd -> "loadEngines".equals(mtd.getNameAsString())) .map(MethodCallExpr::getArguments); assertThat(expressions).isPresent(); diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/prediction/PMMLRestResourceGeneratorTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/prediction/PMMLRestResourceGeneratorTest.java index c0811fe9127..61100e9737f 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/prediction/PMMLRestResourceGeneratorTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/prediction/PMMLRestResourceGeneratorTest.java @@ -33,20 +33,18 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.kie.dmn.feel.codegen.feel11.CodegenStringUtil; +import org.kie.kogito.codegen.context.JavaKogitoBuildContext; +import org.kie.kogito.codegen.context.KogitoBuildContext; import org.kie.kogito.codegen.di.CDIDependencyInjectionAnnotator; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; import org.kie.pmml.commons.model.KiePMMLModel; import static com.github.javaparser.StaticJavaParser.parse; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.kie.kogito.codegen.prediction.PMMLRestResourceGenerator.CDI_TEMPLATE; import static org.kie.pmml.commons.utils.KiePMMLModelUtils.getSanitizedClassName; -import static org.mockito.Mockito.mock; class PMMLRestResourceGeneratorTest { @@ -54,10 +52,12 @@ class PMMLRestResourceGeneratorTest { private final static KiePMMLModel KIE_PMML_MODEL = getKiePMMLModelInternal(); private static PMMLRestResourceGenerator pmmlRestResourceGenerator; private static ClassOrInterfaceDeclaration template = getClassOrInterfaceDeclaration(); + private static KogitoBuildContext buildContext; @BeforeAll public static void setup() { - pmmlRestResourceGenerator = new PMMLRestResourceGenerator(KIE_PMML_MODEL, APP_CANONICAL_NAME); + buildContext = new JavaKogitoBuildContext(); + pmmlRestResourceGenerator = new PMMLRestResourceGenerator(buildContext, KIE_PMML_MODEL, APP_CANONICAL_NAME); assertNotNull(pmmlRestResourceGenerator); } @@ -89,7 +89,8 @@ void constructor() { @Test void generateWithDependencyInjection() { - String retrieved = pmmlRestResourceGenerator.withDependencyInjection(new CDIDependencyInjectionAnnotator()).generate(); + buildContext.setDependencyInjectionAnnotator(new CDIDependencyInjectionAnnotator()); + String retrieved = pmmlRestResourceGenerator.generate(); commonEvaluateGenerate(retrieved); String expected = "Application application;"; assertTrue(retrieved.contains(expected)); @@ -97,7 +98,8 @@ void generateWithDependencyInjection() { @Test void generateWithoutDependencyInjection() { - String retrieved = pmmlRestResourceGenerator.withDependencyInjection(null).generate(); + buildContext.setDependencyInjectionAnnotator(null); + String retrieved = pmmlRestResourceGenerator.generate(); commonEvaluateGenerate(retrieved); String expected = String.format("Application application = new %s();", APP_CANONICAL_NAME); assertTrue(retrieved.contains(expected)); @@ -115,16 +117,6 @@ void getKiePMMLModel() { assertEquals(KIE_PMML_MODEL, pmmlRestResourceGenerator.getKiePMMLModel()); } - @Test - void withDependencyInjection() { - assertNull(pmmlRestResourceGenerator.annotator); - DependencyInjectionAnnotator dependencyInjectionAnnotator = mock(DependencyInjectionAnnotator.class); - PMMLRestResourceGenerator retrieved = - pmmlRestResourceGenerator.withDependencyInjection(dependencyInjectionAnnotator); - assertEquals(pmmlRestResourceGenerator, retrieved); - assertEquals(dependencyInjectionAnnotator, pmmlRestResourceGenerator.annotator); - } - @Test void className() { String classPrefix = getSanitizedClassName(KIE_PMML_MODEL.getName()); @@ -141,14 +133,6 @@ void generatedFilePath() { assertTrue(retrieved.endsWith(expected)); } - @Test - void useInjection() { - pmmlRestResourceGenerator.withDependencyInjection(null); - assertFalse(pmmlRestResourceGenerator.useInjection()); - pmmlRestResourceGenerator.withDependencyInjection(mock(DependencyInjectionAnnotator.class)); - assertTrue(pmmlRestResourceGenerator.useInjection()); - } - @Test void setPathValue() { final Optional retrievedOpt = template.findFirst(SingleMemberAnnotationExpr.class); diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/prediction/PredictionContainerGeneratorTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/prediction/PredictionContainerGeneratorTest.java index c480dce1c8f..d10011e829f 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/prediction/PredictionContainerGeneratorTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/prediction/PredictionContainerGeneratorTest.java @@ -50,7 +50,8 @@ class PredictionContainerGeneratorTest { @BeforeAll public static void setup() { - predictionContainerGenerator = new PredictionModelsGenerator(ApplicationGenerator.DEFAULT_PACKAGE_NAME, + predictionContainerGenerator = new PredictionModelsGenerator( + null, ApplicationGenerator.DEFAULT_PACKAGE_NAME, APP_CANONICAL_NAME, PMML_RESOURCES); assertNotNull(predictionContainerGenerator); diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/prediction/config/PredictionConfigGeneratorTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/prediction/config/PredictionConfigGeneratorTest.java index 9cb6158b9cc..6cd46bf41a4 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/prediction/config/PredictionConfigGeneratorTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/prediction/config/PredictionConfigGeneratorTest.java @@ -17,15 +17,13 @@ import java.util.List; import java.util.Optional; -import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.body.BodyDeclaration; -import com.github.javaparser.ast.expr.ObjectCreationExpr; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.kie.kogito.codegen.di.CDIDependencyInjectionAnnotator; -import org.kie.kogito.codegen.di.SpringDependencyInjectionAnnotator; +import org.kie.kogito.codegen.GeneratedFile; +import org.kie.kogito.codegen.context.QuarkusKogitoBuildContext; +import org.kie.kogito.codegen.context.SpringBootKogitoBuildContext; -import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -33,20 +31,14 @@ class PredictionConfigGeneratorTest { private final static String PACKAGE_NAME = "PACKAGENAME"; - private static PredictionConfigGenerator predictionConfigGenerator; - - @BeforeAll - public static void setup() { - predictionConfigGenerator = new PredictionConfigGenerator(PACKAGE_NAME); - assertNotNull(predictionConfigGenerator); - } @Test void compilationUnitWithCDI() { - predictionConfigGenerator.withDependencyInjection(new CDIDependencyInjectionAnnotator()); - final Optional retrievedOpt = predictionConfigGenerator.compilationUnit(); + PredictionConfigGenerator predictionConfigGenerator = new PredictionConfigGenerator(new QuarkusKogitoBuildContext(s -> false), PACKAGE_NAME); + Optional retrievedOpt = predictionConfigGenerator.generate(); + assertNotNull(retrievedOpt); assertTrue(retrievedOpt.isPresent()); - String retrieved = retrievedOpt.get().toString(); + String retrieved = new String(retrievedOpt.get().contents()); String expected = "@javax.inject.Singleton"; assertTrue(retrieved.contains(expected)); expected = "@javax.inject.Inject"; @@ -59,10 +51,11 @@ void compilationUnitWithCDI() { @Test void compilationUnitWithSpring() { - predictionConfigGenerator.withDependencyInjection(new SpringDependencyInjectionAnnotator()); - final Optional retrievedOpt = predictionConfigGenerator.compilationUnit(); + PredictionConfigGenerator predictionConfigGenerator = new PredictionConfigGenerator(new SpringBootKogitoBuildContext(s -> false), PACKAGE_NAME); + Optional retrievedOpt = predictionConfigGenerator.generate(); + assertNotNull(retrievedOpt); assertTrue(retrievedOpt.isPresent()); - String retrieved = retrievedOpt.get().toString(); + String retrieved = new String(retrievedOpt.get().contents()); String expected = "@org.springframework.stereotype.Component"; assertTrue(retrieved.contains(expected)); expected = "@org.springframework.beans.factory.annotation.Autowired"; @@ -73,15 +66,9 @@ void compilationUnitWithSpring() { assertFalse(retrieved.contains(unexpected)); } - @Test - void newInstance() { - ObjectCreationExpr retrieved = predictionConfigGenerator.newInstance(); - String expected = "new org.kie.kogito.pmml.config.StaticPredictionConfig()"; - assertEquals(expected, retrieved.toString()); - } - @Test void members() { + PredictionConfigGenerator predictionConfigGenerator = new PredictionConfigGenerator(new QuarkusKogitoBuildContext(s -> false), PACKAGE_NAME); List> retrieved = predictionConfigGenerator.members(); assertNotNull(retrieved); assertTrue(retrieved.isEmpty()); diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/process/events/CloudEventsMessageProducerGeneratorTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/process/events/CloudEventsMessageProducerGeneratorTest.java index 6095df6145c..54291392019 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/process/events/CloudEventsMessageProducerGeneratorTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/process/events/CloudEventsMessageProducerGeneratorTest.java @@ -20,8 +20,8 @@ import org.assertj.core.api.Assertions; import org.jbpm.compiler.canonical.TriggerMetaData; import org.junit.jupiter.api.Test; -import org.kie.kogito.codegen.di.CDIDependencyInjectionAnnotator; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; +import org.kie.kogito.codegen.context.KogitoBuildContext; +import org.kie.kogito.codegen.context.QuarkusKogitoBuildContext; import org.kie.kogito.codegen.process.MessageDataEventGenerator; import org.kie.kogito.codegen.process.MessageProducerGenerator; import org.kie.kogito.codegen.process.ProcessExecutableModelGenerator; @@ -33,7 +33,7 @@ class CloudEventsMessageProducerGeneratorTest { void verifyKnativeAddonProcessing() { final List models = ProcessGenerationUtils.execModelFromProcessFile("/messageevent/IntermediateThrowEventMessage.bpmn2"); - final DependencyInjectionAnnotator annotator = new CDIDependencyInjectionAnnotator(); + final KogitoBuildContext buildContext = new QuarkusKogitoBuildContext(s -> true); Assertions.assertThat(models).isNotEmpty(); models.forEach(m -> { final TriggerMetaData metaData = m.generate().getTriggers() @@ -42,10 +42,9 @@ void verifyKnativeAddonProcessing() { .findFirst() .orElseThrow(() -> new IllegalArgumentException("Process does not contains any message producers")); final MessageDataEventGenerator msgDataEventGenerator = - new MessageDataEventGenerator(m.process(), metaData).withDependencyInjection(annotator); + new MessageDataEventGenerator(m.process(), metaData); final MessageProducerGenerator gen = - new CloudEventsMessageProducerGenerator(m.process(), "", "", msgDataEventGenerator.className(), metaData) - .withDependencyInjection(annotator); + new CloudEventsMessageProducerGenerator(buildContext, m.process(), "", "", msgDataEventGenerator.className(), metaData); final String code = gen.generate(); Assertions.assertThat(code).isNotBlank(); Assertions.assertThat(code).contains("decorator.get().decorate"); diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/process/events/CloudEventsResourceGeneratorTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/process/events/CloudEventsResourceGeneratorTest.java index c13e8082c52..19615a9f1e1 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/process/events/CloudEventsResourceGeneratorTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/process/events/CloudEventsResourceGeneratorTest.java @@ -26,9 +26,9 @@ import com.github.javaparser.ast.ImportDeclaration; import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; import org.junit.jupiter.api.Test; +import org.kie.kogito.codegen.context.KogitoBuildContext; +import org.kie.kogito.codegen.context.QuarkusKogitoBuildContext; import org.kie.kogito.codegen.ApplicationGenerator; -import org.kie.kogito.codegen.di.CDIDependencyInjectionAnnotator; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -37,11 +37,11 @@ class CloudEventsResourceGeneratorTest { - private final DependencyInjectionAnnotator annotator = new CDIDependencyInjectionAnnotator(); + private final KogitoBuildContext buildContext = new QuarkusKogitoBuildContext(s -> true); @Test void verifyBasicGenerationCase() { - final String sourceCode = new CloudEventsResourceGenerator(ApplicationGenerator.DEFAULT_PACKAGE_NAME, Collections.emptyList(), annotator).generate(); + final String sourceCode = new CloudEventsResourceGenerator(buildContext, ApplicationGenerator.DEFAULT_PACKAGE_NAME, Collections.emptyList()).generate(); assertNotNull(sourceCode); final CompilationUnit clazz = StaticJavaParser.parse(sourceCode); assertNotNull(clazz); @@ -52,16 +52,16 @@ void verifyBasicGenerationCase() { @Test void generatedFilePath() throws URISyntaxException { - final String filePath = new CloudEventsResourceGenerator(ApplicationGenerator.DEFAULT_PACKAGE_NAME, Collections.emptyList(), annotator).generatedFilePath(); + final String filePath = new CloudEventsResourceGenerator(buildContext, ApplicationGenerator.DEFAULT_PACKAGE_NAME, Collections.emptyList()).generatedFilePath(); assertThat(new URI(filePath).toString()).endsWith(".java"); } @Test void verifyProcessWithIntermediateEvent() { final CloudEventsResourceGenerator generator = new CloudEventsResourceGenerator( + buildContext, ApplicationGenerator.DEFAULT_PACKAGE_NAME, - execModelFromProcessFile("/messageevent/IntermediateCatchEventMessage.bpmn2"), - annotator); + execModelFromProcessFile("/messageevent/IntermediateCatchEventMessage.bpmn2")); final String source = generator.generate(); assertThat(source).isNotNull(); assertThat(generator.getTriggers()).hasSize(1); @@ -81,7 +81,7 @@ void verifyProcessWithIntermediateEvent() { @Test void verifyEmitterVariableNameGen() { - final CloudEventsResourceGenerator generator = new CloudEventsResourceGenerator(ApplicationGenerator.DEFAULT_PACKAGE_NAME, Collections.emptyList(), annotator); + final CloudEventsResourceGenerator generator = new CloudEventsResourceGenerator(buildContext, ApplicationGenerator.DEFAULT_PACKAGE_NAME, Collections.emptyList()); final Map tableTest = new HashMap<>(); tableTest.put("http://github.com/me/myrepo", EMITTER_PREFIX + "httpgithubcommemyrepo"); tableTest.put("$%@1234whatever123", EMITTER_PREFIX + "1234whatever123"); diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/process/events/TopicsInformationResourceGeneratorTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/process/events/TopicsInformationResourceGeneratorTest.java index 2685945e5a4..d1860316a84 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/process/events/TopicsInformationResourceGeneratorTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/process/events/TopicsInformationResourceGeneratorTest.java @@ -26,8 +26,9 @@ import org.junit.jupiter.api.Test; import org.kie.kogito.codegen.AddonsConfig; import org.kie.kogito.codegen.ApplicationGenerator; -import org.kie.kogito.codegen.di.CDIDependencyInjectionAnnotator; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; +import org.kie.kogito.codegen.context.JavaKogitoBuildContext; +import org.kie.kogito.codegen.context.KogitoBuildContext; +import org.kie.kogito.codegen.context.QuarkusKogitoBuildContext; import org.kie.kogito.codegen.process.ProcessGenerationUtils; import org.kie.kogito.event.EventKind; @@ -103,15 +104,15 @@ void verifyProcessWithoutMessageEvent() { } private ClassOrInterfaceDeclaration generateAndParseClass(String bpmnFile, int expectedTriggers, boolean withInjection) { - DependencyInjectionAnnotator annotator = null; + KogitoBuildContext buildContext = new JavaKogitoBuildContext(); if (withInjection) { - annotator = new CDIDependencyInjectionAnnotator(); + buildContext = new QuarkusKogitoBuildContext(s -> true); } final TopicsInformationResourceGenerator generator = new TopicsInformationResourceGenerator( + buildContext, ApplicationGenerator.DEFAULT_PACKAGE_NAME, ProcessGenerationUtils.execModelFromProcessFile(bpmnFile), - annotator, AddonsConfig.DEFAULT.withCloudEvents(true)); if (expectedTriggers > 0) { assertThat(generator.getTriggers()).isNotEmpty(); diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/process/persistence/MongoDBPersistenceGeneratorTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/process/persistence/MongoDBPersistenceGeneratorTest.java index 3a535a538e1..da0181aea3b 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/process/persistence/MongoDBPersistenceGeneratorTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/process/persistence/MongoDBPersistenceGeneratorTest.java @@ -35,7 +35,6 @@ import org.kie.kogito.codegen.GeneratorContext; import org.kie.kogito.codegen.context.QuarkusKogitoBuildContext; import org.kie.kogito.codegen.data.Person; -import org.kie.kogito.codegen.di.CDIDependencyInjectionAnnotator; import static com.github.javaparser.StaticJavaParser.parse; import static org.assertj.core.api.Assertions.assertThat; @@ -52,11 +51,16 @@ class MongoDBPersistenceGeneratorTest { @Test void test() { context.withBuildContext(new QuarkusKogitoBuildContext((className -> true))); - PersistenceGenerator persistenceGenerator = new PersistenceGenerator(targetDirectory.toFile(), Collections.singleton(Person.class), true, null, null, Arrays.asList("com.mongodb.client.MongoClient"), "mongodb"); + PersistenceGenerator persistenceGenerator = new PersistenceGenerator( + targetDirectory.toFile(), + Collections.singleton(Person.class), + true, + null, + null, + Arrays.asList("com.mongodb.client.MongoClient"), + "mongodb"); persistenceGenerator.setPackageName(this.getClass().getPackage().getName()); - persistenceGenerator.setDependencyInjection(null); persistenceGenerator.setContext(context); - persistenceGenerator.setDependencyInjection(new CDIDependencyInjectionAnnotator()); Collection generatedFiles = persistenceGenerator.generate(); Optional generatedCLASSFile = generatedFiles.stream().filter(gf -> gf.getType() == GeneratedFile.Type.CLASS).findFirst(); diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/rules/IncrementalRuleCodegenTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/rules/IncrementalRuleCodegenTest.java index c0534f22e48..71a85cc9140 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/rules/IncrementalRuleCodegenTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/rules/IncrementalRuleCodegenTest.java @@ -26,6 +26,7 @@ import org.kie.api.internal.utils.ServiceRegistry; import org.kie.kogito.codegen.AddonsConfig; import org.kie.kogito.codegen.GeneratedFile; +import org.kie.kogito.codegen.GeneratorContext; import org.kie.kogito.codegen.io.CollectedResource; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/BusinessRuleTaskSpringTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/BusinessRuleTaskSpringTest.java index a09fa859f61..68e5f3cae7c 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/BusinessRuleTaskSpringTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/BusinessRuleTaskSpringTest.java @@ -19,10 +19,10 @@ import org.junit.jupiter.api.Disabled; import org.kie.kogito.codegen.tests.BusinessRuleTaskTest; -@Disabled +@Disabled("KOGITO-4000") public class BusinessRuleTaskSpringTest extends BusinessRuleTaskTest { public BusinessRuleTaskSpringTest() { - withSpringContext(true); + withSpringContext(); } } diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/BusinessRuleUnitSpringTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/BusinessRuleUnitSpringTest.java index b2b23ff1fbc..210633d576a 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/BusinessRuleUnitSpringTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/BusinessRuleUnitSpringTest.java @@ -19,10 +19,10 @@ import org.junit.jupiter.api.Disabled; import org.kie.kogito.codegen.tests.BusinessRuleUnitTest; -@Disabled +@Disabled("KOGITO-4000") public class BusinessRuleUnitSpringTest extends BusinessRuleUnitTest { public BusinessRuleUnitSpringTest() { - withSpringContext(true); + withSpringContext(); } } diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/CallActivityTaskSpringTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/CallActivityTaskSpringTest.java index de1e0fe9d84..8159d473ccd 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/CallActivityTaskSpringTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/CallActivityTaskSpringTest.java @@ -19,10 +19,10 @@ import org.junit.jupiter.api.Disabled; import org.kie.kogito.codegen.tests.CallActivityTaskTest; -@Disabled +@Disabled("KOGITO-4000") public class CallActivityTaskSpringTest extends CallActivityTaskTest { public CallActivityTaskSpringTest() { - withSpringContext(true); + withSpringContext(); } } diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/EmbeddedSubProcessSpringTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/EmbeddedSubProcessSpringTest.java index c31e1de122e..4f5eb3c7169 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/EmbeddedSubProcessSpringTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/EmbeddedSubProcessSpringTest.java @@ -19,10 +19,10 @@ import org.junit.jupiter.api.Disabled; import org.kie.kogito.codegen.tests.EmbeddedSubProcessTest; -@Disabled +@Disabled("KOGITO-4000") public class EmbeddedSubProcessSpringTest extends EmbeddedSubProcessTest { public EmbeddedSubProcessSpringTest() { - withSpringContext(true); + withSpringContext(); } } diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/EventSubProcessSpringTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/EventSubProcessSpringTest.java index fd384395225..3777b437acb 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/EventSubProcessSpringTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/EventSubProcessSpringTest.java @@ -19,10 +19,10 @@ import org.junit.jupiter.api.Disabled; import org.kie.kogito.codegen.tests.EventSubProcessTest; -@Disabled +@Disabled("KOGITO-4000") public class EventSubProcessSpringTest extends EventSubProcessTest { public EventSubProcessSpringTest() { - withSpringContext(true); + withSpringContext(); } } diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/GatewaySpringTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/GatewaySpringTest.java index a446058afed..afd6cab4936 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/GatewaySpringTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/GatewaySpringTest.java @@ -19,10 +19,10 @@ import org.junit.jupiter.api.Disabled; import org.kie.kogito.codegen.tests.GatewayTest; -@Disabled +@Disabled("KOGITO-4000") public class GatewaySpringTest extends GatewayTest { public GatewaySpringTest() { - withSpringContext(true); + withSpringContext(); } } diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/InvalidProcessSpringTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/InvalidProcessSpringTest.java index 2a2d9c75502..e622c4f79bd 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/InvalidProcessSpringTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/InvalidProcessSpringTest.java @@ -19,10 +19,10 @@ import org.junit.jupiter.api.Disabled; import org.kie.kogito.codegen.tests.InvalidProcessTest; -@Disabled +@Disabled("KOGITO-4000") public class InvalidProcessSpringTest extends InvalidProcessTest { public InvalidProcessSpringTest() { - withSpringContext(true); + withSpringContext(); } } diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/MessageIntermediateEventSpringTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/MessageIntermediateEventSpringTest.java index 246f94c99b2..986ecf50a33 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/MessageIntermediateEventSpringTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/MessageIntermediateEventSpringTest.java @@ -19,10 +19,10 @@ import org.junit.jupiter.api.Disabled; import org.kie.kogito.codegen.tests.MessageIntermediateEventTest; -@Disabled +@Disabled("KOGITO-4000") public class MessageIntermediateEventSpringTest extends MessageIntermediateEventTest { public MessageIntermediateEventSpringTest() { - withSpringContext(true); + withSpringContext(); } } diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/MessageStartEventSpringTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/MessageStartEventSpringTest.java index 0701b933368..c6cd9ec9d3c 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/MessageStartEventSpringTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/MessageStartEventSpringTest.java @@ -19,10 +19,10 @@ import org.junit.jupiter.api.Disabled; import org.kie.kogito.codegen.tests.MessageStartEventTest; -@Disabled +@Disabled("KOGITO-4000") public class MessageStartEventSpringTest extends MessageStartEventTest { public MessageStartEventSpringTest() { - withSpringContext(true); + withSpringContext(); } } diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/PublishEventSpringTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/PublishEventSpringTest.java index 36dc6544e97..cc8dc045c8d 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/PublishEventSpringTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/PublishEventSpringTest.java @@ -19,10 +19,10 @@ import org.junit.jupiter.api.Disabled; import org.kie.kogito.codegen.tests.PublishEventTest; -@Disabled +@Disabled("KOGITO-4000") public class PublishEventSpringTest extends PublishEventTest { public PublishEventSpringTest() { - withSpringContext(true); + withSpringContext(); } } diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/ServiceTaskSpringTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/ServiceTaskSpringTest.java index 19368534b07..839439cd71a 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/ServiceTaskSpringTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/ServiceTaskSpringTest.java @@ -19,10 +19,10 @@ import org.junit.jupiter.api.Disabled; import org.kie.kogito.codegen.tests.ServiceTaskTest; -@Disabled +@Disabled("KOGITO-4000") public class ServiceTaskSpringTest extends ServiceTaskTest { public ServiceTaskSpringTest() { - withSpringContext(true); + withSpringContext(); } } diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/SignalEventSpringTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/SignalEventSpringTest.java index 0b395f187b5..0422dda05af 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/SignalEventSpringTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/SignalEventSpringTest.java @@ -19,10 +19,10 @@ import org.junit.jupiter.api.Disabled; import org.kie.kogito.codegen.tests.SignalEventTest; -@Disabled +@Disabled("KOGITO-4000") public class SignalEventSpringTest extends SignalEventTest { public SignalEventSpringTest() { - withSpringContext(true); + withSpringContext(); } } diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/TimerEventSpringTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/TimerEventSpringTest.java index a28fefda1c3..f9d318ebddc 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/TimerEventSpringTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/TimerEventSpringTest.java @@ -19,10 +19,10 @@ import org.junit.jupiter.api.Disabled; import org.kie.kogito.codegen.tests.TimerEventTest; -@Disabled +@Disabled("KOGITO-4000") public class TimerEventSpringTest extends TimerEventTest { public TimerEventSpringTest() { - withSpringContext(true); + withSpringContext(); } } diff --git a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/UserTaskSpringTest.java b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/UserTaskSpringTest.java index 544aadb74b7..f0a345b2ac5 100644 --- a/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/UserTaskSpringTest.java +++ b/kogito-codegen/src/test/java/org/kie/kogito/codegen/tests/spring/UserTaskSpringTest.java @@ -23,11 +23,11 @@ import org.kie.kogito.codegen.tests.UserTaskTest; import org.springframework.web.bind.annotation.PostMapping; -@Disabled +@Disabled("KOGITO-4000") public class UserTaskSpringTest extends UserTaskTest { public UserTaskSpringTest() { - withSpringContext(true); + withSpringContext(); } private class Dummy { diff --git a/kogito-maven-plugin/src/main/java/org/kie/kogito/maven/plugin/AbstractKieMojo.java b/kogito-maven-plugin/src/main/java/org/kie/kogito/maven/plugin/AbstractKieMojo.java index 3f2af187217..ee340438e9e 100644 --- a/kogito-maven-plugin/src/main/java/org/kie/kogito/maven/plugin/AbstractKieMojo.java +++ b/kogito-maven-plugin/src/main/java/org/kie/kogito/maven/plugin/AbstractKieMojo.java @@ -24,12 +24,10 @@ import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.project.MavenProject; +import org.kie.kogito.codegen.context.JavaKogitoBuildContext; import org.kie.kogito.codegen.context.KogitoBuildContext; import org.kie.kogito.codegen.context.QuarkusKogitoBuildContext; import org.kie.kogito.codegen.context.SpringBootKogitoBuildContext; -import org.kie.kogito.codegen.di.CDIDependencyInjectionAnnotator; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; -import org.kie.kogito.codegen.di.SpringDependencyInjectionAnnotator; public abstract class AbstractKieMojo extends AbstractMojo { @@ -44,19 +42,11 @@ protected void setSystemProperties(Map properties) { } } - protected DependencyInjectionAnnotator discoverDependencyInjectionAnnotator(MavenProject project) { - switch (discoverFramework(project)) { - case QUARKUS: return new CDIDependencyInjectionAnnotator(); - case SPRING: return new SpringDependencyInjectionAnnotator(); - default: return null; - } - } - protected KogitoBuildContext discoverKogitoRuntimeContext(MavenProject project) { switch (discoverFramework(project)) { case QUARKUS: return new QuarkusKogitoBuildContext(fqcn -> hasClassOnClasspath(project, fqcn)); case SPRING: return new SpringBootKogitoBuildContext(fqcn -> hasClassOnClasspath(project, fqcn)); - default: return null; + default: return new JavaKogitoBuildContext(fqcn -> hasClassOnClasspath(project, fqcn)); } } diff --git a/kogito-maven-plugin/src/main/java/org/kie/kogito/maven/plugin/GenerateDeclaredTypes.java b/kogito-maven-plugin/src/main/java/org/kie/kogito/maven/plugin/GenerateDeclaredTypes.java index ea6f3fecf5d..f843613a6c4 100644 --- a/kogito-maven-plugin/src/main/java/org/kie/kogito/maven/plugin/GenerateDeclaredTypes.java +++ b/kogito-maven-plugin/src/main/java/org/kie/kogito/maven/plugin/GenerateDeclaredTypes.java @@ -155,10 +155,8 @@ private ApplicationGenerator createApplicationGenerator( context.withBuildContext(discoverKogitoRuntimeContext(project)); ApplicationGenerator appGen = - new ApplicationGenerator(appPackageName, targetDirectory) - .withDependencyInjection(discoverDependencyInjectionAnnotator(project)) - .withClassLoader(projectClassLoader) - .withGeneratorContext(context); + new ApplicationGenerator(context, appPackageName, targetDirectory) + .withClassLoader(projectClassLoader); if (generateRuleUnits) { appGen.setupGenerator(DeclaredTypeCodegen.ofPath(kieSourcesDirectory.toPath())) diff --git a/kogito-maven-plugin/src/main/java/org/kie/kogito/maven/plugin/GenerateModelMojo.java b/kogito-maven-plugin/src/main/java/org/kie/kogito/maven/plugin/GenerateModelMojo.java index 6bba56ac894..a3c68dc7cf3 100644 --- a/kogito-maven-plugin/src/main/java/org/kie/kogito/maven/plugin/GenerateModelMojo.java +++ b/kogito-maven-plugin/src/main/java/org/kie/kogito/maven/plugin/GenerateModelMojo.java @@ -50,7 +50,6 @@ import org.kie.kogito.codegen.GeneratorContext; import org.kie.kogito.codegen.DashboardGeneratedFileUtils; import org.kie.kogito.codegen.decision.DecisionCodegen; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; import org.kie.kogito.codegen.io.CollectedResource; import org.kie.kogito.codegen.prediction.PredictionCodegen; import org.kie.kogito.codegen.process.ProcessCodegen; @@ -242,7 +241,6 @@ private ApplicationGenerator createApplicationGenerator() throws IOException, Mo boolean useTracing = hasClassOnClasspath(project, "org.kie.kogito.tracing.decision.DecisionTracingListener"); boolean useKnativeEventing = hasClassOnClasspath(project, "org.kie.kogito.events.knative.ce.extensions.KogitoProcessExtension"); boolean useCloudEvents = hasClassOnClasspath(project, "org.kie.kogito.addon.cloudevents.AbstractTopicDiscovery"); - DependencyInjectionAnnotator dependencyInjectionAnnotator = discoverDependencyInjectionAnnotator(project); AddonsConfig addonsConfig = new AddonsConfig() .withPersistence(usePersistence) @@ -261,11 +259,9 @@ private ApplicationGenerator createApplicationGenerator() throws IOException, Mo context.withBuildContext(discoverKogitoRuntimeContext(project)); ApplicationGenerator appGen = - new ApplicationGenerator(appPackageName, targetDirectory) - .withDependencyInjection(dependencyInjectionAnnotator) + new ApplicationGenerator(context, appPackageName, targetDirectory) .withAddons(addonsConfig) - .withClassLoader(projectClassLoader) - .withGeneratorContext(context); + .withClassLoader(projectClassLoader); // if unspecified, then default to checking for file type existence // if not null, the property has been overridden, and we should use the specified value diff --git a/kogito-maven-plugin/src/main/java/org/kie/kogito/maven/plugin/ProcessClassesMojo.java b/kogito-maven-plugin/src/main/java/org/kie/kogito/maven/plugin/ProcessClassesMojo.java index c87da138f11..15a8468bcd5 100644 --- a/kogito-maven-plugin/src/main/java/org/kie/kogito/maven/plugin/ProcessClassesMojo.java +++ b/kogito-maven-plugin/src/main/java/org/kie/kogito/maven/plugin/ProcessClassesMojo.java @@ -15,7 +15,6 @@ package org.kie.kogito.maven.plugin; - import java.io.File; import java.io.IOException; import java.lang.reflect.Type; @@ -121,7 +120,6 @@ public void execute() throws MojoExecutionException { String persistenceType = context.getApplicationProperty("kogito.persistence.type").orElse(PersistenceGenerator.DEFAULT_PERSISTENCE_TYPE); PersistenceGenerator persistenceGenerator = new PersistenceGenerator(new File(project.getBuild().getDirectory()), modelClasses, !classes.isEmpty(), new ReflectionProtoGenerator(), cl, parameters, persistenceType); persistenceGenerator.setPackageName(appPackageName); - persistenceGenerator.setDependencyInjection(discoverDependencyInjectionAnnotator(project)); persistenceGenerator.setContext(context); Collection generatedFiles = persistenceGenerator.generate(); generatedFiles = generatedFiles.stream().filter(x -> x.getType().equals(GeneratedFile.Type.CLASS)).collect(Collectors.toList()); diff --git a/kogito-quarkus-extension/deployment/src/main/java/org/kie/kogito/quarkus/deployment/KogitoAssetsProcessor.java b/kogito-quarkus-extension/deployment/src/main/java/org/kie/kogito/quarkus/deployment/KogitoAssetsProcessor.java index 66984913153..d83f8f43ecd 100644 --- a/kogito-quarkus-extension/deployment/src/main/java/org/kie/kogito/quarkus/deployment/KogitoAssetsProcessor.java +++ b/kogito-quarkus-extension/deployment/src/main/java/org/kie/kogito/quarkus/deployment/KogitoAssetsProcessor.java @@ -76,8 +76,6 @@ import org.kie.kogito.codegen.JsonSchemaGenerator; import org.kie.kogito.codegen.context.QuarkusKogitoBuildContext; import org.kie.kogito.codegen.decision.DecisionCodegen; -import org.kie.kogito.codegen.di.CDIDependencyInjectionAnnotator; -import org.kie.kogito.codegen.di.DependencyInjectionAnnotator; import org.kie.kogito.codegen.io.CollectedResource; import org.kie.kogito.codegen.prediction.PredictionCodegen; import org.kie.kogito.codegen.process.ProcessCodegen; @@ -169,8 +167,6 @@ public void generateModel( boolean useCloudEvents = combinedIndexBuildItem.getIndex().getClassByName(quarkusCloudEvents) != null; boolean useProcessSVG = combinedIndexBuildItem.getIndex().getClassByName(quarkusSVGService) != null; - DependencyInjectionAnnotator dependencyInjectionAnnotator = new CDIDependencyInjectionAnnotator(); - AddonsConfig addonsConfig = new AddonsConfig() .withPersistence(usePersistence) .withMonitoring(useMonitoring) @@ -188,11 +184,10 @@ public void generateModel( ApplicationGenerator appGen = new ApplicationGenerator( + context, appPackageName, new File(appPaths.getFirstProjectPath().toFile(), "target")) - .withDependencyInjection(dependencyInjectionAnnotator) - .withAddons(addonsConfig) - .withGeneratorContext(context); + .withAddons(addonsConfig); // configure each individual generator. Ordering is relevant. @@ -413,7 +408,6 @@ private PersistenceGenerator makePersistenceGenerator( jandexProtoGenerator, parameters, persistenceType); - persistenceGenerator.setDependencyInjection(new CDIDependencyInjectionAnnotator()); persistenceGenerator.setPackageName(appPackageName); persistenceGenerator.setContext(context); return persistenceGenerator; diff --git a/kogito-quarkus-extension/deployment/src/main/java/org/kie/kogito/quarkus/deployment/KogitoCompilationProvider.java b/kogito-quarkus-extension/deployment/src/main/java/org/kie/kogito/quarkus/deployment/KogitoCompilationProvider.java index d929bdf8ad3..41dc4935f80 100644 --- a/kogito-quarkus-extension/deployment/src/main/java/org/kie/kogito/quarkus/deployment/KogitoCompilationProvider.java +++ b/kogito-quarkus-extension/deployment/src/main/java/org/kie/kogito/quarkus/deployment/KogitoCompilationProvider.java @@ -38,7 +38,6 @@ import org.kie.kogito.codegen.Generator; import org.kie.kogito.codegen.GeneratorContext; import org.kie.kogito.codegen.context.QuarkusKogitoBuildContext; -import org.kie.kogito.codegen.di.CDIDependencyInjectionAnnotator; public abstract class KogitoCompilationProvider extends JavaCompilationProvider { @@ -66,9 +65,7 @@ public final void compile(Set filesToCompile, Context context) { generationContext .withBuildContext(new QuarkusKogitoBuildContext(className -> hasClassOnClasspath(cl, className))); - ApplicationGenerator appGen = new ApplicationGenerator(appPackageName, outputDirectory) - .withDependencyInjection(new CDIDependencyInjectionAnnotator()) - .withGeneratorContext(generationContext); + ApplicationGenerator appGen = new ApplicationGenerator(generationContext, appPackageName, outputDirectory); addGenerator(appGen, filesToCompile, context, cl);