No Runnable Methods and Test Class Should Have Exactly One Public Constructor Exception - eclipse

I can't seem to shake this error. The Eclipse Runner appears to find the #Test annotations however the BlockJUnit4ClassRunner validateConstructor and validateInstanceMethods can't see the #Test annotations.
I have read In this case, Test.class have been loaded with the system ClassLoader (i.e. the one that loaded JUnitCore), therefore technically none of the test methods will have been annotated with that annotation.
Solution is to load JUnitCore in the same ClassLoader as the tests themselves.
I've tried updating the JUnitCore in the same ClassLoader however missed the exact configuration. I have also tried an external runner along with try/catch to consume the error.. Nothing appears to work.
How would I...
Junit Runner to identify the class,
or
Possibly Ignore this error in a try/catch
or
Implement the correct structure for the ClassLoader solution?
I've attached a copy of code in git repository reference. bhhc.java throws the exception upon execution.
Supported Data:
SRC: https://github.com/agolem2/MavenJunit/blob/master/src/Test/bhhc.java
ERROR:
Google
Completed Test Case bhhc Date: 2017-09-26 08_57_17.318
Test run was NOT successful:
No runnable methods - Trace: java.lang.Exception: No runnable methods
org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4Cl
assRunner.java:191)
org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUni
t4ClassRunner.java:128)
Test class should have exactly one public constructor - Trace:
java.lang.Exception: Test class should have exactly one public constructor
org.junit.runners.BlockJUnit4ClassRunner.validateOnlyOneConstructor(BlockJUnit
4ClassRunner.java:158)
org.junit.runners.BlockJUnit4ClassRunner.validateConstructor(BlockJUnit4ClassR
unner.java:147)

Related

Spring Boot Geode Unsatisfied dependency expressed through method 'sessionRegion'

