Reusable aspects jar - aop

We are going to start using aspectsJ in our production Java standalone apps soon. So, I am trying to come up with a jar that has aspects so I can weave them to the production apps without any code change.
I am trying to create a separate project (MyAspects.jar)for aspects and include them to the existing java class path to minimize code changes. While I am adding the aop.xml to the production application jar's META-INF folder.
While running the app, I am using -javaagent:pathto\aspectjweaver.jar and include MyAspects.jar in the folder that is on the classpath.
But when execute it, it errors out with below details. Including whole stacktrace.
I am using aspectjweaver-1.8.4.jar.
[AppClassLoader#553f5d07] info AspectJ Weaver Version 1.8.4 built on Thursday Nov 6, 2014 at 20:19:21 GMT
[AppClassLoader#553f5d07] info register classloader sun.misc.Launcher$AppClassLoader#553f5d07
[AppClassLoader#553f5d07] info using configuration file:/C:/riskEventLoader/lib/risk-event-loader.jar!/META-INF/aop.xml
[AppClassLoader#553f5d07] info register aspect com.aspect.generic.GenericAspect
Jan 12, 2015 8:37:15 AM org.aspectj.weaver.tools.Jdk14Trace error
SEVERE: register definition failed java.lang.RuntimeException: Cannot register non aspect: com$aspect$generic$GenericAspect , com.aspect.generic.GenericAspect
at org.aspectj.weaver.bcel.BcelWeaver.addLibraryAspect(BcelWeaver.java:219)
at org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor.registerAspects(ClassLoaderWeavingAdaptor.java:485)
at org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor.registerDefinitions(ClassLoaderWeavingAdaptor.java:304)
at org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor.initialize(ClassLoaderWeavingAdaptor.java:171)
at org.aspectj.weaver.loadtime.Aj$ExplicitlyInitializedClassLoaderWeavingAdaptor.initialize(Aj.java:340)
at org.aspectj.weaver.loadtime.Aj$ExplicitlyInitializedClassLoaderWeavingAdaptor.getWeavingAdaptor(Aj.java:345)
at org.aspectj.weaver.loadtime.Aj$WeaverContainer.getWeaver(Aj.java:319)
at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:113)
at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:54)
at sun.instrument.TransformerManager.transform(TransformerManager.java:169)
at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:365)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Edit (by kriegaex):
I am adding some code snippets here which were previously posted as comments so as to make them more readable and qualify the question for reopening.
Aspect:
Please note that I have fixed some syntax errors, namely missing leading * signifying method return type in the two execution() pointcuts. I also simplified the logging statements.
package com.aspect.generic;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
#Aspect
public class GenericAspect {
#Pointcut("execution(* *(..))")
public void myTraceCall() {}
#Around("execution(* com.test.riskcheck..*(..))")
public Object myTrace(ProceedingJoinPoint thisJoinPoint) throws Throwable {
System.out.println("[BEFORE] " + thisJoinPoint);
Object retVal = null;
try {
retVal = thisJoinPoint.proceed();
} finally {
System.out.println("[AFTER] " + thisJoinPoint + " -> retval = " + retVal);
}
return retVal;
}
}
AspectJ LTW configuration file aop.xml:
I also simplified this file a bit. It still exposes the same problem as the one posted by the question's author for the same reason.
<?xml version="1.0" encoding="UTF-8"?>
<aspectj>
<aspects>
<aspect name="com.aspect.generic.GenericAspect"/>
</aspects>
<weaver options="-verbose -showWeaveInfo">
<include within="com.test.riskcheck..*"/>
</weaver>
</aspectj>

Related

Room Migration test failing : schema not found

I'm try to implement android test for my room database, to test migrations. For this, I generated the schema needed, and I follow the step from the Android documentation.
When I run my migration test, it shows that the schema cannot be loaded, despite I added the assets line in the Gradle build. I added multiple other build types, it was not helping. I'm making something wrong, but I can't find where.
Room Version : 2.3.0
The error :
Cannot find the schema file in the assets folder. Make sure to include the exported json schemas in your test assert inputs. See https://developer.android.com/training/data-storage/room/migrating-db-versions#export-schema for details. Missing file: Asset file database.Sauvegarde/1.json not found
java.io.FileNotFoundException: Cannot find the schema file in the assets folder. Make sure to include the exported json schemas in your test assert inputs. See https://developer.android.com/training/data-storage/room/migrating-db-versions#export-schema for details. Missing file: Asset file database.Sauvegarde/1.json not found
at androidx.room.testing.MigrationTestHelper.loadSchema(MigrationTestHelper.java:326)
at androidx.room.testing.MigrationTestHelper.createDatabase(MigrationTestHelper.java:152)
at globalTests.migrations.MigrationTest.migrate1To2(MigrationTest.java:31)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:61)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.robolectric.RobolectricTestRunner$HelperTestRunner$1.evaluate(RobolectricTestRunner.java:575)
at org.robolectric.internal.SandboxTestRunner$2.lambda$evaluate$0(SandboxTestRunner.java:263)
at org.robolectric.internal.bytecode.Sandbox.lambda$runOnMainThread$0(Sandbox.java:89)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
In test structure:
MigrationTest :
package globalTests.migrations;
import ...;
#RunWith(AndroidJUnit4.class)
public class MigrationTest {
private static final String TEST_DB = "migration-test";
#Rule
public MigrationTestHelper helper;
public MigrationTest() {
helper = new MigrationTestHelper(InstrumentationRegistry.getInstrumentation(),
Sauvegarde.class.getCanonicalName(),
new FrameworkSQLiteOpenHelperFactory());
}
#Test
public void migrate1To2() throws IOException {
SupportSQLiteDatabase db = helper.createDatabase(TEST_DB, 1);
// Prepare for the next version.
db.close();
// Re-open the database with version 2 and provide
// MIGRATION_1_2 as the migration process.
db = helper.runMigrationsAndValidate(TEST_DB, 2, true, Migrations.MIGRATION_1_2);
// MigrationTestHelper automatically verifies the schema changes,
// but you need to validate that the data was migrated properly.
}
}
gradle.build :
testOptions {
execution 'ANDROIDX_TEST_ORCHESTRATOR'
}
javaCompileOptions {
annotationProcessorOptions {
arguments += ["room.schemaLocation":
"$projectDir/schemas".toString()]
}
}
sourceSets {
// Adds exported schema location as test app assets.
debug.assets.srcDirs += files("$projectDir/schemas".toString())
customDebugType.assets.srcDirs += files("$projectDir/schemas".toString())
androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
test.assets.srcDirs += files("$projectDir/schemas".toString())
}
In schemas location :
The problem is like this one, but the solution not worked for me ...
Speaking from experience, one possible source of this issue is the stripping of assets during packaging, i.e., if you have something like the rule below. It seems like it should apply to the release build only, but, alas, it applies do debug as well and will remove your schema files from view.
buildTypes {
debug {...}
release {
aaptOptions {
ignoreAssetsPattern '!*.json'
}
}
}
Something else you could do is to look at what assets are visible to the various contexts you have available to you in the test itself:
println("Instrumentation context.assets")
var assets = InstrumentationRegistry.getInstrumentation().context.assets
assets.list("")?.forEachIndexed { index, it ->
println("$index -> $it")
}
println("Instrumentation targetContext.assets")
assets = InstrumentationRegistry.getInstrumentation().targetContext.assets
assets.list("")?.forEachIndexed { index, it ->
println("$index -> $it")
}
println("ApplicationProvider context.assets")
assets = ApplicationProvider.getApplicationContext<App>().assets
assets.list("")?.forEachIndexed { index, it ->
println("$index -> $it")
}
I found the problem,
Roboelectric didn't import my Android resources for the tests
you need to add this to Gradle:
testOptions {
unitTests{
includeAndroidResources = true
}
}
Source

