What is releaseid in kieRepository in drool engine code - drools

I was going through drool engine code for spring I am not able to find what is the use of kie repository and releaseId in drool engine.I have attached the sample code below can some one explain me this what does it do
public KieContainer kieContainer() throws IOException {
KieRepository kieRepository = getKieServices().getRepository();
kieRepository.addKieModule(new KieModule() {
public ReleaseId getReleaseId() {
return kieRepository.getDefaultReleaseId();
}
});
KieBuilder kieBuilder = getKieServices()
.newKieBuilder(kieFileSystem())
.buildAll();
return getKieServices().newKieContainer(kieRepository.getDefaultReleaseId());

When you publish your rules in a kjar, they're published to a Maven repository. That's what the "kie repository" is -- the Maven repository with the your rules init. The release id is the artifact id.
The logic you're looking at is how to pull a kjar from a Maven repository and deploy the rules from it.
Alternatively, you could keep your DRL files (or XLSX decision tables, or what not) locally and not bother with either the repository or release id.

Related

Eclipse IDE 2020‑03 Debugger is doing weird stuff

So I am stuck with a problem when debugging with the most recent version of Eclipse 2020-03, which I installed for a new project I'm working on.
It first struck me that things were not working correctly when I couldn't read a resource with Class.getResource( String name ), as the debugger at the breakpoint in getResource(..) kept telling me that the name was null, while I definitely had provided a path name.
Clearing, cleaning, reloading the target (Running Platform), refreshing and rebuilding did not change anything, so I decided to create a simple OSGI plugin project with just an Activator, and a debug configuration with only the bare minimum bundles.
The Activator looks like this:
public class Activator implements BundleActivator {
public static final String BUNDLE_ID = "test.myapp.core";
private static BundleContext context;
private Logger logger = Logger.getLogger(this.getClass().getName());
static BundleContext getContext() {
return context;
}
public Activator() {
super();
logger.info("STARTED: " + BUNDLE_ID);
}
#Override
public void start(BundleContext bundleContext) throws Exception {
logger.info("ACTIVATED: " + BUNDLE_ID);
Activator.context = bundleContext;
InputStream in = getClass().getResourceAsStream( "/test.cfg" );
}
#Override
public void stop(BundleContext bundleContext) throws Exception {
Activator.context = null;
}
}
EDIT: Changed the original link to build.properties to test.cfg in order to avoid confusion.
But when I start the debugger, it will activate the bundle, but will not show any of the log messages. Also the debugger will not respond to the breakpoints I put in. Strangely enough, selecting 'ss' shows me far more bundles than the ones provided in the debug configuration.
id State Bundle
0 ACTIVE org.eclipse.osgi_3.15.200.v20200214-1600
1 ACTIVE test.myapp.core_1.0.0.qualifier
2 ACTIVE org.apache.lucene.core.source_8.4.1.v20200122-1459
3 ACTIVE javax.annotation.source_1.2.0.v201602091430
....
It seems as if a different debug configuration is launched, and is using an previously built version of my bundle, where the log messages were not yet included. clearing the bin folder, and eventually all the metadata also had no effect.
I'm totally stumped as of what I'm experiencing here. Hopefully someone can help!
Well..as it seems, I found out what was wrong. There were two problems that were occuring all at once:
1: Regarding the problems with getResource( String name). The Bundle-ClassPath setting in Manifest.MF MUST include . (see https://www.eclipse.org/forums/index.php/t/287184/), so in my case:
Bundle-ClassPath: .,
test.myapp.core
Bundle-ClassPath is not added automatically by the plugin wizards, so that can cause some problems.
2: The Debug configuration screen in the new IDE seems to be very slow, and does not change the selected bundles if you switch from "only show selected" and back. As a result, the previous list of bundles remained active, while they were unchecked in the Debug Configuration Editor.
I'll file a report for these issues
ADDITIONAL
So I have made some further investigations on the Bundle-ClassPath issue, and what probably has happened that this entry in the Manifest.MF occured when adding some libraries. After they were removed again, the Bundle-ClassPath entry remained, and caused all sorts of problems. If you ever:
1: Notice that certain classes from bundle A cause a NoClassDefFound exception when used in bundle B
2: The build.properties file from bundle A give a warning that sources are missing
3: Other bundles don't seem to give that problem
Check to see if there is a Bundle-ClassPath entry in your Manifest.MF file. Most probably that entry is causing the problems. Either remove the entry in the manifest, or add ,. at the end.
see:
1: What is the intended use case for Bundle-Classpath in OSGI bundles
2: https://bugs.eclipse.org/bugs/show_bug.cgi?id=139271

Instanciate a JPA EntityManager in an Eclipse RCP (Java SE) environment

Context :
Eclipse RCP project, divided into plugins, each one devoted to a task (eg : HMI management, communications, ...)
Necessity to persist some data in a database
- ORM : hibernate's JPA (JPA 2.1, Hibernate 5.2.1 used throught an org.hibernate.core plugin as constructed [here (page 8)][1]
- database : in mysql
- constraint : Java SE environment, so the only way to obtain an EntityManager (for the persistence operations) is to create it through an EntityManagerFactory
First step (that works!) :
Plugin that manages the database operations, its structure :
com.plugin.name
JRE System Library
Plug-in Dependencies
Referenced Libraries (contains the mysql connector jar)
src/
com.plugin.name (package containing the plugin activator)
com.plugin.name.entities (package containing all my entities)
com.plugin.name.utils (package containing my access functions and a main)
META-INF/
persistence.xml
META-INF/
MANIFEST.MF
In com.plugin.name.utils I have my classes performing all the persistence functions.
In these classes, I create an EntityManagerFactory this way :
private static final EntityManagerFactory ENTITY_MANAGER_FACTORY = Persistence.createEntityManagerFactory("com.plugin.name");
where "com.plugin.name" is the persistence unit name defined in my persistence.xml
In one of those classes, I have a main running some database-related functions.
When I run this main as java application, everything works fine.
(to prevent future questions : my persistence.xml file was originally generated in the MANIFEST.MF META-INF folder but when running this main, it couldn't be found, so I moved it. I checked both configurations when calling the persistence functions from another plugin)
The problem :
I need to access my persistence functions from another plugin, let's call him com.plugin.other
So I added com.plugin.name as a dependency of this plugin.
But when I try to run the application, I get the following error :
javax.persistence.PersistenceException: No Persistence provider for EntityManager named com.plugin.name
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:61)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
When i run the main as standalone application, if there's any problem with the persistence.xml file (not found, incomplete, etc) it gets at least mentionned... Here I'm really stuck with no clue to understand where the problem comes from.
I finally made it without the persistence.xml by using the createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map) method in the PersistenceProvider.
Code :
Activator a = Activator.getDefault();
Bundle b = a.getBundle();
URL url = b.getResource("META-INF/persistence.xml");
List<PersistenceProvider> providers = PersistenceProviderResolverHolder.getPersistenceProviderResolver().getPersistenceProviders();
for (PersistenceProvider pp : providers) {
PersistenceUnitInfoImpl pui = new PersistenceUnitInfoImpl();
pui.setPersistenceUnitName("persistenceUnitName");
pui.setTransactionType(PersistenceUnitTransactionType.RESOURCE_LOCAL);
pui.setPersistenceUnitRootUrl(url);
Properties prop = pui.getProperties();
if (prop == null) {
prop = new Properties();
}
prop.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://ip:port/dbName");
prop.setProperty("javax.persistence.jdbc.user", "dbUser");
prop.setProperty("javax.persistence.jdbc.password", "dbPass");
prop.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
pui.setProperties(prop);
pui.setClassLoader(com.mysql.jdbc.Driver.class.getClassLoader());
emFactory = pp.createContainerEntityManagerFactory(pui, null);
}
}

