How can we use Dagger2 with kotlin? - kotlin

I want use Dagger2 with kotlin. But then I use this setting for dagger2 with kotlin by the way on the internet, it occurs a problem.
//build.gradle
apply plugin: 'kotlin-kapt'
kapt {
generateStubs = true
}
...
dependencies {
compile 'com.google.dagger:dagger-android:2.11'
compile 'com.google.dagger:dagger-android-support:2.11'
kapt 'com.google.dagger:dagger-android-processor:2.11'
kapt 'com.google.dagger:dagger-compiler:2.11'
}
Here a problem, I am using Lombok too. Is this the problem?
e: java.lang.IllegalStateException: failed to analyze: org.jetbrains.kotlin.kapt3.diagnostic.KaptError: Error while annotation processing
at org.jetbrains.kotlin.analyzer.AnalysisResult.throwIfError(AnalysisResult.kt:57)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules(KotlinToJVMBytecodeCompiler.kt:137)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:158)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:61)
at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:107)
at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:51)
at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:92)
at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$2.invoke(CompileServiceImpl.kt:386)
at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$2.invoke(CompileServiceImpl.kt:96)
at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:892)
at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:96)
at org.jetbrains.kotlin.daemon.common.DummyProfiler.withMeasure(PerfUtils.kt:137)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.checkedCompile(CompileServiceImpl.kt:919)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.doCompile(CompileServiceImpl.kt:891)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:385)
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:498)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:346)
at sun.rmi.transport.Transport$1.run(Transport.java:200)
at sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
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)
Caused by: org.jetbrains.kotlin.kapt3.diagnostic.KaptError: Error while annotation processing
at org.jetbrains.kotlin.kapt3.AnnotationProcessingKt.doAnnotationProcessing(annotationProcessing.kt:90)
at org.jetbrains.kotlin.kapt3.AnnotationProcessingKt.doAnnotationProcessing$default(annotationProcessing.kt:42)
at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.runAnnotationProcessing(Kapt3Extension.kt:205)
at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.analysisCompleted(Kapt3Extension.kt:166)
at org.jetbrains.kotlin.kapt3.ClasspathBasedKapt3Extension.analysisCompleted(Kapt3Extension.kt:82)
at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM$analyzeFilesWithJavaIntegration$2.invoke(TopDownAnalyzerFacadeForJVM.kt:96)
at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(TopDownAnalyzerFacadeForJVM.kt:106)
at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration$default(TopDownAnalyzerFacadeForJVM.kt:83)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:376)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:67)
at org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport.analyzeAndReport(AnalyzerWithCompilerReport.kt:96)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.analyze(KotlinToJVMBytecodeCompiler.kt:367)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules(KotlinToJVMBytecodeCompiler.kt:132)
... 30 more
:app:kaptStagingDebugKotlin FAILED
FAILURE: Build failed with an exception.
MenuActivity
abstract class MenuActivity : BaseFragmentActivity() {
#Inject
internal var presenter: MenuPresenter? = null
override fun baseFragmentWithTag(): Map<String, Class<out BaseManagerFragment>> {
val map = HashMap<String, Class<out BaseManagerFragment>>()
for (tag in MenuScreensTag.values())
map.put(tag.getTag(), tag.getFragmentClazz())
return map
}
#JvmOverloads
fun switchTag(screensTag: MenuScreensTag, clearCurrentStack: Boolean = false) {
val tag = screensTag.getTag()
switchToStackByTag(tag, clearCurrentStack)
}
public override fun inject(appComponent: AppComponent) {
val component = DaggerMenuComponent.builder()
.appComponent(appComponent)
.menuModule(MenuModule(this))
.build()
component.injectFragment(this)
component.injectPresenter(presenter!!)
}
}
Here is the MenuActivity code.
I just use kotlin plugin to convert java to kotlin directly. Then the error occurs.

Like you assumed already, Lombok is the problem. Kapt runs before Lombok and thus some relevant classes or at least parts of it don't exist yet. Therefore compilation fails.
In our case we replaced Lombok with Kotlin data classes in one go. Alternatively you can move all these classes to a separate module which builds before you run Kapt the first time. If you don't have to many classes you could also de-lombok these or implement what you need manually.

Thank you all,
I have solved this.
make
#Inject
internal var presenter: MenuPresenter? = null
to
#Inject
lateinit var presenter: MenuPresenter? = null

Related

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.

NullPointerException while setting Resource Bundle in Codenameone

