I'm using Flyway 5.2.4 and OSGI Bundle Activator. I want to migrate database on bundle Start() method.
Here's my ActivatorClass:
import org.flywaydb.core.Flyway;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Activator implements BundleActivator {
private final Logger log = LoggerFactory.getLogger(this.getClass());
private ServiceRegistration serviceRegistration;
public void start(BundleContext bundleContext) {
log.info("Starting...");
serviceRegistration = bundleContext.registerService(IConnector.class.getName(), new Connector(), null);
log.info("Started.");
//FlyWay Section
Flyway flyway = Flyway.configure().dataSource("jdbc:postgresql://localhost:5432/", "postgres", "12345").load();
flyway.migrate();
}
public void stop(BundleContext bundleContext) {
log.info("Stopping...");
serviceRegistration.unregister();
log.info("Stopped.");
}
}
As you can see, I'm using slf4j as my Logger. Maybe that's why I get this errors in my StackTrace after app deploying:
java.lang.Exception: Could not start bundle mvn:internship/db-connector/1.0.0 in feature(s) feature-1.0.0: Activator start error in bundle db-connector [2343].
at org.apache.karaf.features.internal.FeaturesServiceImpl.startBundle(FeaturesServiceImpl.java:519)[20:org.apache.karaf.features.core:3.0.8]
at org.apache.karaf.features.internal.FeaturesServiceImpl.installFeatures(FeaturesServiceImpl.java:474)[20:org.apache.karaf.features.core:3.0.8]
at org.apache.karaf.features.internal.FeaturesServiceImpl.installFeature(FeaturesServiceImpl.java:415)[20:org.apache.karaf.features.core:3.0.8]
at Proxy683d032e_ad2c_4b9a_98f7_baca7b5564f1.installFeature(Unknown Source)[:]
at Proxyfff1bf4b_671e_4ff6_bb97_e0dabf9f20e8.installFeature(Unknown Source)[:]
at org.apache.karaf.kar.internal.KarServiceImpl.installFeatures(KarServiceImpl.java:282)[89:org.apache.karaf.kar.core:3.0.8]
at org.apache.karaf.kar.internal.KarServiceImpl.install(KarServiceImpl.java:111)[89:org.apache.karaf.kar.core:3.0.8]
at org.apache.karaf.kar.internal.KarServiceImpl.install(KarServiceImpl.java:93)[89:org.apache.karaf.kar.core:3.0.8]
at Proxy40d8d25a_37b2_4855_a381_fbb78daa68ce.install(Unknown Source)[:]
at Proxy068a2f57_120b_4ee8_b953_7c8262bae9a2.install(Unknown Source)[:]
at org.apache.karaf.deployer.kar.KarArtifactInstaller.update(KarArtifactInstaller.java:62)[91:org.apache.karaf.deployer.kar:3.0.8]
at Proxy3c143b4c_a2ef_49d0_870b_21a9b5f74704.update(Unknown Source)[:]
at org.apache.felix.fileinstall.internal.DirectoryWatcher.update(DirectoryWatcher.java:1101)[7:org.apache.felix.fileinstall:3.5.2]
at org.apache.felix.fileinstall.internal.DirectoryWatcher.update(DirectoryWatcher.java:898)[7:org.apache.felix.fileinstall:3.5.2]
at org.apache.felix.fileinstall.internal.DirectoryWatcher.doProcess(DirectoryWatcher.java:478)[7:org.apache.felix.fileinstall:3.5.2]
at org.apache.felix.fileinstall.internal.DirectoryWatcher.process(DirectoryWatcher.java:355)[7:org.apache.felix.fileinstall:3.5.2]
at org.apache.felix.fileinstall.internal.DirectoryWatcher.run(DirectoryWatcher.java:307)[7:org.apache.felix.fileinstall:3.5.2]
Caused by: org.osgi.framework.BundleException: Activator start error in bundle db-connector [2343].
at org.apache.felix.framework.Felix.activateBundle(Felix.java:2196)[org.apache.felix.framework-4.2.1.jar:]
at org.apache.felix.framework.Felix.startBundle(Felix.java:2064)[org.apache.felix.framework-4.2.1.jar:]
at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:955)[org.apache.felix.framework-4.2.1.jar:]
at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:942)[org.apache.felix.framework-4.2.1.jar:]
at org.apache.karaf.features.internal.FeaturesServiceImpl.startBundle(FeaturesServiceImpl.java:516)[20:org.apache.karaf.features.core:3.0.8]
... 16 more
Caused by: java.lang.ExceptionInInitializerError
at org.flywaydb.core.internal.util.FeatureDetector.isSlf4jAvailable(FeatureDetector.java:96)
at org.flywaydb.core.internal.logging.LogCreatorFactory.getLogCreator(LogCreatorFactory.java:39)
at org.flywaydb.core.api.logging.LogFactory.getLog(LogFactory.java:78)
at org.flywaydb.core.internal.util.FeatureDetector.<clinit>(FeatureDetector.java:25)
at org.flywaydb.core.internal.logging.LogCreatorFactory.getLogCreator(LogCreatorFactory.java:35)
at org.flywaydb.core.api.logging.LogFactory.getLog(LogFactory.java:78)
at org.flywaydb.core.Flyway.<clinit>(Flyway.java:86)
at internship.connectors.postgresConnector.Activator.start(Activator.java:18)
at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:645)
at org.apache.felix.framework.Felix.activateBundle(Felix.java:2146)
... 20 more
Caused by: org.flywaydb.core.api.FlywayException: Unable to instantiate class org.flywaydb.core.internal.logging.javautil.JavaUtilLogCreator : org.flywaydb.core.internal.logging.javautil.JavaUtilLogCreator
at org.flywaydb.core.internal.util.ClassUtils.instantiate(ClassUtils.java:63)[2348:org.flywaydb.core:5.2.4]
at org.flywaydb.core.internal.logging.LogCreatorFactory.getLogCreator(LogCreatorFactory.java:46)[2348:org.flywaydb.core:5.2.4]
at org.flywaydb.core.api.logging.LogFactory.getLog(LogFactory.java:78)[2348:org.flywaydb.core:5.2.4]
at org.flywaydb.core.internal.util.ClassUtils.<clinit>(ClassUtils.java:39)[2348:org.flywaydb.core:5.2.4]
... 30 more
Caused by: java.lang.ClassNotFoundException: org.flywaydb.core.internal.logging.javautil.JavaUtilLogCreator
at java.net.URLClassLoader.findClass(Unknown Source)[:1.8.0_212]
at java.lang.ClassLoader.loadClass(Unknown Source)[:1.8.0_212]
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)[:1.8.0_212]
at java.lang.ClassLoader.loadClass(Unknown Source)[:1.8.0_212]
at java.lang.Class.forName0(Native Method)[:1.8.0_212]
at java.lang.Class.forName(Unknown Source)[:1.8.0_212]
at org.flywaydb.core.internal.util.ClassUtils.instantiate(ClassUtils.java:61)[2348:org.flywaydb.core:5.2.4]
... 33 more
So, I just have no idea what's wrong here, I've used simpliest example from official Flyway's site and get this errors.
I've already try to delete my own Logger. I thought it can let FlyWay to use it's logger, but everything goes the same way (same errors).
Could you help me?
P.S. Looks like this pull request somehow related to my problem.
Indeed it seems Flyway might have issues in OSGi. Maybe you can provide them an issue and your example.
Another issue with your example is that you try to access the DataSource via a url. This does not work in OSGi. The reason is that this way flyway has to have direct access to the database driver classes. This does not work in OSGi.
In OSGi the way to access a Database is with a DataSourceFactory which the database driver creates as a service. From this factory you can create a DataSource.
As not all database drivers offer this service there is pax-jdbc which provides factories for all common databases. It also allows to create a DataSource including pooling from a OSGi config.
Your approach of migrating on bundle start is a very bad idea. The methods in the activator must return quickly and a databse migration might take a while. Of course you want to make sure the migration takes place before any bundle in the system accesses the database. Fortunately there is a way to hook into the DataSource creation to do things like a migration.
See the liquibase tutorial which also shows a database migration. It uses the PreHook offered by pax-jdbc which makes sure your migration code is run before the DataSource is given to any other bundle.
I managed to avoid this error by setting a custom LogFactory before entering flyway's migration code. The basic idea is presented in this sample commit
Related
Recently I've been trying to set and customize scheduler in our XPages project. I've tried to put the following snippet in our project:
import org.eclipse.core.runtime.Plugin;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator extends Plugin implements BundleActivator {
#Override
public void start(final BundleContext context) throws Exception {
// Here you start your scheduler
}
}
In the Code section of a template I can easily write this code I don't have a warning about unresolved dependencies. So, the org.eclipse.core.runtime and org.osgi.framework packages must be shipped with Domino I thought.
But it seems that it does not.
Whenever this code is executed I get 500 error in a browser and the stack as follows:
javax.servlet.ServletException: java.lang.NoClassDefFoundError: org.eclipse.core.runtime.Plugin
at com.ibm.xsp.webapp.FacesServlet.handleError(FacesServlet.java:595)
at com.ibm.xsp.webapp.FacesServlet.renderErrorPage(FacesServlet.java:424)
at com.ibm.xsp.webapp.FacesServlet.service(FacesServlet.java:182)
at com.ibm.xsp.webapp.FacesServletEx.service(FacesServletEx.java:138)
at com.ibm.xsp.webapp.DesignerFacesServlet.service(DesignerFacesServlet.java:103)
at com.ibm.designer.runtime.domino.adapter.ComponentModule.invokeServlet(ComponentModule.java:588)
at com.ibm.domino.xsp.module.nsf.NSFComponentModule.invokeServlet(NSFComponentModule.java:1335)
at com.ibm.designer.runtime.domino.adapter.ComponentModule$AdapterInvoker.invokeServlet(ComponentModule.java:865)
at com.ibm.designer.runtime.domino.adapter.ComponentModule$ServletInvoker.doService(ComponentModule.java:808)
at com.ibm.designer.runtime.domino.adapter.ComponentModule.doService(ComponentModule.java:577)
at com.ibm.domino.xsp.module.nsf.NSFComponentModule.doService(NSFComponentModule.java:1319)
at com.ibm.domino.xsp.module.nsf.NSFService.doServiceInternal(NSFService.java:662)
at com.ibm.domino.xsp.module.nsf.NSFService.doService(NSFService.java:482)
at com.ibm.designer.runtime.domino.adapter.LCDEnvironment.doService(LCDEnvironment.java:357)
at com.ibm.designer.runtime.domino.adapter.LCDEnvironment.service(LCDEnvironment.java:313)
at com.ibm.domino.xsp.bridge.http.engine.XspCmdManager.service(XspCmdManager.java:272)
Caused by: java.lang.NoClassDefFoundError: org.eclipse.core.runtime.Plugin
at java.lang.ClassLoader.defineClassImpl(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:346)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:154)
at com.ibm.domino.xsp.module.nsf.ModuleClassLoader$DynamicClassLoader.findClass(ModuleClassLoader.java:455)
at java.lang.ClassLoader.loadClassHelper(ClassLoader.java:850)
at java.lang.ClassLoader.loadClass(ClassLoader.java:829)
at com.ibm.domino.xsp.module.nsf.ModuleClassLoader$DynamicClassLoader.loadClass(ModuleClassLoader.java:403)
at java.lang.ClassLoader.loadClass(ClassLoader.java:809)
at ru.lanit.egrz.scheduler.RefreshEGRZTokenExecutor.executeAndScheduleRefreshToken(RefreshEGRZTokenExecutor.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
at java.lang.reflect.Method.invoke(Method.java:508)
at com.ibm.jscript.types.JavaAccessObject.call(JavaAccessObject.java:322)
at com.ibm.jscript.types.FBSObject.call(FBSObject.java:161)
at com.ibm.jscript.ASTTree.ASTCall.interpret(ASTCall.java:197)
at com.ibm.jscript.ASTTree.ASTProgram.interpret(ASTProgram.java:119)
at com.ibm.jscript.ASTTree.ASTProgram.interpretEx(ASTProgram.java:139)
at com.ibm.jscript.JSExpression._interpretExpression(JSExpression.java:435)
at com.ibm.jscript.JSExpression.access$1(JSExpression.java:424)
at com.ibm.jscript.JSExpression$2.run(JSExpression.java:414)
at java.security.AccessController.doPrivileged(AccessController.java:686)
at com.ibm.jscript.JSExpression.interpretExpression(JSExpression.java:410)
at com.ibm.jscript.JSExpression.evaluateValue(JSExpression.java:251)
at com.ibm.jscript.JSExpression.evaluateValue(JSExpression.java:234)
at com.ibm.xsp.javascript.JavaScriptInterpreter.interpret(JavaScriptInterpreter.java:222)
at com.ibm.xsp.binding.javascript.JavaScriptMethodBinding.invoke(JavaScriptMethodBinding.java:111)
at com.ibm.xsp.application.ActionListenerImpl.processAction(ActionListenerImpl.java:60)
at javax.faces.component.UICommand.broadcast(UICommand.java:324)
at com.ibm.xsp.component.UIEventHandler.broadcast(UIEventHandler.java:366)
at com.ibm.xsp.component.UIDataPanelBase.broadcast(UIDataPanelBase.java:400)
at com.ibm.xsp.component.UIViewRootEx.broadcast(UIViewRootEx.java:1535)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:307)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:428)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:94)
at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:210)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:96)
at com.ibm.xsp.controller.FacesControllerImpl.execute(FacesControllerImpl.java:256)
at com.ibm.xsp.webapp.FacesServlet.serviceView(FacesServlet.java:227)
at com.ibm.xsp.webapp.FacesServletEx.serviceView(FacesServletEx.java:157)
at com.ibm.xsp.webapp.FacesServlet.service(FacesServlet.java:159)
... 13 more
Caused by: java.lang.ClassNotFoundException: org.eclipse.core.runtime.Plugin
at com.ibm.domino.xsp.module.nsf.ModuleClassLoader$DynamicClassLoader.loadClass(ModuleClassLoader.java:359)
at java.lang.ClassLoader.loadClass(ClassLoader.java:809)
... 54 more
IBM literally freaks me out over and over and over again (sorry for that).
I tried to add it as external jars in the section -> Still the same.
I even tried to add these two to lib/ext -> Still the same.
In the build path these two included as Plug-In Dependencies.
Literally, there's something wrong with importing jars and resolving dependencies in Domino (even beyond the scope of this particular problem) I believe.
This is my 3rd if not 4th question on IBM Domino. I sincerely apologize to the community for being that embarrassing but get me right please. In Domino you solve one problem and then the other two emerge. You solve these two and then the other 4 break the app down. And so on
How do I import it correctly without any problems?
Thanks in advance
UPD
To improve my question I'll add some code
So, the bean looks like this:
SchedulerActivatorBean:
import java.io.Serializable;
public class SchedulerActivatorBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3559937702716018697L;
public static void activate() throws Exception
{
new SchedulerActivator().start(null);
}
}
SchedulerActivator (OSGI plugin):
import org.eclipse.core.runtime.Plugin;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class SchedulerActivator extends Plugin implements BundleActivator {
#Override
public void start(final BundleContext context) throws Exception {
// Here you start your scheduler
QuartzScheduler.getInstance(); // starts the scheduler
}
}
Then I modified faces-config.xml as follows:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config>
<managed-bean>
<managed-bean-name>schedulerActivatorBean</managed-bean-name>
<managed-bean-class>ru.lanit.egrz.scheduler.SchedulerActivatorBean</managed-bean-class>
<managed-bean-scope>application</managed-bean-scope>
</managed-bean>
</faces-config>
And finally I call the bean from SSJS:
<xp:eventHandler event="onclick" submit="true"
refreshMode="complete"
action="#{javascript:schedulerActivatorBean.activate()}">
</xp:eventHandler>
The bean is instantiated and available in the app. But when I call the method, I still get:
Caused by: java.lang.ClassNotFoundException: org.eclipse.core.runtime.Plugin
at com.ibm.domino.xsp.module.nsf.ModuleClassLoader$DynamicClassLoader.loadClass(ModuleClassLoader.java:359)
at java.lang.ClassLoader.loadClass(ClassLoader.java:809)
... 54 more
Which, needless to say, left me clueless
A plugin doesn’t live in the NSF. You might want to learn about that first. Use this as a starter: https://www.slideshare.net/fiorep/domino-osgi-development
You might want to revisit your whole approach. Why not use a Notes agent that is scheduled and refreshes token which you store in an NSF. Simple problem solved.
Then have your XPage lookup the values in the NSF. Saves you the whole headache.
For new users you can use agent.run from XPages. The trick is the storage in the NSF.
Use reader fields to secure documents, so users can’t see each other tokens.
Currently I am using AspectJ Load Time Weaving to intercept the constructor of a base entity for auditing purposes. However when running the application I am getting incredibly inconsistent results revolving around the aspectOf() method that aspectJ weaves into LTW classes.
In some cases the application runs, the weaving is done correctly, and the code is functioning as expected. Other times I am met with:
java.lang.NoSuchMethodException: ca.gc.cfp.core.cfpws.repository.aspect.BaseEntityAspect.aspectOf()
Currently I am using https://github.com/subes/invesdwin-instrument to dynamically attach the instrumentation agent into the JVM so our deployment guys don't need to do any extra configuration.
My Spring application main:
#SpringBootApplication
#EntityScan(basePackages = {"ca.gc.cfp.model"})
public class CfpWsApplication {
public static void main(final String[] args) {
DynamicInstrumentationLoader.waitForInitialized();
DynamicInstrumentationLoader.initLoadTimeWeavingContext();
if (!InstrumentationLoadTimeWeaver.isInstrumentationAvailable()) {
throw new IllegalStateException(
"Instrumentation is not available AspectJ weaver will not function.");
}
SpringApplication.run(CfpWsApplication.class, args);
}
The LTW Aspect:
#Aspect
public class BaseEntityAspect {
Logger logger = LoggerFactory.getLogger(BaseEntityAspect.class);
/** Application context property needed to fetch the AuditDate bean */
#Autowired private ApplicationContext context;
#AfterReturning(
"onBaseEntityCreated() && !within(ca.gc.cfp.core.cfpws.repository.aspect.BaseEntityAspect)")
public void injectAuditTimeStamp(JoinPoint joinPoint) {
try {
AuditDate auditDate = context.getBean(AuditDate.class);
Object entityTarget = joinPoint.getTarget();
// Inject the auditing date for this Entity instance
if (entityTarget instanceof BaseEntity) {
BaseEntity baseEnt = (BaseEntity) entityTarget;
baseEnt.setAuditDate(auditDate.getAuditingTimeStamp());
}
} catch (NullPointerException e) {
logger.error(
e.getMessage()
+ " Not yet in the conext of an httpRequest, the AuditDate bean has not yet been instantiated.");
}
}
#Pointcut(
"execution(ca.gc.cfp.model.entity.BaseEntity.new(..)) && !within(ca.gc.cfp.core.cfpws.repository.aspect.BaseEntityAspect)")
public void onBaseEntityCreated() {}
}
The Aspect config class with a temporary factory method using the Aspects utils to let spring know it should ask aspectJ for the woven Aspect:
#Configuration
#EnableAspectJAutoProxy
public class AspectConfig {
/**
* Static factory for access to the load time woven aspect. This allows the aspect to be injected
* with the application context and beans from the spring IoC
*/
#Bean
public BaseEntityAspect getBaseEntityAspect() {
return Aspects.aspectOf(BaseEntityAspect.class);
}
}
aop.xml:
<aspectj>
<weaver options="-verbose -showWeaveInfo -Xreweavable -debug">
<include within="ca.gc.cfp.model" />
<include within="ca.gc.cfp.model..*" />
<include within="ca.gc.cfp.core.cfpws.repository.aspect..*"/>
</weaver>
<aspects>
<aspect name="ca.gc.cfp.core.cfpws.repository.aspect.BaseEntityAspect" />
</aspects>
</aspectj>
In a lot of cases when I run with this configuration I get the following:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [ca.gc.cfp.core.cfpws.repository.aspect.BaseEntityAspect]: Factory method 'getBaseEntityAspect' threw exception; nested exception is org.aspectj.lang.NoAspectBoundException: Exception while initializing ca.gc.cfp.core.cfpws.repository.aspect.BaseEntityAspect: java.lang.NoSuchMethodException: ca.gc.cfp.core.cfpws.repository.aspect.BaseEntityAspect.aspectOf()
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
... 19 common frames omitted
Caused by: org.aspectj.lang.NoAspectBoundException: Exception while initializing ca.gc.cfp.core.cfpws.repository.aspect.BaseEntityAspect: java.lang.NoSuchMethodException: ca.gc.cfp.core.cfpws.repository.aspect.BaseEntityAspect.aspectOf()
at org.aspectj.lang.Aspects.aspectOf(Aspects.java:50) ~[aspectjrt-1.9.4.jar:1.9.4]
at ca.gc.cfp.core.cfpws.configuration.AspectConfig.getBaseEntityAspect(AspectConfig.java:22) ~[classes/:na]
at ca.gc.cfp.core.cfpws.configuration.AspectConfig$$EnhancerBySpringCGLIB$$1cae4c58.CGLIB$getBaseEntityAspect$0(<generated>) ~[classes/:na]
at ca.gc.cfp.core.cfpws.configuration.AspectConfig$$EnhancerBySpringCGLIB$$1cae4c58$$FastClassBySpringCGLIB$$84edb9e.invoke(<generated>) ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at ca.gc.cfp.core.cfpws.configuration.AspectConfig$$EnhancerBySpringCGLIB$$1cae4c58.getBaseEntityAspect(<generated>) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_211]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_211]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_211]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_211]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
... 20 common frames omitted
Caused by: java.lang.NoSuchMethodException: ca.gc.cfp.core.cfpws.repository.aspect.BaseEntityAspect.aspectOf()
at java.lang.Class.getDeclaredMethod(Class.java:2130) ~[na:1.8.0_211]
at org.aspectj.lang.Aspects.getSingletonOrThreadAspectOf(Aspects.java:134) ~[aspectjrt-1.9.4.jar:1.9.4]
at org.aspectj.lang.Aspects.aspectOf(Aspects.java:45) ~[aspectjrt-1.9.4.jar:1.9.4]
... 31 common frames omitted
However this is not always the case, occasionally the application runs just fine, the code executes as expected and there are no issues. This has been eluding me for a couple weeks now and I cannot seem to figure out what could be causing this code to occasionally work and occasionally not work. Could it be that CGLIB proxies are hiding the aspectOf() method from the compiler??
EDIT / UPDATE: I was able to remove the use of the above third party dependency for dynamically loading the java agent into the Spring application context. I instead used javaagent arguments and it is working fine from within my IDE. However building and running via Maven in a terminal is still causing issues. I've specified the javaagent argument via the Environment variable : MAVEN_OPTS. After doing so maven seems to be picking it up but my class still isn't being woven.
With regard to your own answer: The AspectJ Maven plugin helps you with compile-time weaving (CTW), not load-time weaving (LTW). For LTW you need to make sure that the weaving agent is active before any of the target classes have been loaded because LTW works at class-loader level. AspectJ Maven is only necessary if either you use aspects in native syntax (not annotation-based) or you want to use CTW.
I don't know about this invesdwin-instrument tool, but the AspectJ weaver offers its own capability to attach it during runtime. A third-party tool should not be necessary. Anyway, I do recommend to modify the Java command line in order to ensure the weaving agent is in place before anything else is loaded in your container. Your deployment guys ought to help you make sure that the -javaagent:... parameter is there. It is their job! To work around that in order to make life easier for them but the behaviour of your application potentially unpredictable is not going to improve its stability.
As per Kieveli's comment. My TL was thinking similarly. I'm new to Maven, Spring boot, and AOP. Looking into it externally run Maven and the build from within Eclipse seem to be "clobbering" one another.
I've been using maven via MINGW64 to clean / install / build, and the project doesn't specify usage of the AspectJ compiler which is likely why the factory method is not being woven into the class.
We're discussing a solution to this as we use Jenkins for build automation on our server. I am thinking that this Maven plugin may be the solution. https://www.mojohaus.org/aspectj-maven-plugin/
I am fairly new to the hibernate framework and I'm creating a simple application with a Udemy course. I've continually been getting a 'java.lang.NoClassDefFoundError' on the following stack. It appears that when I create a org.hibernate.cfg.Configuration object the exception is thrown. Any guidance would be appreciated on how to solve the following issue, is it possible that this hibernate version is buggy and I need to backtrack to a previous version?
Hibernate-Core Version: 5.3.0.Final
Hibernate-Annotations: 3.5.6.Final
My-SQL Server Version: 8.0.12
DEBUG - Logging Provider: org.jboss.logging.Log4jLoggerProvider
DEBUG - Adding Integrator [org.hibernate.cfg.beanvalidation.BeanValidationIntegrator].
DEBUG - Adding Integrator [org.hibernate.secure.spi.JaccIntegrator].
DEBUG - Adding Integrator [org.hibernate.cache.internal.CollectionCacheInvalidator].
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
at org.hibernate.boot.spi.XmlMappingBinderAccess.<init>(XmlMappingBinderAccess.java:43)
at org.hibernate.boot.MetadataSources.<init>(MetadataSources.java:86)
at org.hibernate.cfg.Configuration.<init>(Configuration.java:123)
at org.hibernate.cfg.Configuration.<init>(Configuration.java:118)
at com.dataPack.data.HibernateUtil.buildSessionFactory(HibernateUtil.java:16)
at com.dataPack.data.HibernateUtil.<clinit>(HibernateUtil.java:10)
at com.dataPack.data.Application.main(Application.java:9)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.JAXBException
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
... 7 more
Here is the HibernateUtil class I created to build the sessionFactory.
package com.dataPack.data;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
Configuration configuration = null;
try {
configuration = new Configuration();
return configuration
.buildSessionFactory(new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build());
} catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("Issue Building Session Factory!");
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Here is the hibernate.properties file we are suppose to use.
hibernate.connection.username=user
hibernate.connection.password=password
hibernate.connection.url=jdbc:mysql://localhost:3306/ifinances
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
Since this project is known to work, it's likely that others have used a different Java version as the jaxb Apis were removed from Java SE. There are multiple ways to address this (as detailed in How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException in Java 9 ) but the most reliable is to add the jaxb API dependency (groupId javax.xml.bind, artifactId jaxb-api -https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api/2.3.0) to the pom.xml or gradle build file.
Then rebuild and if you still hit ClassNotFound errors then see https://stackoverflow.com/a/43574427/9705485
I have problems using a OSGI-Service in a camel route. Read tutorial-osgi-camel-part1
but didn't get it to work.
The setup:
bundle 1 defines a Service interface (separate bundle for interface because there can be several implementations of it)
bundle 2 implements this interface
bundle 3 should use bundle 2 that provides interface from bundle 1
In bundle 2 (the implementation) are the two xml files, one with
<osgi:service ref="invokeService">
<osgi:interfaces>
<value>invoker.Invoker</value>
</osgi:interfaces>
</osgi:service>
and the other with
<bean id="invokeService" class="invokerImpl.InvokerImpl">
</bean>
Bundle 3 has a xml file with
<osgi:reference id="invokeService" interface="invoker.Invoker"/>
in it.
Bundle 3 and the CamelContext is started with
#Override
public void start(BundleContext bundleContext) throws Exception {
OsgiDefaultCamelContext camelContext = new OsgiDefaultCamelContext(bundleContext);
camelContext.addRoutes(new ExampleRoute());
camelContext.start();
}
In my route I want to use the Service (from bundle 2) with
.to("bean:invokeService")
Exception I get:
19:14:39.953 TRACE o.a.camel.core.osgi.OsgiClassResolver:42 Resolve class invokeService
19:14:39.969 TRACE o.a.camel.core.osgi.OsgiClassResolver:84 Cannot load class: invokeService using classloader: CamleOSGIExample_1.0.0.qualifier [254]. This exception be ignored.
java.lang.ClassNotFoundException: invokeService
at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:513) ~[na:na]
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:429) ~[na:na]
(...)
and
org.apache.camel.NoSuchBeanException: No bean could be found in the registry for: invokeService
at org.apache.camel.component.bean.RegistryBean.getBean(RegistryBean.java:68) ~[camel-core-2.10.3.jar:2.10.3]
at org.apache.camel.component.bean.BeanProcessor.process(BeanProcessor.java:83) ~[camel-core-2.10.3.jar:2.10.3]
I'm using Equinox.
Also discussed here and with the solution:
http://camel.465427.n5.nabble.com/Problems-using-a-osgi-bundle-in-a-camel-route-tp5728064.html
Here's my Java class
import endpoint.NewSessionRemote;
import javax.naming.Context;
import javax.naming.InitialContext;
public class HelloClient {
public static void main(String[] args) {
try {
Context ctx = new InitialContext();
NewSessionRemote hello = (NewSessionRemote) ctx.lookup("endpoint.NewSessionRemote");
System.out.println(hello.stringChange(4));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
When I run this class I'm getting an exception.
javax.naming.NameNotFoundException: endpoint.NewSessionRemote not found
at com.sun.enterprise.naming.TransientContext.doLookup(TransientContext.java:216)
at com.sun.enterprise.naming.TransientContext.lookup(TransientContext.java:188)
at com.sun.enterprise.naming.SerialContextProviderImpl.lookup(SerialContextProviderImpl.java:74)
at com.sun.enterprise.naming.RemoteSerialContextProviderImpl.lookup(RemoteSerialContextProviderImpl.java:129)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:154)
at com.sun.corba.ee.impl.protocol.CorbaServerRequestDispatcherImpl.dispatchToServant(CorbaServerRequestDispatcherImpl.java:687)
at com.sun.corba.ee.impl.protocol.CorbaServerRequestDispatcherImpl.dispatch(CorbaServerRequestDispatcherImpl.java:227)
at com.sun.corba.ee.impl.protocol.CorbaMessageMediatorImpl.handleRequestRequest(CorbaMessageMediatorImpl.java:1846)
at com.sun.corba.ee.impl.protocol.CorbaMessageMediatorImpl.handleRequest(CorbaMessageMediatorImpl.java:1706)
at com.sun.corba.ee.impl.protocol.CorbaMessageMediatorImpl.handleInput(CorbaMessageMediatorImpl.java:1088)
at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:223)
at com.sun.corba.ee.impl.protocol.CorbaMessageMediatorImpl.handleRequest(CorbaMessageMediatorImpl.java:806)
at com.sun.corba.ee.impl.protocol.CorbaMessageMediatorImpl.dispatch(CorbaMessageMediatorImpl.java:563)
at com.sun.corba.ee.impl.protocol.CorbaMessageMediatorImpl.doWork(CorbaMessageMediatorImpl.java:2567)
at com.sun.corba.ee.impl.orbutil.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:555)
java.lang.NullPointerException
All the other enterprise bean classes are written according to the EJB 3.0 standard.
Your valuable contribution is expected.
Solution
The exception was
javax.naming.NameNotFoundException: endpoint.NewSessionRemote not found
It occurs because the JNDI name that was given by the application side didn't match the servser's (Glassfish) actual JNDI name, so I did was check the JNDI tree in Glassish through its admin console (vendor specific) and I did notice that the JNDI for the NewSessionRemote interface (which is the business interface of the session bean NewSessionBean) is different from the name which I have given in the application side. So how did this happen then suddenly something came in to my mind that's the ejb-jar.xml there is another name JNDI name assigned to the same NewSessionRemote using tag. So I simply remove it and redeploy EJB module. That's it.
Looks like you have no RMI registry (i.e. active server) you are lookingUp() against.
You supplied no Context.INITIAL_CONTEXT_FACTORY variable, so the lookup should be a valid URL, which it is not.
Hence, you should put something like this on your env (on the iCtx):
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
I suggest you read the the simple examples over at http://java.sun.com/j2se/1.5.0/docs/guide/jndi/jndi-rmi.html
When using JNDI, you're using an API that requires a specific configuration underlying it in order to connect to the server (see the Javadoc for details on what that configuration is). For example, java.naming.factory.initial is the property which indicates which implementation of JNDI you want to use.
Now, when running code inside a JavaEE server, this configuration is available implicitly, and all you need to do is what you have done in your code - instantiate InitialContext, and perform a lookup. However, when running outside the server, this implicit configuration is not present, and so you need to configure your InitialContext explicitly.
Your sample code uses a main() method, which suggests that you're running outside the container. The config you need will depend on your specific application server, you'll need to look up that documentation to see what config to supply.