Search in sources :

Example 6 with CollectedResource

use of org.kie.kogito.codegen.api.io.CollectedResource in project kogito-runtimes by kiegroup.

the class CollectedResourceProducer method fromPaths.

/**
 * Returns a collection of CollectedResource from the given paths.
 * If a path is a jar, then walks inside the jar.
 */
public static Collection<CollectedResource> fromPaths(Path... paths) {
    Collection<CollectedResource> resources = new ArrayList<>();
    for (Path path : paths) {
        if (path.toFile().isDirectory()) {
            Collection<CollectedResource> res = fromDirectory(path);
            resources.addAll(res);
        } else if (path.getFileName().toString().endsWith(".jar") || path.getFileName().toString().endsWith(".jar.original")) {
            Collection<CollectedResource> res = fromJarFile(path);
            resources.addAll(res);
        } else if (!path.toFile().exists()) {
            LOGGER.debug("Skipping '{}' because doesn't exist", path);
        } else {
            throw new IllegalArgumentException("Expected directory or archive, file given: " + path);
        }
    }
    return resources;
}
Also used : Path(java.nio.file.Path) CollectedResource(org.kie.kogito.codegen.api.io.CollectedResource) ArrayList(java.util.ArrayList) Collection(java.util.Collection)

Example 7 with CollectedResource

use of org.kie.kogito.codegen.api.io.CollectedResource in project kogito-runtimes by kiegroup.

the class CollectedResourceProducer method fromJarFile.

/**
 * Returns a collection of CollectedResource from the given jar file.
 */
public static Collection<CollectedResource> fromJarFile(Path jarPath) {
    Collection<CollectedResource> resources = new ArrayList<>();
    try (ZipFile zipFile = new ZipFile(jarPath.toFile())) {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            InternalResource resource = new ByteArrayResource(readBytesFromInputStream(zipFile.getInputStream(entry)));
            resource.setSourcePath(entry.getName());
            resources.add(toCollectedResource(jarPath, entry.getName(), resource));
        }
        return resources;
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
Also used : CollectedResource(org.kie.kogito.codegen.api.io.CollectedResource) InternalResource(org.drools.core.io.internal.InternalResource) ZipFile(java.util.zip.ZipFile) ZipEntry(java.util.zip.ZipEntry) ArrayList(java.util.ArrayList) UncheckedIOException(java.io.UncheckedIOException) ByteArrayResource(org.drools.core.io.impl.ByteArrayResource) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException)

Example 8 with CollectedResource

use of org.kie.kogito.codegen.api.io.CollectedResource in project kogito-runtimes by kiegroup.

the class DecisionModelResourcesProviderGeneratorTest method generateDecisionModelResourcesProvider.

