Wildfly 18 - drools 7.39.0-Final: Deploy app and get java.lang.NoClassDefFoundError: Could not initialize class - wildfly

Been trying to migrate an application up to WF 18.0 and drools 7.39.0-Final.
Drools 7.39.0-Final is the last WF18 release.
One of our applications uses drools/kie.
I get errors like the following when trying to deploy it.
"jboss.deployment.subunit.\"policy-ear.ear\".\"policy-beans.jar\".component.CepRuleEngineHolder.START"
=> "java.lang.IllegalStateException: WFLYEE0042: Failed to construct component instance
Caused by: java.lang.IllegalStateException: WFLYEE0042: Failed to construct component instance
Caused by: javax.ejb.EJBException: WFLYEJB0442: Unexpected Error
Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.drools.dynamic.DynamicServiceRegistrySupplier$LazyHolder"
From searching around I found that this can be caused by static stuff/constructors failing.
So I downloaded the source and as an experiment changed things as below. This fixes it.
This example below shows what I did for the KieServices class.
Note that the error above is for a DynamicServiceRegistrySupplier class, I tried to apply my change to that class, but it's a huge build and had some other issues. Before I chased that I wanted to ask if there's a better way to do this? It doesn't seem like I should have to do this at all, this is the latest published drools for WF18.
For KieServices, I changed this:
/**
* A Factory for this KieServices
*/
class Factory {
static class LazyHolder {
private static KieServices INSTANCE = ServiceRegistry.getInstance().get(KieServices.class);
}
/**
* Returns a reference to the KieServices singleton
*/
public static KieServices get() {
return LazyHolder.INSTANCE;
}
}
to:
/**
* A Factory for this KieServices
*/
class Factory {
static private KieServices instance = null;
public static class LazyHolder {
public LazyHolder() {
}
}
/**
* Returns a reference to the KieServices singleton
*/
public static KieServices get() {
if ( instance == null) {
instance = ServiceRegistry.getInstance().get(KieServices.class);
}
return instance;
}
}

Related

Repository autowired returning null

I want to make a application with Spring boot on back-end and Swing on front-end. I need to use a repository autowired on my service class, how to make it when i need to instantiate the service class?
I already tried change the repository to BeanFactory, tried to change the location of the files but i can't escape! I need to instantiate the Service class and autowired doesn't work with this.
I have a Model called Permission.
Repository (PermissionRepository.java):
#Repository
public interface PermissionRepository extends JpaRepository<Permission, Long>{
Optional<Permission> findByDescription(String description);
}
Service (PermissionService.java):
#Autowired
BeanFactory beanFactory;
public List<Permission> loadAll() {
return this.beanFactory.getBean(PermissionRepository.class).findAll();
}
Use (BasicOperations.java):
public static void initialPermission() {
try {
if (new PermissionService().loadAll().isEmpty()) {
//logics
}
} catch(Exception e) {
...
}
}
I expect a List, java.util.List but, the error is a nullPointer on my autowired repository
Stack:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.riTrap.service.PermissionService.loadAll(PermissionService.java:20)
You should use autowired instead of new PermissionService. You use loadAll to check if the database contains elements. If the database is big, this approach can damage your application. Suggestion : use count instead
#Service
public class PermissionService {
#Autowired
PermissionRepository permissionRepository;
public List<Permission> loadAll() {
return permissionRepository.findAll();
}
public boolean isEmpty() {
return permissionRepository.count() == 0L;
}
}
If you need to initialize the bean before usage, you can use the constructor :
#Service
public class BasicOperations {
#Autowired
public BasicOperations(PermissionService permissionService){
if(permissionService.isEmpty()){
//DO STUFF
}
}
}

Jersey integrated quartz #Inject annotation not working

The specific reason I know is because the QuartzJob class is instantiated, but I know that the constructor with no arguments is used, and then the execute method is called to report the exception. #Inject does not work.
Printed error message:
org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573)
Caused by: java.lang.NullPointerException
at org.openscoring.service.quartz.QuartzJob.execute(QuartzJob.java:36)
at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
... 1 more
QuartzJob implements the Job interface
#Service
#Singleton
public class QuartzJob implements Job {
#Inject
private SynchronousCache synchronousCache;
#Override
public void execute(JobExecutionContext content) {
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+ "★★★★★★★★★★★");
synchronousCache.synchronizationModel();
}
}
QuartzManager.addJob("test", QuartzJob.class, "10/59 * * * * ? *");
Add a timed task

UnsatisfiedDependencyException in SpringMVC and MongoDB project