I am testing translation in codename one, just used the Chrome Example added code to read "en" local I think, and I am receiving this exception, here is the code, thank you
public class Chrome {
private Resources theme;
private Form current;
public void init(Object context) {
theme = UIManager.initFirstTheme("/theme");
}
public void start() {
String local = L10NManager.getInstance().getLanguage();
System.err.println("local: "+local);
UIManager.getInstance().setBundle(theme.getL10N("l10n", local));
Here is Output:
local: en
java.lang.NullPointerException
at com.codename1.ui.util.Resources.getL10N(Resources.java:834)
at com.codename1.demo.chrome.Chrome.start(Chrome.java:39)
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 com.codename1.impl.javase.Executor$3$1.run(Executor.java:258)
at com.codename1.ui.Display.processSerialCalls(Display.java:1331)
at com.codename1.ui.Display.mainEDTLoop(Display.java:1125)
at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
Java Result: 1
This NPE will happen if there's no localization resource named "l10n" in the resource bundle. You need to add a localization bundle and name it exactly (case sensitive no spaces) "l10n".

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

Logging calls to external code with an aspect leads to exceptions

I am trying to find list of all external functions that are being called in a program. Program under test is in package net.sf.gaeappmanager.google.appengine and external functions are in package and subpackage of org.apache.http...
To achieve this, I have written aspects as below:
public pointcut capturehttp() :
within(net.sf.gaeappmanager..*) &&
!within(gaeAspect) &&
(
call(* org.apache.http..*+.*(..)) ||
call(org.apache.http..*+.new(..))
);
after() : capturehttp() {
System.out.println(
"Function of http Package" +
thisJoinPoint.getSignature().getName()
);
}
But this aspect is not working as it should be. It is throwing unhandled exceptions. If I use only System.out.println("Function of http Package") without thisJoinPoint then it works fine.
Added Extra Information as required by #kriegaex
I am executing PUT using test cases generated through Evosuite tool. First I am including here the test case:
#Test
public void test0() throws Throwable {
// Undeclared exception!
try {
Manager.retrieveAppQuotaDetails("#;[", ")C)!L{Fy,b%<$%", "#;[", ")C)!L{Fy,b%<$%");
fail("Expecting exception: NoClassDefFoundError");
} catch(NoClassDefFoundError e) {
//
// org/apache/commons/logging/LogFactory
//
assertThrownBy("org.apache.http.impl.client.AbstractHttpClient", e);
}
}
//Test case number: 1
/*
* 1 covered goal:
* Goal 1. net.sf.gaeappmanager.google.appengine.Manager.<init>()V: root-Branch
*/
#Test
public void test1() throws Throwable {
Manager manager0 = new Manager();
}
}
When I am executing this test case (with the aspects given above), I am getting the following exceptions:
There were 2 failures:
1) test1(net.sf.gaeappmanager.google.appengine.Manager_ESTest)
java.lang.NoClassDefFoundError: Could not initialize class net.sf.gaeappmanager.
google.appengine.Manager
at net.sf.gaeappmanager.google.appengine.Manager_ESTest.test1(Manager_ES
Test.java:48)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(Framework
Method.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCal
lable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMe
thod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMet
hod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.
java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.ja
va:27)
at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement
.call(FailOnTimeout.java:298)
at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement
.call(FailOnTimeout.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.lang.Thread.run(Thread.java:745)
2) test0(net.sf.gaeappmanager.google.appengine.Manager_ESTest)
java.lang.AssertionError: Exception was not thrown in org.apache.http.impl.clien
t.AbstractHttpClient
at org.evosuite.runtime.EvoAssertions.assertThrownBy(EvoAssertions.java:
70)
at net.sf.gaeappmanager.google.appengine.Manager_ESTest.test0(Manager_ES
Test.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(Framework
Method.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCal
lable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMe
thod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMet
hod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.
java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.ja
va:27)
at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement
.call(FailOnTimeout.java:298)
at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement
.call(FailOnTimeout.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.lang.Thread.run(Thread.java:745)
FAILURES!!!
Tests run: 2, Failures: 2
If I execute the same test case but without thisJoinPoint in the aspects, I get the following result:
.
.Function of http Package
Time: 0.669
OK (2 tests)
My main concern is why adding thisJoinPoint in the aspects is resulting the exceptions and how I can get the list of all external functions in a program.

NoClassDefFoundError in org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:53

NoClassDefFoundError in org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:53
I'm developing an AOP logger. It works fine with a straight up Java class with a main() method but is failing when used in conjunction with Spring Boot. The logging jar file is in both the bootclasspath and the class path. An exception is thrown even before I'm able to print out the class path. Am I missing a configuration step to make Spring Boot happy?
The exception:
java.lang.reflect.InvocationTargetException
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.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:53)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoClassDefFoundError: Could not initialize class com.co.brs.logging.aop.AopLogger
at com.co.brs.restserver.RestApplication.main(RestApplication.java:73)
... 6 more
The command line:
/usr/java/latest/bin/java -Xbootclasspath/p:/usr/local/co/lib/logging-logger.jar -server -cp /usr/local/co/lib/logging-logger.jar:/usr/local/co/bin/../lib/restserver:/usr/local/co/lib/*:/usr/local/co/catalog/lib/*:/usr/local/co/lib/logging-logmanager/* -jar /usr/local/co/bin/../lib/restserver/rest-server.jar >> /usr/local/co/bin/../log/restserver.out 2>&1 &
The RestApplication.java:
#Configuration
#EnableAutoConfiguration
#ComponentScan({"com.co.brs.restserver.component", "com.co.brs.restserver.service", "com.co.brs.restserver.web", "com.co.brs.restserver.doc"})
public class RestApplication {
#Value("${keystore.file}") private String keystoreFile;
#Value("${keystore.pass}") private String keystorePass;
#Value("${keystore.type}") private String keystoreType;
#Value("${secure.port}") private String securePort;
/**
* Start Spring boot Application
* #throws Exception
*/
public static void main(String[] args) throws Exception {
ClassLoader loader = RestApplication.class.getClassLoader();
System.out.println(System.getProperty("java.class.path"));
//Get the System Classloader
ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader();
//Get the URLs
URL[] urls = ((URLClassLoader)sysClassLoader).getURLs();
for(int i=0; i< urls.length; i++)
{
System.out.println(urls[i].getFile());
}
SpringApplication restApp = new SpringApplication(RestApplication.class);
restApp.setShowBanner(false);
restApp.setDefaultProperties(new HashMap<String, Object>());
ApplicationContext context = restApp.run(args);
RestService restService = context.getBean(RestService.class);
restApp.setRegisterShutdownHook(true);
// Start component
if (!restService.start()) {
// Failed to start
System.out.println("Failed to start - exiting\n");
System.exit(SpringApplication.exit(context, new JobExecutionExitCodeGenerator()));
}
System.out.println("Rest Service is up and running");
}
And the AOP Logger snippet:
pointcut logMethod():
(execution(public * *(..)) && !execution(public * get*(..)) && !execution(public void set*(..))
&& !cflow(adviceexecution() && !execution(public com.co.brs.logging* *(..))));
before(): logMethod() {...}
The pom.xml file includes the following dependencies:
<dependency>
<groupId>com.co.brs.logging</groupId>
<artifactId>logging-logger</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.2</version>
</dependency>
and
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
I updated the point cut in the AOPLogger to ignore main() methods and got farther.
The point cut:
pointcut logMethod():
(execution(public * *(..)) && !execution(public * get*(..)) && !execution(public void set*(..)) && !execution(public void main(..))
&& !cflow(adviceexecution() && !execution(public com.co.brs.logging* *(..))));
New output: (The code is getting into the execution:
java.lang.reflect.InvocationTargetException
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.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:53)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoClassDefFoundError: org/aspectj/runtime/reflect/Factory
at com.co.brs.logging.CatalogHandler.ajc$preClinit(CatalogHandler.java:1)
at com.co.brs.logging.CatalogHandler.<clinit>(CatalogHandler.java:1)
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:408)
at java.lang.Class.newInstance(Class.java:433)
at java.util.logging.LogManager$5.run(LogManager.java:966)
at java.security.AccessController.doPrivileged(Native Method)
at java.util.logging.LogManager.loadLoggerHandlers(LogManager.java:958)
at java.util.logging.LogManager.initializeGlobalHandlers(LogManager.java:1578)
at java.util.logging.LogManager.access$1500(LogManager.java:145)
at java.util.logging.LogManager$RootLogger.accessCheckedHandlers(LogManager.java:1667)
at java.util.logging.Logger.getHandlers(Logger.java:1776)
at org.slf4j.bridge.SLF4JBridgeHandler.removeHandlersForRootLogger(SLF4JBridgeHandler.java:169)
at org.springframework.boot.logging.log4j.Log4JLoggingSystem.beforeInitialize(Log4JLoggingSystem.java:64)
at org.springframework.boot.logging.LoggingApplicationListener.onApplicationEvent(LoggingApplicationListener.java:135)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:98)
at org.springframework.boot.context.event.EventPublishingRunListener.publishEvent(EventPublishingRunListener.java:100)
at org.springframework.boot.context.event.EventPublishingRunListener.started(EventPublishingRunListener.java:54)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:276)
at com.emc.brs.restserver.RestApplication.main(RestApplication.java:62)
... 6 more
I further updated the pointcut to only include the package for my product and now the code gets past the initial boot without a problem. The final pointcut defines an intercept for my package, not simple getters and setters, not the logging package itself, not main() methods and not while already giving advice.
pointcut logMethod():
(execution(public com.co.brs* *(..))
&& !execution(public * get*(..))
&& !execution(public void set*(..))
&& !execution(public void main(..))
&& !cflow(adviceexecution()
&& !execution(public com.co.brs.logging* *(..))));
before(): logMethod()
{ ... }
To me it looks like you want to capture public method calls within a certain package instead of method calls returning types from that package, i.e. execution(public * com.co.brs..*(..)) rather than execution(public com.co.brs..* *(..)). The same is true for the logging execution at the end, you also got that one wrong.
You can also further refine your pointcut, e.g. by
using a construct like com.co.brs..* instead of com.co.brs* to explicitly denote that you mean package com.co.brs and all its subpackages,
omitting the public modifiers on subsequent pointcuts chained together via && because the first pointcut already limits executions to public ones.
You also do not need the outermost parentheses enclosing everything.
pointcut logMethod():
execution(public * com.co.brs..*(..)) &&
!execution(* get*(..)) &&
!execution(void set*(..)) &&
!execution(void main(..)) &&
!cflow(adviceexecution()) &&
!execution(* com.co.brs.logging..*(..));
Please also note that !cflow(adviceexecution()) also excludes execution of other advice from other aspects. If this is what you want it is fine. If not, you should rather use something like !within(MyAdvice) instead.