Search in sources :

Example 96 with InternalKieModule

use of org.drools.compiler.kie.builder.impl.InternalKieModule in project drools by kiegroup.

the class KieCDIExtension method addKBaseBean.

public void addKBaseBean(AfterBeanDiscovery abd, KieCDIEntry entry) {
    ReleaseId releaseId = entry.getReleaseId();
    // default to classpath, but allow it to be overridden
    KieContainerImpl kieContainer = classpathKContainer;
    if (releaseId != null) {
        kieContainer = (KieContainerImpl) gavs.get(releaseId);
        if (kieContainer == null) {
            log.error("Unable to create @KBase({}), could not retrieve KieContainer for ReleaseId {}", entry.getValue(), releaseId.toString());
            return;
        }
    }
    KieProject kProject = kieContainer.getKieProject();
    KieBaseModel kBaseModel = null;
    String kBaseQName = entry.getValue();
    if (StringUtils.isEmpty(kBaseQName)) {
        kBaseModel = kProject.getDefaultKieBaseModel();
    } else {
        kBaseModel = kProject.getKieBaseModel(kBaseQName);
    }
    if (kBaseModel == null) {
        log.error("Annotation @KBase({}) found, but no KieBaseModel exists.\nEither the required kmodule.xml does not exist, is corrupted, or is missing the KieBase entry", kBaseQName);
        return;
    }
    if (!kBaseModel.getScope().trim().equals(entry.getScope().getClass().getName())) {
        try {
            if (kBaseModel.getScope().indexOf('.') >= 0) {
                entry.setScope((Class<? extends Annotation>) Class.forName(kBaseModel.getScope()));
            } else {
                entry.setScope((Class<? extends Annotation>) Class.forName("javax.enterprise.context." + kBaseModel.getScope()));
            }
        } catch (ClassNotFoundException e) {
            log.error("KieBaseModule {} overrides default annotation, but it was not able to find it {}\n{}", new String[] { kBaseQName, kBaseModel.getScope(), e.getMessage() });
        }
    }
    KBaseBean bean = new KBaseBean(kBaseQName, kBaseModel, kieContainer, entry.getKReleaseId(), entry.getScope(), entry.getName(), entry.getInjectionPoints());
    if (log.isDebugEnabled()) {
        InternalKieModule kModule = kProject.getKieModuleForKBase(kBaseQName);
        log.debug("Added Bean for @KBase({})", kBaseQName, kModule);
    }
    abd.addBean(bean);
}
Also used : KieBaseModel(org.kie.api.builder.model.KieBaseModel) KieProject(org.drools.compiler.kie.builder.impl.KieProject) KieContainerImpl(org.drools.compiler.kie.builder.impl.KieContainerImpl) KReleaseId(org.kie.api.cdi.KReleaseId) ReleaseId(org.kie.api.builder.ReleaseId) InternalKieModule(org.drools.compiler.kie.builder.impl.InternalKieModule)

Example 97 with InternalKieModule

use of org.drools.compiler.kie.builder.impl.InternalKieModule in project drools by kiegroup.

the class BuildFromKJarTest method createKieModule.

private InternalKieModule createKieModule(KieServices ks, ReleaseId releaseId) {
    KieFileSystem kfs = ks.newKieFileSystem();
    kfs.writeKModuleXML(getDefaultKieModuleModel(ks).toXML());
    kfs.writePomXML(KJARUtils.getPom(releaseId));
    String javaSrc = Person.class.getCanonicalName().replace('.', '/') + ".java";
    Resource javaResource = ks.getResources().newFileSystemResource("src/test/java/" + javaSrc);
    kfs.write("src/main/java/" + javaSrc, javaResource);
    kfs.write("src/main/resources/rule.drl", getRule());
    KieBuilder kieBuilder = ks.newKieBuilder(kfs);
    List<Message> messages = ((KieBuilderImpl) kieBuilder).buildAll(ExecutableModelProject.class).getResults().getMessages();
    if (!messages.isEmpty()) {
        fail(messages.toString());
    }
    return (InternalKieModule) kieBuilder.getKieModule();
}
Also used : KieBuilderImpl(org.drools.compiler.kie.builder.impl.KieBuilderImpl) KieFileSystem(org.kie.api.builder.KieFileSystem) Message(org.kie.api.builder.Message) Resource(org.kie.api.io.Resource) KieBuilder(org.kie.api.builder.KieBuilder) InternalKieModule(org.drools.compiler.kie.builder.impl.InternalKieModule)

Example 98 with InternalKieModule

use of org.drools.compiler.kie.builder.impl.InternalKieModule in project drools by kiegroup.