I'm working on a Spring MVC and MongoDB backed application.
My api is working fine,but i would like to create an integration test with Fongo in order to test saving a file and after getting this file by my services.
I have already tried, but when i added #Autowired in my Service class, it returned an UnsatisfiedDependencyException. My test fixture class is the following:
#ActiveProfiles({"test"})
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(
locations = {
"classpath*:config/servlet-config.xml",
"classpath*:config/SpringConfig.xml"})
#WebAppConfiguration
public class IntegrationTest {
#Autowired // returns UnsatisfiedDependencyException
private FileService fileService;
#Before
#Test
public void setUp() throws IOException {
Fongo fongo = new Fongo("dbTest");
DB db = fongo.getDB("myDb");
}
#Test
public void testInsertAndGetFile() throws IOException{
//create a file document in order to save
File file = new File();
file.setId("1");
file.setFileName("test1");
file.setVersionId("1");
//save the file
String id = fileService.storeFile(file);
//get the file
File fileDocument= fileService.getFileById("1");
//check if id is the file id which is expected
assertEquals(fileDocument.getId(), "1");
}
}
and i am receiving this log message:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.ots.openonefilesystem.integration.IntegrationTest': Unsatisfied dependency expressed through field 'fileService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean found for dependency [com.myproject.service.FileService]: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean found for dependency [com.myproject.service.FileService]: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
I'm using xml configuration.
How can i solve my testing error? In my service class FileService i have put #Service, however it seems that Spring expected at least 1 bean which qualifies as autowire candidate.
Also if i remove the #Autowired, the log returns NullpointerException when saving of getting the file,as it was expected.
PS: I use springFramework 4.3.3.RELEASE, spring-data-mongodb 1.9.5.RELEASE
Thank you in advance!
I had to configure Mock Database (Fongo), in order to #Autowired FileService. This, I made it via #ContextConfiguration(classes = {MockDatasourceConfig.class})
So, the correct test fixture class is the following:
#ActiveProfiles({"test"})
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {MockDatasourceConfig.class})
#WebAppConfiguration
public class IntegrationTest{
#Autowired
private FileService fileService;
#Test
public void testInsertAndGetFile() throws IOException{
//create a file document in order to save
File file = new File();
file.setId("1");
file.setFileName("test1");
file.setVersionId("1");
//save the file and return his id
String id = fileService.storeFileGeneral(file);
//get the file
FileDocument fileDocument= fileService.getFileById(id);
//check that the file isn't null
assertNotNull(fileDocument);
//check if id is the file id which is expected
assertEquals(fileDocument.getId(), id);
assertEquals(fileDocument.getFileName(), "test1");
}
}
and the MockDatasourceConfig class is the following:
#Profile({"test"})
#Configuration
#PropertySource("classpath:mongo.properties")
#ComponentScan(basePackageClasses = {File.class})
#EnableMongoRepositories(basePackageClasses = RepositoryPackageMarker.class)
public class MockDatasourceConfig extends AbstractMongoConfiguration {
#Autowired
Environment env;
#Override
protected String getDatabaseName() {
return env.getProperty("mongo.dbname", "myDb");
}
#Override
public Mongo mongo() throws Exception {
return new Fongo(getDatabaseName()).getMongo();
}
#Bean
public GridFsTemplate gridFsTemplate() throws Exception {
return new GridFsTemplate( mongoDbFactory(),mappingMongoConverter());
}
}
P.S: With helpful advice of #M.Deinum

#Configurable not recognized in SpringBoot Application [duplicate]

I am having a strange problem with a custom jpa-entity listener I've created in a spring boot application. I'm trying to use Springs #Configurable mechanism to configure the EntityListener (as seen in Springs AuditingEntityListener) but Spring refuses to recognize my Listener as soon as it is used in the #EntityListeners-Annotation on a jpa entity. if it is not configured on a jpa entity, the Listener gets wired/configured by Spring as it should.
I've created an example project with a junit-test to demonstrate the problem:
https://github.com/chrisi/aopconfig/find/master
#SpringBootApplication
#EnableSpringConfigured
#EnableLoadTimeWeaving
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
The EntityListener:
/**
* This bean will NOT be instanciated by Spring but it should be configured by Spring
* because of the {#link Configurable}-Annotation.
* <p>
* The configuration only works if the <code>UnmanagedBean</code> is not used as an <code>EntityListener</code>
* via the {#link javax.persistence.EntityListeners}-Annotation.
*
* #see FooEntity
*/
#Configurable
public class UnmanagedBean {
#Autowired
private ManagedBean bean;
public int getValue() {
return bean.getValue();
}
}
The Bean I want to be injected in the EntityListener/UnmanagedBean:
/**
* This bean will be instanciated/managed by Spring and will be injected into the
* {#link UnmanagedBean} in the case the <code>UnmanagedBean</code> is not used as an JPA-EntityListener.
*/
#Component
#Data
public class ManagedBean {
private int value = 42;
}
The Entity where the Listener should be used:
/**
* This simple entity's only purpose is to demonstrate that as soon as
* it is annotated with <code>#EntityListeners({UnmanagedBean.class})</code>
* springs configurable mechanism will not longer work on the {#link UnmanagedBean}
* and therefore the <code>ConfigurableTest.testConfigureUnmanagedBean()</code> fails.
*/
#Entity
#EntityListeners({UnmanagedBean.class}) // uncomment to make the test fail
public class FooEntity {
#Id
private Long id;
private String bar;
}
And finally the test that shows that the wiring is not working as soon as the Listener is used:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = Application.class)
public class ConfigurableTest {
/**
* This test checks if the ManagedBean was injected into the UnmanagedBean
* by Spring after it was created with <code>new</code>
*/
#Test
public void testConfigureUnmanagedBean() {
UnmanagedBean edo = new UnmanagedBean();
int val = edo.getValue();
Assert.assertEquals(42, val);
}
}
The junit-test (the wiring of the EntityListener/ManagedBean) fails as soon as
the annotation #EntityListeners({UnmanagedBean.class}) in FooEntity is activated.
Is this a bug or did I miss something else?
In order to run the test you have to use -javaagent:spring-instrument-4.1.6.RELEASE.jar on the commandline an provide the jar file in the working directory.
This is the "condensed" version of a question I asked earlier:
#Configurable not recognized in SpringBoot Application