OSGI: How to update a 'consumer' bundle

I have been trying to understand a strange OSGI behavior. Hoping someone can shed some light on it. Here is my setup
1) Using eclipse\plugins\org.eclipse.osgi_3.7.0.v20110613.jar
2) I have a Bundle that exports a service (HelloworldService)
It registers the service in the activator as such
public void start(BundleContext context) throws Exception {
IHelloService helloService = new HelloServiceImpl();
helloServiceRegistration =context.registerService(
IHelloService.class.getName(), helloService, null
);
}
3) I have a 'consumer' bundle that uses the service via a ServiceTracker
ServiceReference externalServiceReference = Activator.getContext().getServiceReference(IHelloService.class.getName());
IHelloService externalService = (IHelloService) Activator.getContext().getService(externalServiceReference);
Now when I deploy both these jars to OSGI (helloworld.jar and helloworldservice.jar); it works fine. I am able to get a 'IHelloService' impl object and make calls on it. I can start/stop the bundles and when they come back; it works just fine
The problem happens when I 'uninstall' and then 'install' the HelloWorldservice bundle.
In that case; the 'Helloworld' consumer externalServiceReference is NULL.
If I view the bundle info; I see this
osgi> bundle 1
mypackage.helloworld_1.0.0.qualifier [1]
Id=1, Status=RESOLVED Data Root=C:\Users\\dev\eclipse\plugins\configuration\org.eclipse.obundles\1\data
No registered services.
No services in use.
No exported packages
Imported packages
mypackage.helloworldservice; version="0.0.0" **stale**
org.osgi.framework; version="1.6.0"
org.osgi.util.tracker; version="1.5.0"
No fragment bundles
Named class space
mypackage.helloworld; bundle-version="1.0.0.qualifier"[provided]
No required bundles
Notice that its 'imported packages' has GONE STALE. Here is the line in question
Imported packages
mypackage.helloworldservice; version="0.0.0"<stale>
Now I can fix this by issuing an 'update' command from the console.
Here is my question
1) How do I programatically do this from within my 'consumer' bundle..
2) If I am on a production system and I deploy a new 'copy' of the helloworlservice.jar (replacing the existing version); Do I have to update all its users.. I thought the ServiceTracker would give me the service on the fly
Thanks
The consumer bundle imports the mypackage.helloworldservice package from the service jar. When you uninstall the service jar, the consumer jar is still wired to the now stale package from the uninstalled service jar. When you install a new service jar, it exports a new "copy" of the mypackage.helloworldservice package (I suspect the service jar does not also import the mypackage.helloworldservice package). So you need to refresh the consumer jar to get it to wire to the new mypackage.helloworldservice package.