Formatting LocalDateTime for JAX-RS

I'm using resteasy-jaxrs in combination with jackson-datatype-jsr310 to serialize LocalDateTime in the response. This works fine for properties in my classes because I can add the necessary annotation like
#XmlJavaTypeAdapter(LocalDateTimeAdapter.class)
public LocalDateTime getExpirationDate() {
return expirationDate;
}
using the LocalDateTimeAdapter
public class LocalDateTimeAdapter extends XmlAdapter<String, LocalDateTime> {
#Override
public LocalDateTime unmarshal(String s) throws Exception {
return LocalDateTime.parse(s);
}
#Override
public String marshal(LocalDateTime dateTime) throws Exception {
return dateTime.toString();
}
}
In the json I get something like
"expirationDate": "2026-07-17T23:59:59"
But I've a map of objects and this map also can have items of type LocalDateTime and for those there is no annotation and so I get the full object in the json response like
"effectiveDate": {
"dayOfMonth": 1,
"dayOfWeek": "FRIDAY",
"month": "JUNE",
"year": 2018, ...
Is there a way to format every LocalDateTime field, no matter where it comes from?
UPDATE after Paul's answer
Since I already hat the com.fasterxml.jackson.datatype:jackson-datatype-jsr310 dependency, I added the ObjectMapperContextResolver class and removed the annotation from my LocalDateTime property. Sadly all LocalDateTimes were now serialized as full object again. In the comments of the post I saw that someone added a context-param to the web.xml so that the ObjectMapperContextResolver gets picked up. After adding this to my web.xml, it looks like this.
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>Servlet 3.1 Web Application</display-name>
<listener>
<listener-class>com.kopi.web.InitListener</listener-class>
</listener>
<context-param>
<param-name>resteasy.resources</param-name>
<param-value>com.kopi.utils.ObjectMapperContextResolver</param-value>
</context-param>
</web-app>
Now since adding the context-param resteasy.resources, the webapp doesn't start anymore due to
SEVERE: Servlet [com.kopi.rest.RestApplication] in web application [/kopi] threw load() exception
java.lang.RuntimeException: RESTEASY003130: Class is not a root resource. It, or one of its interfaces must be annotated with #Path: com.kopi.utils.ObjectMapperContextResolver implements: javax.ws.rs.ext.ContextResolver
at org.jboss.resteasy.core.ResourceMethodRegistry.addResourceFactory(ResourceMethodRegistry.java:179)
at org.jboss.resteasy.core.ResourceMethodRegistry.addResourceFactory(ResourceMethodRegistry.java:158)
at org.jboss.resteasy.core.ResourceMethodRegistry.addPerRequestResource(ResourceMethodRegistry.java:77)
at org.jboss.resteasy.spi.ResteasyDeployment.registration(ResteasyDeployment.java:482)
at org.jboss.resteasy.spi.ResteasyDeployment.startInternal(ResteasyDeployment.java:279)
at org.jboss.resteasy.spi.ResteasyDeployment.start(ResteasyDeployment.java:86)
at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.init(ServletContainerDispatcher.java:119)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.init(HttpServletDispatcher.java:36)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1194)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1110)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1000)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4902)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5212)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:152)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:724)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:700)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:596)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1805)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
In other comments I saw that versions might be an issue. So I'm currently using
org.jboss.resteasy:resteasy-jaxrs 3.5.1.Final
org.jboss.resteasy:resteasy-jackson-provider 3.5.1.Final
org.jboss.resteasy:resteasy-servlet-initializer 3.5.1.Final
com.fasterxml.jackson.datatype:jackson-datatype-jsr310 2.9.5
Thank you, kopi
Instead of the XmlAdapter which you need to declare on individual properties, you could just configure it globally with Jackson using a ContextResolver. This is where you can configure the ObjectMapper and register the JavaTimeModule with the mapper. This configuration will be global so you don't need to use the XmlAdapter. To see how you can configure this, you can see this post.
#XmlJavaTypeAdapter can apply to a whole package (see doc).
When #XmlJavaTypeAdapter annotation is defined at the package level it
applies to all references from within the package to
#XmlJavaTypeAdapter.type().
Try to add the file package-info.java next to the class that has the map. Given the package of the class is com.acme.beans and that of the adapter is com.acme.adapters, the content of the file should be something like:
#XmlJavaTypeAdapter(LocalDateTimeAdapter.class)
package com.acme.beans;
import com.acme.adapters.LocalDateTimeAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

