Logging calls to external code with an aspect leads to exceptions - aop

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.

Related

Unable to Instantiate Class while Alter Region adding cache loaded to that region

I have an apache geode setup where there is one locator and one Server. we have a region employee in that. we were trying to implement in-line cache where a cache miss will lookup into database and will fill apache geode, but after deployment of Jars when i am trying to alter the region . It shows exception
Stack Trace:
[error 2021/04/09 15:18:30.513 IST <Function Execution Processor2> tid=0x3a] Error instantiating class: <com.abc.geode.ApacheGeode.EmployeeCacheLoader>
java.lang.RuntimeException: Error instantiating class: <com.abc.geode.ApacheGeode.EmployeeCacheLoader>
at org.apache.geode.management.internal.configuration.domain.DeclarableTypeInstantiator.newInstance(DeclarableTypeInstantiator.java:43)
at org.apache.geode.management.internal.cli.functions.RegionAlterFunction.alterRegion(RegionAlterFunction.java:202)
at org.apache.geode.management.internal.cli.functions.RegionAlterFunction.executeFunction(RegionAlterFunction.java:67)
at org.apache.geode.management.cli.CliFunction.execute(CliFunction.java:37)
at org.apache.geode.internal.cache.MemberFunctionStreamingMessage.process(MemberFunctionStreamingMessage.java:201)
at org.apache.geode.distributed.internal.DistributionMessage.scheduleAction(DistributionMessage.java:372)
at org.apache.geode.distributed.internal.DistributionMessage$1.run(DistributionMessage.java:436)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.geode.distributed.internal.ClusterOperationExecutors.runUntilShutdown(ClusterOperationExecutors.java:475)
at org.apache.geode.distributed.internal.ClusterOperationExecutors.doFunctionExecutionThread(ClusterOperationExecutors.java:393)
at org.apache.geode.logging.internal.executors.LoggingThreadFactory.lambda$newThread$0(LoggingThreadFactory.java:119)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ClassCastException: com.abc.geode.ApacheGeode.EmployeeCacheLoader cannot be cast to org.apache.geode.cache.Declarable
at org.apache.geode.management.internal.configuration.domain.DeclarableTypeInstantiator.newInstance(DeclarableTypeInstantiator.java:34)
public class EmployeeCacheLoader implements CacheLoader<Long,Employee>, Declarable {
#Override
public Employee load(LoaderHelper<Long, Employee> helper) throws CacheLoaderException {
Employee e=new Employee();
e.setEmail("a#b.com");
e.setIdemployee(2L);
return e;
}
#Override
public void close() {
}
#Override
public void init(Properties props) {
}
Things tried
I tried by not implementing Declarable but still no success.
I have not done any change for serializer.
I've just tried the scenario using Apache Geode 1.13.2 and it works just fine, you can find the example here. Do you have multiple versions of the same jar within the server's class path?, that might be the reason for the exception.
Cheers.

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

How to connect google bigtable outside of google cloud platform

I have a Google Bigtable cluster created.
I'm trying to connect following this tutorial
I was trying to download their cli project and build it, but when I try to execute any command it fails. Also I tried to build my simpler example of connector. Here it is:
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.util.ArrayList;
public class BigTableTestConnector {
private final static Logger logger = Logger.getLogger(BigTableTestConnector.class);
public void testConnection() throws MasterNotRunningException, ZooKeeperConnectionException {
try {
Connection connection = ConnectionFactory.createConnection();
String tableName = "testTable";
ArrayList<String> columnFamilies = new ArrayList<String>();
columnFamilies.add("columnFamily1");
columnFamilies.add("columnFamily2");
columnFamilies.add("justString");
columnFamilies.add("uhhaha");
Admin admin = connection.getAdmin();
HTableDescriptor tableDescriptor = new HTableDescriptor(tableName);
for (String colFamily : columnFamilies) {
tableDescriptor.addFamily(new HColumnDescriptor(colFamily));
}
admin.createTable(tableDescriptor);
} catch (IOException e) {
e.printStackTrace();
}
logger.info("done");
}
public static void main(String... args) throws Exception {
BigTableTestConnector bttc = new BigTableTestConnector();
bttc.testConnection();
}
}
but when I run it on my local machine, I get following exception
java.io.IOException: java.lang.reflect.InvocationTargetException
at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:240)
at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:218)
at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:90)
at com.zoomdata.thrift.provider.BigTableTestConnector.testConnection(BigTableTestConnector.java:33)
at com.zoomdata.thrift.provider.BigTableTestConnector.main(BigTableTestConnector.java:81)
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:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: java.lang.reflect.InvocationTargetException
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:422)
at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:238)
... 9 more
Caused by: java.io.IOException: Error getting access token from metadata server at: http://metadata/computeMetadata/v1/instance/service-accounts/default/token
at com.google.cloud.bigtable.hbase.CredentialFactory.getCredentialFromMetadataServiceAccount(CredentialFactory.java:100)
at com.google.cloud.bigtable.hbase.BigtableOptionsFactory.fromConfiguration(BigtableOptionsFactory.java:236)
at org.apache.hadoop.hbase.client.BigtableConnection.<init>(BigtableConnection.java:120)
... 14 more
Caused by: java.io.IOException: ComputeEngineCredentials cannot find the metadata server. This is likely because code is not running on Google Compute Engine.
at com.google.auth.oauth2.ComputeEngineCredentials.refreshAccessToken(ComputeEngineCredentials.java:63)
at com.google.auth.oauth2.OAuth2Credentials.refresh(OAuth2Credentials.java:76)
at com.google.cloud.bigtable.hbase.CredentialFactory.getCredentialFromMetadataServiceAccount(CredentialFactory.java:98)
... 16 more
Caused by: java.net.UnknownHostException: metadata
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:432)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:527)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:211)
at sun.net.www.http.HttpClient.New(HttpClient.java:308)
at sun.net.www.http.HttpClient.New(HttpClient.java:326)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1168)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1104)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:998)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:932)
at com.google.bigtable.repackaged.com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:93)
at com.google.bigtable.repackaged.com.google.api.client.http.HttpRequest.execute(HttpRequest.java:965)
at com.google.auth.oauth2.ComputeEngineCredentials.refreshAccessToken(ComputeEngineCredentials.java:61)
... 18 more
It said:
ComputeEngineCredentials cannot find the metadata server. This is likely because code is not running on Google Compute Engine.
So does it mean that this code can run only inside Compute Engine?
Is there a way to connect to it from my local computer? Does anyone have any examples of this?
For running locally, you need to make sure that the environment variable GOOGLE_APPLICATION_CREDENTIALS is set to your key.json you got from cloud console. This is the likely cause in your case.

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.

Runtime exception when functional test running

public class MyTest extends FunctionalTest {
#Test
public void gtest() {
Http.Response response = GET("http://google.com"); // <--- RuntimeException
assertIsOk(response);
assertContentType("text/html", response);
assertCharset("utf-8", response);
}
}
This code throw :
java.lang.RuntimeException: java.util.concurrent.ExecutionException: play.exceptions.UnexpectedException: Unexpected Error
at play.test.FunctionalTest.makeRequest(FunctionalTest.java:299)
at play.test.FunctionalTest.makeRequest(FunctionalTest.java:305)
at play.test.FunctionalTest.GET(FunctionalTest.java:103)
at play.test.FunctionalTest.GET(FunctionalTest.java:57)
at MyTest.gtest(MyTest.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Can u tell why this error occurs ? And how to fix it? Playframework 1.2.4 / Java 1.7.0_02.
You probably just need to increase your execution pool size, which is by default 1 in dev mode (which also means test, by default). You're running out of threads and thus the exception occurs.
Try with a setting like this in your application.conf:
%test.play.pool=2