Why am I getting an ArrayIndexOutOfBoundsException running this particular Cucumber step in Kotlin? - 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!

Related

Not able to use MockK in Android Espresso UI Testing

I am getting a error when trying to use MockK in UI test which was perfectly working in Unittest cases
MockK could not self-attach a jvmti agent to the current VM
Full error report
Caused by: io.mockk.proxy.MockKAgentException: MockK could not self-attach a jvmti agent to the current VM. This feature is required for inline mocking.
This error occured due to an I/O error during the creation of this agent: java.io.IOException: Unable to dlopen libmockkjvmtiagent.so: dlopen failed: library "libmockkjvmtiagent.so" not found
Potentially, the current VM does not support the jvmti API correctly
at io.mockk.proxy.android.AndroidMockKAgentFactory.init(AndroidMockKAgentFactory.kt:67)
at io.mockk.impl.JvmMockKGateway.<init>(JvmMockKGateway.kt:46)
at io.mockk.impl.JvmMockKGateway.<clinit>(JvmMockKGateway.kt:186)
... 30 more
Caused by: java.io.IOException: Unable to dlopen libmockkjvmtiagent.so: dlopen failed: library "libmockkjvmtiagent.so" not found
at dalvik.system.VMDebug.nativeAttachAgent(Native Method)
at dalvik.system.VMDebug.attachAgent(VMDebug.java:693)
at android.os.Debug.attachJvmtiAgent(Debug.java:2617)
at io.mockk.proxy.android.JvmtiAgent.<init>(JvmtiAgent.kt:48)
at io.mockk.proxy.android.AndroidMockKAgentFactory.init(AndroidMockKAgentFactory.kt:40)
Let me know is there any other way to initialize the MockK to make use in Espresso
When tried to add
androidTestImplementation "org.mockito:mockito-inline:$mockitoVersion"
Observed this error
2 files found with path 'mockito-extensions/org.mockito.plugins.MockMaker'.
Adding a packagingOptions block may help, please refer to
https://developer.android.com/reference/tools/gradle-api/7.2/com/android/build/api/dsl/ResourcesPackagingOptions
for more information
Versions
mockk version = 1.12.4
Android = 32
kotlin_version = '1.6.21'
Code which causes this issue when added in android UI testcases(Espresso)
val presenter = mockk<LoginPresenter>()
val view = mockk<LoginView>()
How to perform a mock api call like this
val presenter = mockk<LoginPresenter>()
val view = mockk<LoginView>()
onView(withId(R.id.button_login)).perform(loginClick())
But i want mock api to be called
instead of loginClick() in perform() can i call some how the below execution
so that my app uses mock api's
or is there any way to make my entire testcase file use mockk data
every { presenter.onLoginButtonClicked("bc#mail.com","Abc123") } returns view.onCognitoLoginSuccess()
For me adding this solved the problem:
android {
testOptions {
packagingOptions {
jniLibs {
useLegacyPackaging = true
}
}
}
}
I found this here. Hope it helps.
Accorfing to here :
Instrumented Android tests are all failing due to issue with mockk
1.12.4
I used io.mockk:mockk-android:1.12.4 and i have same issue..
SOLUTION:
I change the version of io.mockk:mockk-android to 1.12
3 and test runed fine for me
androidTestImplementation "io.mockk:mockk-android:1.12.3"

Mock Bigquery function in kotlin unit test