Velocity Initialization failing

I am using velocity as Java Code Generator, I am running a Eclipse application which has multiple plugins and different plugins are calling Velocity module for code generation.
Whenever i run a particular plugin it works fine individually no matter how many times i run it , Now if i will try to run the other plugin it throws velocity exception(i have provided stack trace below), I will restart the eclipse again and other plugin will work fine.
Conclusion: Velocity initialization fails when one plugin runs after some plugin already executed
The code i was using
velocityEngine = new VelocityEngine();
velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, LOCATION);
velocityEngine.setProperty(RESOURCE_LOADER,ClasspathResourceLoader.class.getName());
try {
velocityEngine.init();
} catch (Exception e) {
LOG.error("Failed to load velocity templates e={}", e);
}
i read it is caused by not able to create velocity.log file , then i tried it like this
velocityEngine = new VelocityEngine();
velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "class,file");
velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.Log4JLogChute");
velocityEngine.setProperty("runtime.log.logsystem.log4j.logger", "VELLOGGER");
velocityEngine.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
velocityEngine.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem");
/*
velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, LOCATION);
velocityEngine.setProperty(RESOURCE_LOADER,ClasspathResourceLoader.class.getName());
*/
try{
LOG.debug("Velocity Initialisation In AbstractFactory");
velocityEngine.init();
LOG.debug("Velocity Initialisation Done!!!");
}catch(Exception e){
LOG.error("Error Occured In Initialising Velocity Engine {}",e);
}
still it is failing while getting
template = velocityEngine.getTemplate(COMMAND_TEMPLATE_LOCATION.concat(command).concat(TEMPLATE_EXTENSION));
with exception stack trace:
org.apache.velocity.exception.VelocityException: Error initializing log: Failed to initialize an instance of org.apache.velocity.runtime.log.NullLogSystem with the current runtime configuration.
at org.apache.velocity.runtime.RuntimeInstance.initializeLog(RuntimeInstance.java:875)
at org.apache.velocity.runtime.RuntimeInstance.init(RuntimeInstance.java:262)
at org.apache.velocity.app.VelocityEngine.init(VelocityEngine.java:93)
at com.yodlee.dap.cortex.generation.engine.AbstractTemplateFactory.<init>(AbstractTemplateFactory.java:68)
at com.yodlee.dap.cortex.generation.engine.GenericTemplateFactory.<init>(GenericTemplateFactory.java:26)
at com.yodlee.dap.cortex.generation.generator.CodeGenerator.generateCode(CodeGenerator.java:52)
at com.yodlee.dap.cortex.codegenerator.processor.CodeGenProcessor.process(CodeGenProcessor.java:75)
at com.yodlee.dap.cortex.codegenerator.handler.CortexHandler.handle(CortexHandler.java:80)
at com.yodlee.dap.cortex.codegenerator.handler.CortexHandler.handle(CortexHandler.java:48)
at com.yodlee.dap.cortex.codegenerator.generate.CodeGenHandler.generate(CodeGenHandler.java:23)
at com.yodlee.eclipse.json.template.generator.code.TemplateGenerator.writeJavaFile(TemplateGenerator.java:228)
at com.yodlee.eclipse.json.template.generator.code.TemplateGenerator.findNewStates(TemplateGenerator.java:291)
at com.yodlee.eclipse.json.template.generator.code.TemplateGenerator.codeParser(TemplateGenerator.java:137)
at com.yodlee.eclipse.json.site.flow.CodeGenerator.generate(CodeGenerator.java:24)
at com.yodlee.eclipse.json.editor.JsonEditor.addBrowserContent(JsonEditor.java:310)
at com.yodlee.eclipse.json.editor.JsonEditor.setJsonInput(JsonEditor.java:450)
at com.yodlee.eclipse.json.editor.JsonReconcileStrategy$1.run(JsonReconcileStrategy.java:66)
at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:182)
at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4211)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3827)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022)
at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150)
at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610)
at org.eclipse.equinox.launcher.Main.run(Main.java:1519)
at org.eclipse.equinox.launcher.Main.main(Main.java:1492)
Caused by: org.apache.velocity.exception.VelocityException: Failed to initialize an instance of org.apache.velocity.runtime.log.NullLogSystem with the current runtime configuration.
at org.apache.velocity.runtime.log.LogManager.createLogChute(LogManager.java:220)
at org.apache.velocity.runtime.log.LogManager.updateLog(LogManager.java:269)
at org.apache.velocity.runtime.RuntimeInstance.initializeLog(RuntimeInstance.java:871)
... 42 common frames omitted
Caused by: org.apache.velocity.exception.VelocityException: The specified logger class org.apache.velocity.runtime.log.NullLogSystem does not implement the org.apache.velocity.runtime.log.LogChute interface.
at org.apache.velocity.runtime.log.LogManager.createLogChute(LogManager.java:181)
... 44 common frames omitted
12:32:52.177 [main] DEBUG com.yodlee.dap.cortex.generation.engine.GenericTemplateFactory - Start getGenericTemplate For= GenericClass
12:32:52.180 [main] ERROR com.yodlee.dap.cortex.generation.engine.GenericTemplateFactory - Error Occured In Velocity initialisation Module {}
org.apache.velocity.exception.VelocityException: Error initializing log: Failed to initialize an instance of org.apache.velocity.runtime.log.CommonsLogLogChute with the current runtime configuration.
at org.apache.velocity.runtime.RuntimeInstance.initializeLog(RuntimeInstance.java:875)
at org.apache.velocity.runtime.RuntimeInstance.init(RuntimeInstance.java:262)
at org.apache.velocity.app.VelocityEngine.init(VelocityEngine.java:93)
at com.yodlee.dap.cortex.generation.engine.GenericTemplateFactory.getGenericTemplate(GenericTemplateFactory.java:43)
at com.yodlee.dap.cortex.generation.generator.CodeGenerator.generateCode(CodeGenerator.java:52)
at com.yodlee.dap.cortex.codegenerator.processor.CodeGenProcessor.process(CodeGenProcessor.java:75)
at com.yodlee.dap.cortex.codegenerator.handler.CortexHandler.handle(CortexHandler.java:80)
at com.yodlee.dap.cortex.codegenerator.handler.CortexHandler.handle(CortexHandler.java:48)
at com.yodlee.dap.cortex.codegenerator.generate.CodeGenHandler.generate(CodeGenHandler.java:23)
at com.yodlee.eclipse.json.template.generator.code.TemplateGenerator.writeJavaFile(TemplateGenerator.java:228)
at com.yodlee.eclipse.json.template.generator.code.TemplateGenerator.findNewStates(TemplateGenerator.java:291)
at com.yodlee.eclipse.json.template.generator.code.TemplateGenerator.codeParser(TemplateGenerator.java:137)
at com.yodlee.eclipse.json.site.flow.CodeGenerator.generate(CodeGenerator.java:24)
at com.yodlee.eclipse.json.editor.JsonEditor.addBrowserContent(JsonEditor.java:310)
at com.yodlee.eclipse.json.editor.JsonEditor.setJsonInput(JsonEditor.java:450)
at com.yodlee.eclipse.json.editor.JsonReconcileStrategy$1.run(JsonReconcileStrategy.java:66)
at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:182)
at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4211)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3827)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022)
at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150)
at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610)
at org.eclipse.equinox.launcher.Main.run(Main.java:1519)
at org.eclipse.equinox.launcher.Main.main(Main.java:1492)
Caused by: org.apache.velocity.exception.VelocityException: Failed to initialize an instance of org.apache.velocity.runtime.log.CommonsLogLogChute with the current runtime configuration.
at org.apache.velocity.runtime.log.LogManager.createLogChute(LogManager.java:220)
at org.apache.velocity.runtime.log.LogManager.updateLog(LogManager.java:269)
at org.apache.velocity.runtime.RuntimeInstance.initializeLog(RuntimeInstance.java:871)
... 41 common frames omitted
Caused by: org.apache.velocity.exception.VelocityException: The specified logger class org.apache.velocity.runtime.log.CommonsLogLogChute does not implement the org.apache.velocity.runtime.log.LogChute interface.
at org.apache.velocity.runtime.log.LogManager.createLogChute(LogManager.java:181)
... 43 common frames omitted
Later i have found the actual root cause of the problem. It was whenever a plugin was initialising the velocity the other plugin was not able to re-initialise it, As the run time environment was same. Additionally both were present as separate module and hence it was not able to access it because of scope issue and hence velocity initialisation was failing.
The solution we implemented as we clubbed both the plugins under single module and hence initialised class from one module was accessible by other.
In my case veolocity and my application was initialized by 2 different class loaders. So when it tries to find the logger class in runtime it cannot find the class. As a solution I had to switched class loaders as a work around(anyway this is not a good way to solve this ).
VelocityEngine ve = new VelocityEngine();
Thread currentThread = Thread.currentThread();
ClassLoader temp = Thread.currentThread().getContextClassLoader();
try
{
currentThread.setContextClassLoader( getClass().getClassLoader() );
ve.setProperty( "runtime.log.logsystem.class", NullLogChute.class.getName() );
ve.init();
}
finally
{
currentThread.setContextClassLoader( temp );
}