@Test
public void generateDecisionModelResourcesProvider() {
    final KogitoBuildContext context = QuarkusKogitoBuildContext.builder().withAddonsConfig(AddonsConfig.builder().withTracing(true).build()).build();
    final Collection<CollectedResource> collectedResources = CollectedResourceProducer.fromPaths(Paths.get("src/test/resources/decision/models/vacationDays").toAbsolutePath(), Paths.get("src/test/resources/decision/models/vacationDaysAlt").toAbsolutePath());
    final long numberOfModels = collectedResources.stream().filter(r -> r.resource().getResourceType() == ResourceType.DMN).count();
    final DecisionCodegen codeGenerator = DecisionCodegen.ofCollectedResources(context, collectedResources);
    final Collection<GeneratedFile> generatedFiles = codeGenerator.generate();
    // the two resources below, see https://github.com/kiegroup/kogito-runtimes/commit/18ec525f530b1ff1bddcf18c0083f14f86aff171#diff-edd3a09d62dc627ee10fe37925944217R53
    assertThat(generatedFiles.size()).isGreaterThanOrEqualTo(2);
    // Align this FAI-215 test (#621) with unknown order of generated files (ie.: additional generated files might be present)
    // A Rest endpoint is always generated per model.
    List<GeneratedFile> generatedRESTFiles = generatedFiles.stream().filter(gf -> gf.type().equals(AbstractGenerator.REST_TYPE)).collect(toList());
    assertFalse(generatedRESTFiles.isEmpty());
    assertEquals(numberOfModels, generatedRESTFiles.size());
    List<GeneratedFile> generatedCLASSFile = generatedFiles.stream().filter(gf -> gf.type().equals(GeneratedFileType.SOURCE)).collect(toList());
    assertEquals(1, generatedCLASSFile.size());
    GeneratedFile classFile = generatedCLASSFile.get(0);
    assertEquals("org/kie/kogito/app/DecisionModelResourcesProvider.java", classFile.relativePath());
    final CompilationUnit compilationUnit = parse(new ByteArrayInputStream(classFile.contents()));
    final ClassOrInterfaceDeclaration classDeclaration = compilationUnit.findFirst(ClassOrInterfaceDeclaration.class).orElseThrow(() -> new NoSuchElementException("Compilation unit doesn't contain a class or interface declaration!"));
    assertNotNull(classDeclaration);
    final MethodDeclaration methodDeclaration = classDeclaration.findFirst(MethodDeclaration.class, d -> d.getName().getIdentifier().equals("getResources")).orElseThrow(() -> new NoSuchElementException("Class declaration doesn't contain a method named \"getResources\"!"));
    assertNotNull(methodDeclaration);
    assertTrue(methodDeclaration.getBody().isPresent());
    final BlockStmt body = methodDeclaration.getBody().get();
    assertTrue(body.getStatements().size() > 2);
    assertTrue(body.getStatements().get(1).isExpressionStmt());
    final ExpressionStmt expression = (ExpressionStmt) body.getStatements().get(1);
    assertTrue(expression.getExpression() instanceof MethodCallExpr);
    final MethodCallExpr call = (MethodCallExpr) expression.getExpression();
    assertEquals("add", call.getName().getIdentifier());
    assertTrue(call.getScope().isPresent());
    assertTrue(call.getScope().get().isNameExpr());
    final NameExpr nameExpr = call.getScope().get().asNameExpr();
    assertEquals("resourcePaths", nameExpr.getName().getIdentifier());
    long numberOfAddStms = body.getStatements().stream().filter(this::isAddStatement).count();
    assertEquals(numberOfModels, numberOfAddStms);
    List<NodeList<Expression>> defaultDecisionModelResources = body.getStatements().stream().filter(this::isAddStatement).map(stm -> stm.asExpressionStmt().getExpression().asMethodCallExpr().getArguments()).collect(toList());
    // verify .add(..) number of parameters
    defaultDecisionModelResources.forEach(nodeList -> assertEquals(1, nodeList.size()));
    Set<String> distinctDefaultDecisionModelResources = defaultDecisionModelResources.stream().map(nodeList -> nodeList.get(0).toString()).collect(toSet());
    assertEquals(defaultDecisionModelResources.size(), distinctDefaultDecisionModelResources.size());
}
Also used : Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) ExpressionStmt(com.github.javaparser.ast.stmt.ExpressionStmt) StaticJavaParser.parse(com.github.javaparser.StaticJavaParser.parse) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ResourceType(org.kie.api.io.ResourceType) ByteArrayInputStream(java.io.ByteArrayInputStream) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) CollectedResource(org.kie.kogito.codegen.api.io.CollectedResource) AbstractGenerator(org.kie.kogito.codegen.core.AbstractGenerator) Expression(com.github.javaparser.ast.expr.Expression) CompilationUnit(com.github.javaparser.ast.CompilationUnit) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) NoSuchElementException(java.util.NoSuchElementException) Collectors.toSet(java.util.stream.Collectors.toSet) AddonsConfig(org.kie.kogito.codegen.api.AddonsConfig) NodeList(com.github.javaparser.ast.NodeList) KogitoBuildContext(org.kie.kogito.codegen.api.context.KogitoBuildContext) GeneratedFileType(org.kie.kogito.codegen.api.GeneratedFileType) Collection(java.util.Collection) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr) Set(java.util.Set) NameExpr(com.github.javaparser.ast.expr.NameExpr) Statement(com.github.javaparser.ast.stmt.Statement) Test(org.junit.jupiter.api.Test) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) QuarkusKogitoBuildContext(org.kie.kogito.codegen.api.context.impl.QuarkusKogitoBuildContext) Paths(java.nio.file.Paths) CollectedResourceProducer(org.kie.kogito.codegen.core.io.CollectedResourceProducer) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) GeneratedFile(org.kie.kogito.codegen.api.GeneratedFile) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) CompilationUnit(com.github.javaparser.ast.CompilationUnit) CollectedResource(org.kie.kogito.codegen.api.io.CollectedResource) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) NodeList(com.github.javaparser.ast.NodeList) NameExpr(com.github.javaparser.ast.expr.NameExpr) GeneratedFile(org.kie.kogito.codegen.api.GeneratedFile) ExpressionStmt(com.github.javaparser.ast.stmt.ExpressionStmt) ByteArrayInputStream(java.io.ByteArrayInputStream) KogitoBuildContext(org.kie.kogito.codegen.api.context.KogitoBuildContext) QuarkusKogitoBuildContext(org.kie.kogito.codegen.api.context.impl.QuarkusKogitoBuildContext) NoSuchElementException(java.util.NoSuchElementException) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr) Test(org.junit.jupiter.api.Test)