the class GenerateModel method generate.

public void generate() throws IOException {
    KieServices ks = KieServices.Factory.get();
    final KieBuilderImpl kieBuilder = (KieBuilderImpl) ks.newKieBuilder(kieDmnValidationBaseDir);
    kieBuilder.buildAll(ValidationBootstrapProject::new, s -> !s.contains("src/test/java") && !s.contains("src\\test\\java") && // <- to break circularity which is only caused by the KieBuilder trying to early compile everything by itself
    !s.contains("DMNValidator") && !s.contains("dtanalysis"));
    Results results = kieBuilder.getResults();
    results.getMessages().forEach(m -> LOG.info("{}", m.toString()));
    InternalKieModule kieModule = (InternalKieModule) kieBuilder.getKieModule();
    List<String> generatedFiles = kieModule.getFileNames().stream().filter(f -> f.endsWith("java")).collect(Collectors.toList());
    LOG.info("Executable model will result in {} code generated files...", generatedFiles.size());
    generatedFiles.forEach(LOG::debug);
    MemoryFileSystem mfs = ((MemoryKieModule) ((CanonicalKieModule) kieModule).getInternalKieModule()).getMemoryFileSystem();
    for (String generatedFile : generatedFiles) {
        final MemoryFile f = (MemoryFile) mfs.getFile(generatedFile);
        final Path newFile = Paths.get(kieDmnValidationBaseDir.getAbsolutePath(), "target", "generated-sources", "bootstrap", f.getPath().asString());
        try {
            // NOSONAR javasecurity:S2083 base dir kieDmnValidationBaseDir is provided as configuration by design, static analysis exclusion applies to these 3 lines
            Files.deleteIfExists(newFile);
            // NOSONAR
            Files.createDirectories(newFile.getParent());
            // NOSONAR
            Files.copy(f.getContents(), newFile, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("Unable to write file", e);
        }
    }
    byte[] droolsModelFileContent = mfs.getMap().entrySet().stream().filter(kv -> kv.getKey().startsWith(CanonicalKieModule.MODEL_FILE_DIRECTORY) && kv.getKey().endsWith(CanonicalKieModule.MODEL_FILE_NAME)).map(Map.Entry::getValue).findFirst().orElseThrow(RuntimeException::new);
    List<String> lines = new BufferedReader(new StringReader(new String(droolsModelFileContent))).lines().collect(Collectors.toList());
    lines.forEach(LOG::debug);
    String vbMain = new String(IoUtils.readBytesFromInputStream(ValidationBootstrapMain.class.getResourceAsStream("ValidationBootstrapModels.java")));
    String v1x = lines.stream().filter(x -> x.startsWith("org.kie.dmn.validation.DMNv1x.Rules")).findFirst().orElseThrow(RuntimeException::new);
    String v11 = lines.stream().filter(x -> x.startsWith("org.kie.dmn.validation.DMNv1_1.Rules")).findFirst().orElseThrow(RuntimeException::new);
    String v12 = lines.stream().filter(x -> x.startsWith("org.kie.dmn.validation.DMNv1_2.Rules")).findFirst().orElseThrow(RuntimeException::new);
    vbMain = vbMain.replaceAll("\\$V1X_MODEL\\$", v1x);
    vbMain = vbMain.replaceAll("\\$V11_MODEL\\$", v11);
    vbMain = vbMain.replaceAll("\\$V12_MODEL\\$", v12);
    final Path validationEntryPointFile = Paths.get(kieDmnValidationBaseDir.getAbsolutePath(), "target", "generated-sources", "bootstrap", "org", "kie", "dmn", "validation", "bootstrap", "ValidationBootstrapModels.java");
    LOG.info("Writing code generated ValidationBootstrapModels class into: {}", validationEntryPointFile);
    try {
        // NOSONAR javasecurity:S2083 base dir kieDmnValidationBaseDir is provided as configuration by design, static analysis exclusion applies to these 3 lines
        Files.deleteIfExists(validationEntryPointFile);
        // NOSONAR
        Files.createDirectories(validationEntryPointFile.getParent());
        // NOSONAR
        Files.copy(new ByteArrayInputStream(vbMain.getBytes()), validationEntryPointFile, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("Unable to write file", e);
    }
}
Also used : InternalKieModule(org.drools.compiler.kie.builder.impl.InternalKieModule) MemoryFileSystem(org.drools.compiler.compiler.io.memory.MemoryFileSystem) LoggerFactory(org.slf4j.LoggerFactory) Folder(org.drools.compiler.compiler.io.Folder) StandardCopyOption(java.nio.file.StandardCopyOption) ArrayList(java.util.ArrayList) IoUtils(org.drools.core.util.IoUtils) ModelWriter(org.drools.modelcompiler.builder.ModelWriter) ByteArrayInputStream(java.io.ByteArrayInputStream) KieBuilderImpl(org.drools.compiler.kie.builder.impl.KieBuilderImpl) Map(java.util.Map) KieServices(org.kie.api.KieServices) MemoryFile(org.drools.compiler.compiler.io.memory.MemoryFile) Path(java.nio.file.Path) ModelBuilderImpl(org.drools.modelcompiler.builder.ModelBuilderImpl) MemoryKieModule(org.drools.compiler.kie.builder.impl.MemoryKieModule) Logger(org.slf4j.Logger) Files(java.nio.file.Files) Results(org.kie.api.builder.Results) IOException(java.io.IOException) CanonicalKieModule(org.drools.modelcompiler.CanonicalKieModule) Collectors(java.util.stream.Collectors) File(java.io.File) List(java.util.List) StringReader(java.io.StringReader) CanonicalModelKieProject(org.drools.modelcompiler.builder.CanonicalModelKieProject) Paths(java.nio.file.Paths) BuildContext(org.drools.compiler.kie.builder.impl.BuildContext) BufferedReader(java.io.BufferedReader) MemoryFile(org.drools.compiler.compiler.io.memory.MemoryFile) Path(java.nio.file.Path) KieBuilderImpl(org.drools.compiler.kie.builder.impl.KieBuilderImpl) KieServices(org.kie.api.KieServices) IOException(java.io.IOException) MemoryFileSystem(org.drools.compiler.compiler.io.memory.MemoryFileSystem) Results(org.kie.api.builder.Results) ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) MemoryKieModule(org.drools.compiler.kie.builder.impl.MemoryKieModule) InternalKieModule(org.drools.compiler.kie.builder.impl.InternalKieModule)

Example 99 with InternalKieModule

use of org.drools.compiler.kie.builder.impl.InternalKieModule in project kie-wb-common by kiegroup.

the class KieMetadataTest method compileAndloadKieJarSingleMetadataWithPackagedJar.

@Test
@Ignore("https://issues.redhat.com/browse/AF-2892")
public void compileAndloadKieJarSingleMetadataWithPackagedJar() throws Exception {
    /**
     * If the test fail check if the Drools core classes used, KieModuleMetaInfo and TypeMetaInfo implements Serializable
     */
    Path tmp = TestUtil.createAndCopyToDirectory(tmpRoot, "dummy", ResourcesConstants.KJAR_2_SINGLE_RESOURCES);
    final AFCompiler compiler = KieMavenCompilerFactory.getCompiler(EnumSet.of(KieDecorator.STORE_KIE_OBJECTS, KieDecorator.STORE_BUILD_CLASSPATH, KieDecorator.ENABLE_INCREMENTAL_BUILD));
    WorkspaceCompilationInfo info = new WorkspaceCompilationInfo(Paths.get(tmp.toUri()));
    CompilationRequest req = new DefaultCompilationRequest(mavenRepoPath, info, new String[] { MavenCLIArgs.COMPILE, MavenCLIArgs.ALTERNATE_USER_SETTINGS + alternateSettingsAbsPath }, Boolean.FALSE);
    KieCompilationResponse res = (KieCompilationResponse) compiler.compile(req);
    TestUtil.saveMavenLogIfCompilationResponseNotSuccessfull(tmp, res, this.getClass(), testName);
    if (!res.isSuccessful()) {
        List<String> msgs = res.getMavenOutput();
        for (String msg : msgs) {
            logger.info(msg);
        }
    }
    assertThat(res.isSuccessful()).isTrue();
    Optional<KieModuleMetaInfo> metaDataOptional = res.getKieModuleMetaInfo();
    assertThat(metaDataOptional).isPresent();
    KieModuleMetaInfo kieModuleMetaInfo = metaDataOptional.get();
    assertThat(kieModuleMetaInfo).isNotNull();
    Optional<KieModule> kieModuleOptional = res.getKieModule();
    assertThat(kieModuleOptional).isPresent();
    KieModule kModule = kieModuleOptional.get();
    assertThat(res.getDependenciesAsURI()).hasSize(4);
    KieModuleMetaData kieModuleMetaData = new KieModuleMetaDataImpl((InternalKieModule) kModule, res.getDependenciesAsURI());
    assertThat(kieModuleMetaData).isNotNull();
// comment if you want read the log file after the test run
}
Also used : Path(org.uberfire.java.nio.file.Path) KieCompilationResponse(org.kie.workbench.common.services.backend.compiler.impl.kie.KieCompilationResponse) KieModuleMetaData(org.kie.scanner.KieModuleMetaData) KieModuleMetaDataImpl(org.kie.scanner.KieModuleMetaDataImpl) WorkspaceCompilationInfo(org.kie.workbench.common.services.backend.compiler.impl.WorkspaceCompilationInfo) KieModuleMetaInfo(org.drools.core.rule.KieModuleMetaInfo) DefaultCompilationRequest(org.kie.workbench.common.services.backend.compiler.impl.DefaultCompilationRequest) AFCompiler(org.kie.workbench.common.services.backend.compiler.AFCompiler) CompilationRequest(org.kie.workbench.common.services.backend.compiler.CompilationRequest) DefaultCompilationRequest(org.kie.workbench.common.services.backend.compiler.impl.DefaultCompilationRequest) InternalKieModule(org.drools.compiler.kie.builder.impl.InternalKieModule) KieModule(org.kie.api.builder.KieModule) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 100 with InternalKieModule

use of org.drools.compiler.kie.builder.impl.InternalKieModule in project kie-wb-common by kiegroup.

the class BuildHelper method doBuildAndDeploy.

private BuildResults doBuildAndDeploy(final Module module, final boolean suppressHandlers) {
    try {
        // Build
        final BuildResults results = build(module).getBuildResults();
        StringBuffer message = new StringBuffer();
        message.append("Build of module '" + module.getModuleName() + "' (requested by " + getIdentifier() + ") completed.\n");
        message.append(" Build: " + (results.getErrorMessages().isEmpty() ? "SUCCESSFUL" : "FAILURE"));
        // Deploy, if no errors
        final POM pom = pomService.load(module.getPomXMLPath());
        if (results.getErrorMessages().isEmpty()) {
            final Builder builder = cache.assertBuilder(module);
            final InternalKieModule kieModule = (InternalKieModule) builder.getKieModule();
            final ByteArrayInputStream input = new ByteArrayInputStream(kieModule.getBytes());
            m2RepoService.deployJar(input, pom.getGav());
            message.append(" Maven: SUCCESSFUL");
            if (!suppressHandlers) {
                results.addParameter("RootPath", module.getRootPath().toURI());
                for (PostBuildHandler handler : handlers) {
                    try {
                        handler.process(results);
                    } catch (Exception e) {
                        logger.warn("PostBuildHandler {} failed due to {}", handler, e.getMessage());
                    }
                }
                message.append(" Deploy: " + (results.getErrorMessages().isEmpty() ? "SUCCESSFUL" : "FAILURE"));
            }
        }
        return results;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        // So, instead of throwing the exception, a BuildResults instance is produced on the fly to simulate the error in the problems widget.
        return buildExceptionResults(e, module.getPom().getGav());
    }
}
Also used : IncrementalBuildResults(org.guvnor.common.services.project.builder.model.IncrementalBuildResults) BuildResults(org.guvnor.common.services.project.builder.model.BuildResults) ByteArrayInputStream(java.io.ByteArrayInputStream) PostBuildHandler(org.guvnor.common.services.project.builder.service.PostBuildHandler) ContextNotActiveException(javax.enterprise.context.ContextNotActiveException) POM(org.guvnor.common.services.project.model.POM) InternalKieModule(org.drools.compiler.kie.builder.impl.InternalKieModule)

Aggregations

InternalKieModule (org.drools.compiler.kie.builder.impl.InternalKieModule)201 ReleaseId (org.kie.api.builder.ReleaseId)125 KieServices (org.kie.api.KieServices)120 Test (org.junit.Test)86 KieMavenRepository.getKieMavenRepository (org.kie.scanner.KieMavenRepository.getKieMavenRepository)72 File (java.io.File)62 ArrayList (java.util.ArrayList)57 KieContainer (org.kie.api.runtime.KieContainer)57 KieBuilder (org.kie.api.builder.KieBuilder)55 KieFileSystem (org.kie.api.builder.KieFileSystem)54 FileOutputStream (java.io.FileOutputStream)53 KieMavenRepository (org.kie.scanner.KieMavenRepository)51 KieSession (org.kie.api.runtime.KieSession)43 HashMap (java.util.HashMap)28 Before (org.junit.Before)28 KieModule (org.kie.api.builder.KieModule)24 DeploymentDescriptor (org.kie.internal.runtime.conf.DeploymentDescriptor)23 KieScanner (org.kie.api.builder.KieScanner)20 InternalKieScanner (org.drools.compiler.kie.builder.impl.InternalKieScanner)18 KModuleDeploymentUnit (org.jbpm.kie.services.impl.KModuleDeploymentUnit)17