Why am I getting an ArrayIndexOutOfBoundsException running this particular Cucumber step in Kotlin?

I'm running with a Cucumber JVM feature file, using Java8 and PicoContainer. I've stripped these steps right down so they're empty, and I'm still getting an error. Here's my feature:
Feature: Full Journey
Scenario: Can load a typical JIRA csv and calculate the distribution from it
Given a typical JIRA export "/closed_only_JIRA.csv"
When I import it into Montecarluni
Then I should see the distribution
"""
6, 15, 3, 14, 2, 5, 6, 8, 5, 10, 15, 4, 2, 1
"""
When I copy it to the clipboard
Then I should be able to paste it somewhere else
(Yes, this is a full journey rather than a BDD scenario.)
For whatever reason, running this step in Kotlin causes an error:
import cucumber.api.java8.En
class ClipboardSteps(val world : World) : En {
init {
When("^I copy it to the clipboard$", {
// Errors even without any code here
})
}
}
While this Java class runs just fine:
import cucumber.api.java8.En;
public class JavaClipboardSteps implements En {
public JavaClipboardSteps(World world) {
When("^I copy it to the clipboard$", () -> {
// Works just fine with code or without
});
}
}
I'm utterly bemused, not least because a "Then" in that Kotlin steps class is running perfectly, and this other step runs without error:
import cucumber.api.java8.En
class FileImportSteps(val world: World) : En {
init {
// There's a Given here
When("^I import it into Montecarluni$", {
// There's some code here
})
}
}
The Runner, for completion:
import cucumber.api.CucumberOptions
import cucumber.api.junit.Cucumber
import org.junit.runner.RunWith
#RunWith(Cucumber::class)
#CucumberOptions(
format = arrayOf("pretty"),
glue = arrayOf("com.lunivore.montecarluni.glue"),
features = arrayOf("."))
class Runner {
}
Stacktrace is:
cucumber.runtime.CucumberException: java.lang.ArrayIndexOutOfBoundsException: 52
at cucumber.runtime.java.JavaBackend.addStepDefinition(JavaBackend.java:166)
at cucumber.api.java8.En.Then(En.java:280)
at com.lunivore.montecarluni.glue.DistributionSteps.<init>(DistributionSteps.kt:8)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.picocontainer.injectors.AbstractInjector.newInstance(AbstractInjector.java:145)
at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:342)
at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:678)
at cucumber.runtime.java.picocontainer.PicoFactory.getInstance(PicoFactory.java:40)
at cucumber.runtime.java.JavaBackend.buildWorld(JavaBackend.java:131)
at cucumber.runtime.Runtime.buildBackendWorlds(Runtime.java:141)
at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:38)
at cucumber.runtime.junit.ExecutionUnitRunner.run(ExecutionUnitRunner.java:102)
at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:63)
at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:18)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at cucumber.runtime.junit.FeatureRunner.run(FeatureRunner.java:70)
at cucumber.api.junit.Cucumber.runChild(Cucumber.java:95)
at cucumber.api.junit.Cucumber.runChild(Cucumber.java:38)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at cucumber.api.junit.Cucumber.run(Cucumber.java:100)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.ArrayIndexOutOfBoundsException: 52
at jdk.internal.org.objectweb.asm.Type.getArgumentTypes(Type.java:358)
at cucumber.runtime.java8.ConstantPoolTypeIntrospector.getGenericTypes(ConstantPoolTypeIntrospector.java:32)
at cucumber.runtime.java.Java8StepDefinition.getParameterInfos(Java8StepDefinition.java:54)
at cucumber.runtime.java.Java8StepDefinition.<init>(Java8StepDefinition.java:44)
at cucumber.runtime.java.JavaBackend.addStepDefinition(JavaBackend.java:162)
... 44 more
What's going on?
All source code currently checked in with Kotlin step commented out, here. (Please excuse the mess as I'm new to a lot of the stuff I'm using; refactoring from the initial spike is ongoing.)
This seems to be an unfortunate interaction between an optimisation Kotlin makes compiling anonymous code blocks, an assumption Cucumber makes about how the JVM stores references to lambdas, and Cucumber's use of some JVM internals that it shouldn't be going near!
Your other Kotlin steps don't trigger the bug for various (different) reasons.
Briefly, if Kotlin can implement a block or lambda as a static singleton then it does, presumably for performance reasons. This interferes with some unconventional reflection magic Cucumber performs (details below).
The fix would be to add an additional check in the Cucumber code, although arguably a better fix would be to rewrite the Cucumber code to use generics reflection properly.
A workaround is to ensure Kotlin doesn't optimise the lambda by including a reference to the containing instance. Even something as simple as a reference to this:
When("^I import it into Montecarluni$") {
this
// your code
}
is enough to convince Kotlin not to perform the optimisation.
The details
When Cucumber adds a step definition with a lambda in e.g. cucumber.api.java8.En it introspects the lambda for information about generics.
The way it does this is to use an access hack to reach a sun.reflect.ConstantPool field in the lambda's class definition. This is a native type and is an implementation detail of the class, storing references to constants the class uses. Cucumber then iterates backwards through these looking for a constant that represents the lambda's constructor. It then uses another internal hack, a static method called getArgumentTypes on jdk.internal.org.objectweb.asm.Type, to figure out the lambda's signature.
Running javap -v against the generated classes, it appears that when Kotlin makes a lambda block into a static singleton it adds a constant field called INSTANCE which then appears in the class's constant pool. This field is an instance of an anonymous inner class with a name like ClipboardSteps$1 rather than a lambda as such, so its internal typestring breaks the mini-parser inside getArgumentTypes, which is the error you are seeing.
So the quick fix in Cucumber is to check that the constant pool member's name is "<init>", which represents the lambda's constructor, and to ignore anything else, like our INSTANCE member.
The proper fix would be to rewrite Cucumber's type introspection to not use the constant pool at all!