Example 9 with CollectedResource

use of org.kie.kogito.codegen.api.io.CollectedResource in project kogito-runtimes by kiegroup.

the class OpenApiClientServerlessWorkflowIT method openApiSpecInClasspath.

@ParameterizedTest
@ValueSource(strings = { "openapi/petstore-classpath.sw.json" })
public void openApiSpecInClasspath(final String resource) {
    final KogitoBuildContext context = this.newContext();
    final Collection<CollectedResource> resources = toCollectedResources(Collections.singletonList(resource));
    // OpenApi Generation
    final OpenApiClientCodegen openApiClientCodegen = OpenApiClientCodegen.ofCollectedResources(context, resources);
    assertThat(openApiClientCodegen.getOpenAPISpecResources()).isNotEmpty();
    Collection<GeneratedFile> openApiGeneratedFiles = openApiClientCodegen.generate();
    assertThat(openApiGeneratedFiles).isNotEmpty();
    assertThat(context.getContextAttribute(ContextAttributesConstants.OPENAPI_DESCRIPTORS, List.class)).isNotEmpty();
    // Process Code Generation
    final ProcessCodegen processCodegen = ProcessCodegen.ofCollectedResources(context, resources);
    Collection<GeneratedFile> processGeneratedFiles = processCodegen.generate();
    assertThat(processGeneratedFiles).isNotEmpty();
}
Also used : CollectedResource(org.kie.kogito.codegen.api.io.CollectedResource) KogitoBuildContext(org.kie.kogito.codegen.api.context.KogitoBuildContext) OpenApiClientCodegen(org.kie.kogito.codegen.openapi.client.OpenApiClientCodegen) GeneratedFile(org.kie.kogito.codegen.api.GeneratedFile) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 10 with CollectedResource

use of org.kie.kogito.codegen.api.io.CollectedResource in project kogito-runtimes by kiegroup.

the class ProcessCodegen method processSVG.