I am develop an unit test, which involved (com.google.api.services.bigquery.Bigquery). I mock the object with mockk #SpyK. But the every{} block report error when unit test start. Detail as follow
the dependency is:
"com.google.apis:google-api-services-bigquery:v2-rev20220326-1.32.1"
The exception is throw in setUp() function
Code
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
#ExtendWith(MockKExtension::class, SpringExtension::class)
#EnableConfigurationProperties(ConfidentialTags::class)
#PropertySource(value = ["classpath:application.yml"], factory = YamlPropertySourceFactory::class)
class ResourceAccessServiceTest {
private val mockGoogleCredential = MockGoogleCredential.Builder().build()
#SpyK
private var olderBigQuery: Bigquery = Bigquery.Builder(
MockGoogleCredential.newMockHttpTransportWithSampleTokenResponse(),
mockGoogleCredential.jsonFactory,
mockGoogleCredential
).build()
#InjectMockKs
private lateinit var resourceAccessService: ResourceAccessService
#BeforeAll
fun setUp() {
//error reported here
every { olderBigQuery.RowAccessPolicies().list(any(), any(), any()).execute() } returns mockk() {
every { rowAccessPolicies } returns listOf()
}
}
#Test
fun queryRowAccessExistedPrincipals() {
val list = resourceAccessService.queryRowAccessExistedPrincipals(
TableId.of("proj", "ds", "tbl"),
RowFilter("region", listOf("hk"))
)
assert(list.isEmpty())
}
}
error log
java.net.MalformedURLException: no protocol: projects/2af774bb308513d5/datasets/-3e5359fe6b1a603f/tables/-28b905709f94ecc7/rowAccessPolicies
java.lang.IllegalArgumentException: java.net.MalformedURLException: no protocol: projects/2af774bb308513d5/datasets/-3e5359fe6b1a603f/tables/-28b905709f94ecc7/rowAccessPolicies
at com.google.api.client.http.GenericUrl.parseURL(GenericUrl.java:679)
at com.google.api.client.http.GenericUrl.<init>(GenericUrl.java:125)
at com.google.api.client.http.GenericUrl.<init>(GenericUrl.java:108)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.buildHttpRequestUrl(AbstractGoogleClientRequest.java:373)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.buildHttpRequest(AbstractGoogleClientRequest.java:404)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:514)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:455)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:565)
at com.airwallex.data.grpc.das.service.ResourceAccessServiceTest$setUp$1.invoke(ResourceAccessServiceTest.kt:67)
at com.airwallex.data.grpc.das.service.ResourceAccessServiceTest$setUp$1.invoke(ResourceAccessServiceTest.kt:67)
at io.mockk.impl.eval.RecordedBlockEvaluator$record$block$1.invoke(RecordedBlockEvaluator.kt:25)
at io.mockk.impl.eval.RecordedBlockEvaluator$enhanceWithRethrow$1.invoke(RecordedBlockEvaluator.kt:78)
at io.mockk.impl.recording.JvmAutoHinter.autoHint(JvmAutoHinter.kt:23)
at io.mockk.impl.eval.RecordedBlockEvaluator.record(RecordedBlockEvaluator.kt:40)
at io.mockk.impl.eval.EveryBlockEvaluator.every(EveryBlockEvaluator.kt:30)
at io.mockk.MockKDsl.internalEvery(API.kt:93)
at io.mockk.MockKKt.every(MockK.kt:98)
at com.airwallex.data.grpc.das.service.ResourceAccessServiceTest.setUp(ResourceAccessServiceTest.kt:67)
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.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptLifecycleMethod(TimeoutExtension.java:126)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptBeforeAllMethod(TimeoutExtension.java:68)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeBeforeAllMethods$9(ClassBasedTestDescriptor.java:384)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeBeforeAllMethods(ClassBasedTestDescriptor.java:382)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.before(ClassBasedTestDescriptor.java:196)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.before(ClassBasedTestDescriptor.java:78)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:136)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
The key error info is
java.net.MalformedURLException: no protocol: projects/2af774bb308513d5/datasets/-3e5359fe6b1a603f/tables/-28b905709f94ecc7/rowAccessPolicies
The exception is thrown in the every{} block in setUp function. It seems the url built inside the SDK is invalid, without protocol header. But I don't know how to solve the problems
So what you really want is a way to decouple the code under test from BigQuery. The better way to do so that is to hide BigQuery behind your own abstraction (e.g. an interface) and make the code that needs to query only depend on that abstraction - look up the dependency inversion principle/dependency injection (I've got some answers here that show examples). That way, you can substitute a fake implementation in for testing that, say, queries against a collection in memory.
There is still one problem with this approach. You do at some point need to test against BigQuery for real. Otherwise, how will you prove that component works? I guess the possibilities here are constrained by what your company allows.

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 );
}

Reusable aspects jar

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>

Can you test SetUp success/failure in Google Test?

Is there a way to check that SetUp code has actually worked properly in GTest fixtures, so that the whole fixture or test-application can be marked as failed rather than get weird test results and/or have to explicitly check this in each test?
If you put your fixture setup code into a SetUp method, and it fails and issues a fatal failure (ASSERT_XXX or FAIL macros), Google Test will not run your test body. So all you have to write is
class MyTestCase : public testing::Test {
protected:
bool InitMyTestData() { ... }
virtual void SetUp() {
ASSERT_TRUE(InitMyTestData());
}
};
TEST_F(MyTestCase, Foo) { ... }
Then MyTestCase.Foo will not execute if InitMyTestData() returns false. If you already have nonfatal assertions in your setup code (i.e., EXPECT_XXX or ADD_FAILURE), you can generate a fatal assertion from them by writing ASSERT_FALSE(HasFailure()); You can find more info on failure detection in the Google Test Advanced Guide wiki page.