Cannot create a secure XMLInputFactory when calling Apache CXF Client from Plain Java

I am trying to call a Apache CXF Service from a Plain Java code as follows
public static void main(String args[])
{
Call Apache CXF Service ....
}
I dont get any compile time error, but getting Runtime exception as follows
Exception in thread "main" java.lang.RuntimeException: Cannot create a secure XMLInputFactory
at org.apache.cxf.staxutils.StaxUtils.createXMLInputFactory(StaxUtils.java:314)
at org.apache.cxf.staxutils.StaxUtils.getXMLInputFactory(StaxUtils.java:264)
at org.apache.cxf.staxutils.StaxUtils.createXMLStreamReader(StaxUtils.java:1457)
at org.apache.cxf.staxutils.StaxUtils.read(StaxUtils.java:1110)
at org.apache.cxf.bus.extension.XmlExtensionFragmentParser.getExtensions(XmlExtensionFragmentParser.java:46)
at org.apache.cxf.bus.extension.ExtensionManagerImpl.load(ExtensionManagerImpl.java:183)
at org.apache.cxf.bus.extension.ExtensionManagerImpl.load(ExtensionManagerImpl.java:159)
at org.apache.cxf.bus.extension.ExtensionManagerImpl.load(ExtensionManagerImpl.java:108)
at org.apache.cxf.bus.extension.ExtensionManagerBus.<init>(ExtensionManagerBus.java:121)
at org.apache.cxf.bus.extension.ExtensionManagerBus.<init>(ExtensionManagerBus.java:134)
at org.apache.cxf.bus.CXFBusFactory.createBus(CXFBusFactory.java:40)
at org.apache.cxf.bus.CXFBusFactory.createBus(CXFBusFactory.java:36)
at org.apache.cxf.bus.CXFBusFactory.createBus(CXFBusFactory.java:32)
at org.apache.cxf.BusFactory.getDefaultBus(BusFactory.java:106)
at org.apache.cxf.BusFactory.createThreadBus(BusFactory.java:243)
at org.apache.cxf.BusFactory.getThreadDefaultBus(BusFactory.java:227)
at org.apache.cxf.BusFactory.getThreadDefaultBus(BusFactory.java:214)
at org.apache.cxf.jaxws.spi.ProviderImpl.createServiceDelegate(ProviderImpl.java:89)
at javax.xml.ws.Service.<init>(Unknown Source)
The dependencies I have are as follows
cxf-rt-frontend-jaxws-2.7.12.jar
cxf-api-2.7.12.jar
woodstox-core-asl-4.4.0.jar
stax2-api-3.1.4.jar
xmlschema-core-2.1.0.jar
cxf-rt-core-2.7.12.jar
jaxb-impl-2.1.13.jar
cxf-rt-bindings-soap-2.7.12.jar
cxf-rt-databinding-jaxb-2.7.12.jar
cxf-rt-bindings-xml-2.7.12.jar
cxf-rt-frontend-simple-2.7.12.jar
cxf-rt-ws-addr-2.7.12.jar
cxf-rt-ws-policy-2.7.12.jar
cxf-rt-transports-http-2.7.12.jar
Please help me solve this error
Note:- I don't have pom.xml. I use traditional "lib" folder to place my dependent jars
I added these three lines and worked fine
Properties props = System.getProperties();
props.setProperty("org.apache.cxf.stax.allowInsecureParser", "1");
props.setProperty("UseSunHttpHandler", "true");