Morphia, Embed Mongo and Spring. Address already in use

I am trying use MongoDB, Morphia and Spring and test it, so I started use Embedded Mongo.
When I had only one DAO to persist I did not had any problem with my tests, however, in some cases I needed use more than one DAO, and in that cases my injected Datasore give me an problem: addr already in use.
My Spring Test Database Configuration is this:
#Configuration
public class DatabaseMockConfig {
private static final int PORT = 12345;
private MongodConfigBuilder configBuilder;
private MongodExecutable mongodExecutable;
private MongodProcess mongodProcess;
#Bean
#Scope("prototype")
public MongodExecutable getMongodExecutable() {
return this.mongodExecutable;
}
#Bean
#Scope("prototype")
public MongodProcess mongodProcess() {
return this.mongodProcess;
}
#Bean
public IMongodConfig getMongodConfig() throws UnknownHostException, IOException {
if (this.configBuilder == null) {
configBuilder = new MongodConfigBuilder().version(Version.Main.PRODUCTION).net(new Net(PORT, Network.localhostIsIPv6()));
}
return this.configBuilder.build();
}
#Autowired
#Bean
#Scope("prototype")
public Datastore datastore(IMongodConfig mongodConfig) throws IOException {
MongodStarter starter = MongodStarter.getDefaultInstance();
this.mongodExecutable = starter.prepare(mongodConfig);
this.mongodProcess = mongodExecutable.start();
MongoClient mongoClient = new MongoClient("localhost", PORT);
return new Morphia().createDatastore(mongoClient, "morphia");
}
#Autowired
#Bean
#Scope("prototype")
public EventDAO eventDAO(final Datastore datastore) {
return new EventDAO(datastore);
}
#Autowired
#Bean
#Scope("prototype")
public EditionDAO editionDAO(final Datastore datastore) {
return new EditionDAO(datastore);
}
}
And my DAO classes are similar to that
#Repository
public class EventDAO {
private final BasicDAO<Event, ObjectId> basicDAO;
#Autowired
public EventDAO(final Datastore datastore) {
this.basicDAO = new BasicDAO<>(Event.class, datastore);
}
...
}
My test class is similar to that:
#ContextConfiguration(classes = AppMockConfig.class)
#RunWith(SpringJUnit4ClassRunner.class)
public class EventDAOTest {
#Autowired
private EventDAO eventDAO;
#Autowired
private MongodExecutable mongodExecutable;
#Autowired
private MongodProcess mongodProcess;
#Rule
public ExpectedException expectedEx = ExpectedException.none();
#After
public void tearDown() {
this.mongodProcess.stop();
this.mongodExecutable.stop();
}
...
}
I use prototype scope to solve problem with singleton and make sure that my mock database is clean when I start my test, after that I stop mongod process and mongod executable.
However since I need use more than one DAO I receive that error:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'editionDAO' defined in class br.com.mymusicapp.spring.DatabaseMockConfig: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.mongodb.morphia.Datastore]: :
Error creating bean with name 'datastore' defined in class br.com.mymusicapp.spring.DatabaseMockConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.mongodb.morphia.Datastore]:
Factory method 'datastore' threw exception; nested exception is java.io.IOException: Could not start process: ERROR: listen(): bind() failed errno:98 Address already in use for socket: 0.0.0.0:12345
2015-01-04T01:05:04.128-0200 [initandlisten] ERROR: addr already in use
I know what the error means, I just do not know how can I design my Configuration to solve that. As last option I am considering install a localhost MongoDB just for tests, however I think could be a better solution
That is based on the embedded mongod by flapdoodle, right?
If you want to run multiple tests in parallel (could be changed via JUnit annotations, but it's probably faster in parallel), you cannot use a single, hardcoded port. Instead, let the embedded process select an available port automatically.