private static void processSVG(FileSystemResource resource, Collection<CollectedResource> resources, Collection<Process> processes, Map<String, String> processSVGMap) {
    File f = resource.getFile();
    String processFileCompleteName = f.getName();
    String fileName = processFileCompleteName.substring(0, processFileCompleteName.lastIndexOf("."));
    processes.stream().forEach(process -> {
        if (isFilenameValid(process.getId() + ".svg")) {
            resources.stream().filter(r -> r.resource().getSourcePath().endsWith(String.format(SVG_EXPORT_NAME_EXPRESION, fileName))).forEach(svg -> {
                try {
                    processSVGMap.put(process.getId(), new String(Files.readAllBytes(Paths.get(svg.resource().getSourcePath()))));
                } catch (IOException e) {
                    LOGGER.error("\n IOException trying to add " + svg.resource().getSourcePath() + " with processId:" + process.getId() + "\n" + e.getMessage(), e);
                }
            });
        }
    });
}
Also used : Arrays(java.util.Arrays) ServerlessWorkflowParser(org.kie.kogito.serverless.workflow.parser.ServerlessWorkflowParser) ProcessToExecModelGenerator(org.jbpm.compiler.canonical.ProcessToExecModelGenerator) XmlProcessReader(org.jbpm.compiler.xml.XmlProcessReader) LoggerFactory(org.slf4j.LoggerFactory) ProcessCloudEventMetaFactoryGenerator(org.kie.kogito.codegen.process.events.ProcessCloudEventMetaFactoryGenerator) FileSystemResource(org.drools.core.io.impl.FileSystemResource) BPMNSemanticModule(org.jbpm.bpmn2.xml.BPMNSemanticModule) CollectedResource(org.kie.kogito.codegen.api.io.CollectedResource) Map(java.util.Map) SemanticModules(org.drools.core.xml.SemanticModules) ModelMetaData(org.jbpm.compiler.canonical.ModelMetaData) KogitoBuildContext(org.kie.kogito.codegen.api.context.KogitoBuildContext) GeneratedFileType(org.kie.kogito.codegen.api.GeneratedFileType) ValidationLogDecorator(org.kie.kogito.process.validation.ValidationLogDecorator) Collection(java.util.Collection) Process(org.kie.api.definition.process.Process) Set(java.util.Set) ApplicationSection(org.kie.kogito.codegen.api.ApplicationSection) Reader(java.io.Reader) BPMNDISemanticModule(org.jbpm.bpmn2.xml.BPMNDISemanticModule) String.format(java.lang.String.format) Resource(org.kie.api.io.Resource) BPMNExtensionsSemanticModule(org.jbpm.bpmn2.xml.BPMNExtensionsSemanticModule) List(java.util.List) Stream(java.util.stream.Stream) ProcessConfigGenerator(org.kie.kogito.codegen.process.config.ProcessConfigGenerator) SAXException(org.xml.sax.SAXException) Optional(java.util.Optional) GeneratedFile(org.kie.kogito.codegen.api.GeneratedFile) ValidationException(org.kie.kogito.process.validation.ValidationException) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) StringUtils(org.drools.core.util.StringUtils) TriggerMetaData(org.jbpm.compiler.canonical.TriggerMetaData) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ProcessValidatorRegistry(org.jbpm.process.core.validation.ProcessValidatorRegistry) WorkflowProcess(org.kie.api.definition.process.WorkflowProcess) ContextAttributesConstants(org.kie.kogito.codegen.api.context.ContextAttributesConstants) ValidationContext(org.kie.kogito.process.validation.ValidationContext) GrafanaConfigurationWriter.generateOperationalDashboard(org.kie.kogito.grafana.GrafanaConfigurationWriter.generateOperationalDashboard) UserTaskModelMetaData(org.jbpm.compiler.canonical.UserTaskModelMetaData) AbstractGenerator(org.kie.kogito.codegen.core.AbstractGenerator) GrafanaConfigurationWriter.buildDashboardName(org.kie.kogito.grafana.GrafanaConfigurationWriter.buildDashboardName) OpenApiClientWorkItemIntrospector(org.kie.kogito.codegen.process.openapi.OpenApiClientWorkItemIntrospector) Logger(org.slf4j.Logger) Files(java.nio.file.Files) IOException(java.io.IOException) File(java.io.File) GeneratedInfo(org.kie.kogito.codegen.api.GeneratedInfo) ProcessMetaData(org.jbpm.compiler.canonical.ProcessMetaData) Collectors.toList(java.util.stream.Collectors.toList) KogitoGAV(org.kie.kogito.KogitoGAV) Paths(java.nio.file.Paths) DashboardGeneratedFileUtils(org.kie.kogito.codegen.core.DashboardGeneratedFileUtils) KogitoWorkflowProcess(org.kie.kogito.internal.process.runtime.KogitoWorkflowProcess) Collections(java.util.Collections) IOException(java.io.IOException) GeneratedFile(org.kie.kogito.codegen.api.GeneratedFile) File(java.io.File)

Aggregations

CollectedResource (org.kie.kogito.codegen.api.io.CollectedResource)15 KogitoBuildContext (org.kie.kogito.codegen.api.context.KogitoBuildContext)12 GeneratedFile (org.kie.kogito.codegen.api.GeneratedFile)10 List (java.util.List)9 Collection (java.util.Collection)8 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)8 ArrayList (java.util.ArrayList)7 MethodSource (org.junit.jupiter.params.provider.MethodSource)7 GeneratedFileType (org.kie.kogito.codegen.api.GeneratedFileType)5 File (java.io.File)4 Path (java.nio.file.Path)4 Paths (java.nio.file.Paths)4 Optional (java.util.Optional)4 Collectors (java.util.stream.Collectors)4 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)4 Test (org.junit.jupiter.api.Test)4 CollectedResourceProducer (org.kie.kogito.codegen.core.io.CollectedResourceProducer)4 CompilationUnit (com.github.javaparser.ast.CompilationUnit)3 Collectors.toList (java.util.stream.Collectors.toList)3 AbstractGenerator (org.kie.kogito.codegen.core.AbstractGenerator)3