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);
}
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();
}
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);
}
}
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
}
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());
}
}
Aggregations