The correct dependencies for my gradle.build are driving me crazy!
In order to access an Apache Geode 1.10 server, I am using:
// Geode client dependency
implementation 'org.springframework.geode:spring-geode-starter:1.2.13.RELEASE'
implementation 'org.springframework.data:spring-data-geode:2.2.12.RELEASE'
implementation 'org.springframework.boot:spring-boot-starter-tomcat:2.2.13.RELEASE'
This fails with the error:
org.springframework.context.support.AbstractApplicationContext 596 refresh:
Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'ClusteredSpringSessions' defined in class path resource
[org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionConfiguration.class]:
Unsatisfied dependency expressed through method 'sessionRegion' parameter 0;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'org.springframework.data.gemfire.config.annotation.ClientCacheConfiguration':
Initialization of bean failed; nested exception is java.lang.IllegalAccessError:
class org.springframework.data.gemfire.config.annotation.AbstractCacheConfiguration$$Lambda$703/0x0000000801025d10
tried to access protected method 'boolean org.springframework.data.gemfire.config.annotation.support.AbstractAnnotationConfigSupport.hasValue(java.lang.Number)'
(org.springframework.data.gemfire.config.annotation.AbstractCacheConfiguration$$Lambda$703/0x0000000801025d10
and org.springframework.data.gemfire.config.annotation.support.AbstractAnnotationConfigSupport are in unnamed module of loader 'app')
What is there to tell me the dependency missing for the UnsatisfiedDependencyException for 'ClusteredSpringSessions'?
If I remove the #EnableGemFireHttpSession annotation then I get the error
2021-02-02T19:29:49,011 WARN [main] org.springframework.context.support.AbstractApplicationContext 596 refresh:
Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'cacheManager' defined in class path resource [org/springframework/data/gemfire/cache/config/GemfireCachingConfiguration.class]:
Unsatisfied dependency expressed through method 'cacheManager' parameter 0;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'org.springframework.data.gemfire.config.annotation.ClientCacheConfiguration':
Initialization of bean failed; nested exception is java.lang.IllegalAccessError:
class org.springframework.data.gemfire.config.annotation.AbstractCacheConfiguration$$Lambda$679/0x00000008010306b8
tried to access protected method 'boolean org.springframework.data.gemfire.config.annotation.support.AbstractAnnotationConfigSupport.hasValue(java.lang.Number)'
(org.springframework.data.gemfire.config.annotation.AbstractCacheConfiguration$$Lambda$679/0x00000008010306b8
and org.springframework.data.gemfire.config.annotation.support.AbstractAnnotationConfigSupport are in unnamed module of loader 'app')
What is there to tell me the dependency missing for the UnsatisfiedDependencyException for 'cacheManager'?
Thanks
UPDATE The App is run like Spring Boot #ComponentScan finds candidate component class but does not inject #Configuration beans but more specifically
#SpringBootApplication
#ComponentScan({"api", "rsocket", "pricing", "listeners", "dealing", "web"}) // scans packages for # components
#EnableLogging(logLevel="debug", logFile="geodeApi.log")
public class Api {
private static final Logger log = LogManager.getLogger(Api.class);
public static void main(String[] args) {
log.info("In Main");
SpringApplication app = new SpringApplication(Api.class);
app.setWebApplicationType(WebApplicationType.REACTIVE);
SpringApplication.run(Api.class, args);
log.info("Out Main");
}
}
The component scan finds various #Component annotated classes for example
#Component
#EnableClusterDefinedRegions(clientRegionShortcut=ClientRegionShortcut.PROXY)
public class ClientCache {
private static final Logger log = LogManager.getLogger(ClientCache.class);
#Resource
private Region<String, String> admin;
#Autowired
LQuote lQuote;
#Autowired
LReject lReject;
#Autowired
LDeal lDeal;
#Autowired
DealNumber dealNumber;
#Autowired
PriceService priceService;
#PreDestroy
public void onDestroy() throws Exception {
log.info("onDestroy");
String guid = UUID.randomUUID().toString().substring(0, 8).toUpperCase();
admin.put(guid, "API Shutdown");
// TODO: Cancel all open quote streams
log.traceExit();
}
#Bean
ApplicationRunner StartedUp(){
log.traceEntry("StartedUp");
return args -> {
String guid = UUID.randomUUID().toString().substring(0, 8).toUpperCase();
admin.put(guid, "API Started");
lQuote.addListener();
lReject.addListener();
lDeal.addListener();
// Get latest deal number
int currentId = dealNumber.readCurrentId();
// Set it + 1 in case the web server was reboot on the fly
priceService.setCurrentId(currentId + 1);
log.traceExit();
};
}
A lot of the problem was using Java JDK version 15.
The correct versions require Java 11.
// Geode client dependency
implementation 'org.springframework.geode:spring-geode-starter:1.2.8.RELEASE'
implementation 'org.springframework.data:spring-data-geode:2.2.8.RELEASE'
implementation 'org.springframework.boot:spring-boot-starter-tomcat'
Technically, it is not necessary to explicitly declare the SDG dependency.
The SBDG dependency (i.e. org.springframework.geode:spring-geode-starter) already includes SDG (org.springframework.data:spring-data-geode). You can follow the dependency trail starting here, then here and finally, here.
As the Version Compatibility Matrix for SBDG specifies, SBDG 1.2.13.RELEASE specifically includes, and is based on, SDG 2.2.12.RELEASE (already), which is (technically) based on Apache Geode 1.9.2.
However, if you need to use Apache Geode 1.10, then you could (recommended) simply declare dependency management to enforce the use of Apache Geode 1.10 in your Gradle build:
plugins {
id 'org.springframework.boot' version '2.2.13.RELEASE'
id 'io.spring.dependency-management' version '1.0.10.RELEASE'
id 'java'
}
dependencyManagement {
dependencies {
dependency 'org.apache.geode:geode-core:1.10.0'
dependency 'org.apache.geode:geode-cq:1.10.0'
dependency 'org.apache.geode:geode-lucene:1.10.0'
dependency 'org.apache.geode:geode-wan:1.10.0'
}
}
dependencies {
implementation 'org.springframework.geode:spring-geode-starter:1.2.13.RELEASE`
implementation 'org.springframework.boot:spring-boot-starter-tomcat'
}
...
WARNING: SDG 2.2.12.RELEASE is officially based on Apache Geode 1.9.2, and though it should work reasonably well with Apache Geode 1.10, there could expectedly be limitations in certain use cases.
This is not unlike what Spring Initializer conveniently generates for you. Of course, Spring Initializer now uses the new SBDG BOM that makes managing individual SBDG module dependencies even easier, which is not unlike how Spring Boot's dependency management manages transitive dependencies, including 3rd party libs.
Regarding the Exceptions...
It really seems to me like you are having configuration problems rather than dependency problems, actually.
Of course, it is hard to say for certain given you shared very minimal Gradle build configuration and no code snippets from your Spring Boot application configuration, only mentions and what I am able to derive from the Exception messages. So, for now, I'll proceed based on what you provided and what I know or could derive.
Looking at this part of the (first) Exception message:
Error creating bean with name 'ClusteredSpringSessions' defined in class path resource
[org/springframework/session/data/gemfire/config/annotation/web/http/GemFireHttpSessionConfiguration.class]:
Unsatisfied dependency expressed through method 'sessionRegion' parameter 0
And, specifically:
Unsatisfied dependency expressed through method 'sessionRegion' parameter 0
This message refers to the (Spring Java) configuration provided by SSDG and imported/auto-configured by SBDG.
The "Unsatisfied dependency", or "parameter 0", is the 1st method parameter in the sessionRegion(..) (Spring JavaConfig-based) #Bean definition method declared in SSDG's configuration. It is the dependency on the GemFire cache instance (e.g. ClientCache) required to create the "ClusteredSpringSessions" Region.
So now, the question becomes, how is the cache created?
Well, this is what the framework is trying to do next... resolve the cache bean dependency (instance reference), which necessary triggers the cache creation first (due to dependency order)...
Error creating bean with name 'org.springframework.data.gemfire.config.annotation.ClientCacheConfiguration':
Initialization of bean failed; nested exception is java.lang.IllegalAccessError
We see that an IllegalAccessError occurred (O.o) which already smells like a version problem to me, but...
The ClientCacheConfiguration is provided by SDG.
Finally, we arrive at the underlying cause...
class org.springframework.data.gemfire.config.annotation.AbstractCacheConfiguration$$Lambda$703/0x0000000801025d10
tried to access protected method 'boolean org.springframework.data.gemfire.config.annotation.support.AbstractAnnotationConfigSupport.hasValue(java.lang.Number)'
NOTE: ClientCacheConfiguration extends AbstractCacheConfiguration, which extends AbstractAnnotationConfigSupport, and therefore should have "access" to the protected hasValue(:Number) method.
The main Thread appears to be in one of these Lambdas where the AbstractAnnotationConfig.hasValue(:Number) method is used.
I am no entirely sure what this means...
org.springframework.data.gemfire.config.annotation.AbstractCacheConfiguration$$Lambda$703/0x0000000801025d10
and org.springframework.data.gemfire.config.annotation.support.AbstractAnnotationConfigSupport are in unnamed module of loader 'app'
Are you possibly using Spring Boot's new (Layered) Docker Image support by chance?
The 2nd Exception message (involving the cacheManager bean this time) leads to the same outcome, actually. It is no different, but simply involves another bean (i.e. cacheManager bean) with the same dependency on the cache instance:
Error creating bean with name 'cacheManager' defined in class path resource
[org/springframework/data/gemfire/cache/config/GemfireCachingConfiguration.class]
: Unsatisfied dependency expressed through method 'cacheManager' parameter 0;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'org.springframework.data.gemfire.config.annotation.ClientCacheConfiguration':
Initialization of bean failed; nested exception is java.lang.IllegalAccessError:
class org.springframework.data.gemfire.config.annotation.AbstractCacheConfiguration$$Lambda$679/0x00000008010306b8
tried to access protected method 'boolean org.springframework.data.gemfire.config.annotation.support.AbstractAnnotationConfigSupport.hasValue(java.lang.Number)'
(org.springframework.data.gemfire.config.annotation.AbstractCacheConfiguration$$Lambda$679/0x00000008010306b8
and org.springframework.data.gemfire.config.annotation.support.AbstractAnnotationConfigSupport are in unnamed module of loader 'app')
And, specifically:
Initialization of bean failed; nested exception is java.lang.IllegalAccessError:
tried to access protected method 'boolean org.springframework.data.gemfire
.config.annotation.support.AbstractAnnotationConfigSupport
.hasValue(java.lang.Number)'
And:
(org.springframework.data.gemfire.config.annotation.AbstractCacheConfiguration$$Lambda$679/0x00000008010306b8
and org.springframework.data.gemfire.config.annotation.support.AbstractAnnotationConfigSupport
are in unnamed module of loader 'app')
I am not familiar with this error messages (basically, said class(es) "are in unnamed module of loader 'app'.") What?
How is this Spring Boot app being run?
Definitely providing a sample app, one or more tests, your configuration, logs, Stack Traces in addition to Exception messages, setup, runtime environment, etc, etc, will go along way in trying to understand the context of this problem.
At this point, I am really trying to point you in a direction to start untangling the problem.
Sorry, I cannot (currently) be of more help in this case.

UnknownServiceException: Unknown service requested [EnversService]

I want to run Hibernate in OSGi. I have added the standard Hibernate OSGi bundle and a Blueprint implementation, so that Envers gets registered right on startup.
Even without any kind of documentation I found out you have to start Envers, because... I doubt there is a logical reason, it does not work otherwise.
However now, even though Envers was registered in Blueprint, I get the following exception:
org.hibernate.service.UnknownServiceException: Unknown service requested [org.hibernate.envers.boot.internal.EnversService]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:184)
at org.hibernate.envers.boot.internal.TypeContributorImpl.contribute(TypeContributorImpl.java:22)
at org.hibernate.boot.internal.MetadataBuilderImpl.applyTypes(MetadataBuilderImpl.java:280)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.populate(EntityManagerFactoryBuilderImpl.java:798)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:187)
at org.hibernate.jpa.boot.spi.Bootstrap.getEntityManagerFactoryBuilder(Bootstrap.java:34)
at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilder(HibernatePersistenceProvider.java:165)
at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:114)
at org.hibernate.osgi.OsgiPersistenceProvider.createEntityManagerFactory(OsgiPersistenceProvider.java:78)
at org.acme.project.Main.startSession(PersistenceUnitJpaProvider.java:38)
The stack trace starts at PersistenceProvider#createEntityManagerFactory in the following snippet:
public class Main {
private EntityManagerFactory entityManagerFactory;
public void startSession(Map<String, Object> config) {
BundleContext context = FrameworkUtil.getBundle(getClass()).getBundleContext();
ServiceReference<PersistenceProvider> serviceReference = context.getServiceReference(PersistenceProvider.class);
PersistenceProvider persistenceProvider = context.getService(serviceReference);
this.entityManagerFactory = persistenceProvider.createEntityManagerFactory("persistenceUnit", config);
context.ungetService(serviceReference);
}
I found this bug, and maybe this issue is fixed in the current version of Hibernate. But since the bundle IDs are broken, I have to use 5.1.
So Envers is registered, but not really. What could be the reason for such a strange error message?

ModuleClassLoader singleton

I have this situation:
a JBOSS instance
application client.war
application server.war
a jboss module, properly installed, containing only the interfaces.
The server.war application implements the jboss module interfaces, and publishes these implementations with a JNDI bind. The client.war application with a lookup uses implementations server.war.
A runtime client.war can call the implementation exposed by server.war, but as soon as I try to start a transaction hibernate I get the following error:
ERROR [stderr] java.lang.IllegalStateException: JBAS016071: Singleton
not set for ModuleClassLoader for Module "client.war:main" from
Service Module Loader. This means that you are trying to access a weld
deployment with a Thread Context ClassLoader that is not associated
with the deployment.
There I bumped my head for days, but I can not understand what the problem is. Someone can help me?
Set the class loader on the child thread to be the same as the parent.
Get parent class loader:
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Set child class loader :
ClassLoader cl = Thread.currentThread().setContextClassLoader(cl);
When the child thread is done, make sure to unset the class loader to null, to avoid leaks in case of thread pools.
Although CDI will work in the child thread other things such as remote EJB invocation and JNDI lookups will not.
A much better approch wuld be to use an async EJB invocations You can just create an EJB that looks something like:
#Singleton
public class AsyncBean {
#Asynchronous
public void performTask(int a, int b) {
// the client doesn't care what happens here
}
This would mean that your async task will have the TCCL set correctly, JNDI will work etc (basically it is a full EE invocation).
You can configure the thread pool used for async invocations in standalone.xml, but it will be used for all #Asynchronous methods in the application.
Root Cause
When an application launches its own threads, the new threads use a classloader which is different than the classloader of the originating thread, therefore injection is failing.
Reference
https://access.redhat.com/solutions/257663

EclipseLink adding a Converter causes ValidationException intermittently

I am building a new application using EclipseLink for the first time.
Everything was going okay until I added an entity that uses JSR310 Instant for a timestamp column.
So I created a converter class and mapped it to the the associated field like so:
#Convert(converter = JSR310InstantTypeConverter.class)
private Instant pwdChangeCodeExpiresOn = null;
However since I added that converter the application has started throwing the following exception:
SEVERE: Servlet.service() for servlet [APIJerseyServlet] in context with path [/Sclera] threw exception [org.glassfish.jersey.server.ContainerException: java.lang.ExceptionInInitializerError] with root cause
Local Exception Stack:
Exception [EclipseLink-7351] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.ValidationException
Exception Description: The converter class [com.sclera.utils.JSR310InstantTypeConverter] specified on the mapping attribute [pwdChangeCodeExpiresOn] from the class [com.sclera.entity.Admin] was not found. Please ensure the converter class name is correct and exists with the persistence unit definition.
at org.eclipse.persistence.exceptions.ValidationException.converterClassNotFound(ValidationException.java:2317)
at org.eclipse.persistence.internal.jpa.metadata.converters.ConvertMetadata.process(ConvertMetadata.java:248)
This will start happening after a code change (when Eclipse restarts the server). I have to stop and start (and/or restart) the server manually a few times until it finally starts working again. Then it will work fine until a code change or two later when it will start throwing the exception again.
This is an enormous pain. Anyone know the cause and how to fix it?
Okay solution found. Adding the converter class to the persistence.xml file - as suggested by the error message - seems to have resolved the problem.
<persistence-unit name="example" transaction-type="RESOURCE_LOCAL">
....
<class>com.example.utils.JSR310InstantTypeConverter</class>
...
</persistence-unit>
I should have tried that earlier. The fact that is working some of the time without this made me think it wouldn't make a difference.

Connect to a running JBoss AS7 instance for test purposes

I already have a integration-test phase, when I ran the selenium tests. I also want to run some unit tests in this phase, because the app is too much complex and have a lot of dependencies between his modules (a hell), so, after a week fighting against OpenEJB and Arquillian, I believe that this would be easier.
The thing is: how do I made it work?
I have the instance already running, if I instantiate an InitialContext and try to lookup some bean, I got an exception telling me that I have not set the java.naming.initial.factory, and I don't know what to put in there.
I'm also complaining about the annotated beans.
Suppose a Bean like this:
#Stateless
public class ABeanImpl implements ABean {
#EJB
private BBean;
}
Will the container automatically get right the BBean?
Thanks in advance
How to connect to JBoss 7.1 remote JNDI:
Here is the code snippet that I use for JBoss 7.1:
Properties props = new Properties();
String JBOSS_CONTEXT = "org.jboss.naming.remote.client.InitialContextFactory";
props.put("jboss.naming.client.ejb.context", true);
props.put(Context.INITIAL_CONTEXT_FACTORY, JBOSS_CONTEXT);
props.put(Context.PROVIDER_URL, "remote://localhost:4447");
props.put(Context.SECURITY_PRINCIPAL, "jboss");
props.put(Context.SECURITY_CREDENTIALS, "jboss123");
InitialContext ctx = new InitialContext(props);
Resolution of ambiguous ejb references:
According to JBoss EJB 3 reference, if at any level of your EJB environment (EJB/EAR/Server) are duplicates in used interfaces, exception will be thrown during resolution of injected beans.
Based on above, if you have got a reference to EJB bean which interface:
has two implementations in your EJB module (JAR/WAR) - exception will be thrown
has two implementations in your application (other EJB JAR's in same EAR) - exception will be thrown
has two implementations, one in module with bean ABeanImpl, second somewhere else - implemetation from current module is used.