Use webapp classpath using JavaCompiler in Tomcat within Eclipse with Maven

I have an existing "Example Webapp" that references "Example Library" using Maven. I'm running Tomcat 7 inside Eclipse 4.3RC3 with the m2e plugin. When I launch Example Webapp on Tomcat inside Eclipse, I have verified that the example-library.jar is probably getting deployed in the Tomcat instance's WEB-INF/lib folder.
The Example Webapp has code that compiles certain classes on the fly using JavaCompiler.CompilationTask. These dynamically generated classes reference classes in example-library.jar. Unfortunately the compile task is failing because the referenced classes cannot be found.
I understand that I can set the JavaCompiler classpath, but System.getProperty("java.class.path") only returns me the Tomcat classpath, not the webapp classpath:
C:\bin\tomcat\bin\bootstrap.jar;C:\bin\tomcat\bin\tomcat-juli.jar;C:\bin\jdk6\lib\tools.jar
Other have said that I need to get the real path of WEB-INF/lib from the servlet context, but the class generation code doesn't know anything about a servlet context --- it is written to be agnostic of whether it is used on the client or on the server.
In another question, one answer indicated I could enumerate the classloader URLs, and sure enough this provides me with the jars in WEB-INF/lib, but when I provide this as a -classpath option to compiler.getTask(), the task still fails because it can't find the referenced classes.
How can I simply provide the classpath of the currently executing code to the JavaCompiler instance so that it will find the classes from the libraries in WEB-INF/lib? (A similar question was raised but never answered regarding referencing jars within ear files using JavaCompiler.)
Example: In an attempt to get things working at any cost, I even tried to hard-code the classpath. For example, I have foobar.lib in my webapp lib directory, so I used the following code, modified from the answers I indicated above:
List<String> options = new ArrayList<String>();
options.add("-classpath");
options.add("C:\\work\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\FooBar\\WEB-INF\\lib\\foobar.jar");
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits);
boolean success = task.call();
In the end success is false, and my diaognostics indicates package com.example.foo.bar does not exist..., even though that package is in foobar.jar.
Put example-library.jar somewhere in your file system and pass that location to the code that runs JavaCompiler (the -classpath option). If you use an exploded WAR file to deploy, you can of course point it to the physical location within the WEB-INF/lib folder. The point is that you only need one configurable parameter in your webapp to do this, which can be a properties file entry, -D system property, database row or something else entirely.
Sample code (tested in Tomcat 7 and OpenJDK 1.7 on Fedora 18 x64):
private File compile(File javaFile, String classpath) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnit = fileManager.getJavaFileObjects(javaFile);
List<String> options = classpath != null ? Arrays.asList("-classpath", classpath) : null;
StringWriter output = new StringWriter();
try {
boolean successful = compiler.getTask(output, fileManager, null, options, null, compilationUnit).call();
if (!successful) {
throw new CompilationException("Failed to compile: " + javaFile, output.toString());
}
return firstClassFileFrom(javaFile.getParentFile());
} finally {
fileManager.close();
}
}
private File firstClassFileFrom(File directory) {
return directory.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.endsWith(".class");
}
})[0];
}
See https://github.com/jpalomaki/compiler for a runnable sample webapp.
i met the same question. The reason is not "-classpath" .
my code :
String classpath ="xx/WEB-INF/clases ";
List<String> options = classpath != null ? Arrays.asList("-d", classpath,"-cp",classpath) : null;
CompilationTask task = compiler.getTask(null, javaDinamicoManager, diagnostics,
options, null, Arrays.asList(sourceObj));
boolean result = task.call();
the “result” will return true .
You could follow the answer provided for the even more specific question of how to load dependencies of compiled code from within a web app running directly from an unexpanded WAR file (there are no JAR files to reference - only the container's class loder knows how to access the classes): https://stackoverflow.com/a/45038007/2546679

FluentNhibernate, Nhibernate.Search and Lucene.Net version

I created a project, and used NuGet to install Nhibernate.Search. During the installation NuGet also downloads the Lucene.Net for me.
With NuGet I have following packages downloaded and installed
FluentNHibernate.dll: 1.3.0733
NHibernate.dll: 3.3.1.4000
NHibernate.Search.dll: 2.0.2.4000
Lucene.Net.dll: 2.9.4.1
All the dependencies are managed by NuGet. But when I ran following codes
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Search.Event;
using NHibernate.Search.Store;
namespace Test {
public class NHibernateSearchSessionProvider {
private static ISessionFactory sessionFactory;
private static object syncRoot = new object();
public static ISessionFactory SessionFactory {
get {
lock (syncRoot) {
if (sessionFactory == null) {
sessionFactory = createSessionFactory();
}
return sessionFactory;
}
}
}
private static ISessionFactory createSessionFactory() {
var config = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008
.ConnectionString(c => c.FromConnectionStringWithKey("HomeDB"))
)
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<UserAccountMap>())
.BuildConfiguration();
// Add NHibernate.Search listeners
config.SetListener(NHibernate.Event.ListenerType.PostUpdate, new FullTextIndexEventListener());
config.SetProperty("hibernate.search.default.indexBase", "~/LuceneIndex");
return config.BuildSessionFactory();
}
}
}
An exception message Could not load file or assembly 'Lucene.Net, Version=2.9.2.2, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
It looks like this version of NHibernate.Search is still using Lucene.Net 2.9.2.2 not the new one. I can always manually fix all the dependencies, but I prefer to use NuGet.
Anybody has experience how shall I do to make code work?
Thanks for any suggestion
This looks like a configuration error for the NHibernate.Search nuget package, it states that it supports Lucene.Net 2.9.2.2 and up. Try modifying your packages.config file to use the 2.9.2.2 version of Lucene (instead 2.9.4.1) and nuget will use the specified version during package restoration.
You will probably need to clean out your bin-folder to remove the "old" 2.9.4.1 assembly.
use Install-Package NHibernate.Search.MB
I tried to fix it but it did not.
Already Nhibernate.Search very old