Using Janino in YARN with Apache Twill causes "Imported class x.y could not be loaded" - hadoop-yarn

I'm porting an open source project, which uses Janino for dynamic compilation of classes, to YARN, using Apache Twill. This works great except one last error. When Janino is used with twill, I'm getting an exception that a class cannot be found, although the class in in the Classpath and even used.
The exception I'm getting is:
2014-06-09T18:30:40,093Z ERROR o.a.d.e.p.i.p.ProjectRecordBatch [zk1]
[37daf04b-7d82-4d2f-987c-59851f2aeafe:frag:0:0]
AbstractSingleRecordBatch:next(AbstractSingleRecordBatch.java:60) -
Failure during query
org.apache.drill.exec.exception.SchemaChangeException: Failure while
attempting to load generated class
at org.apache.drill.exec.physical.impl.project.ProjectRecordBatch.setupNewSchema(ProjectRecordBatch.java:243)
at org.apache.drill.exec.record.AbstractSingleRecordBatch.next(AbstractSingleRecordBatch.java:57)
at org.apache.drill.exec.physical.impl.project.ProjectRecordBatch.next(ProjectRecordBatch.java:83)
at org.apache.drill.exec.record.AbstractSingleRecordBatch.next(AbstractSingleRecordBatch.java:45)
at org.apache.drill.exec.physical.impl.limit.LimitRecordBatch.next(LimitRecordBatch.java:99)
at org.apache.drill.exec.record.AbstractSingleRecordBatch.next(AbstractSingleRecordBatch.java:45)
at org.apache.drill.exec.physical.impl.svremover.RemovingRecordBatch.next(RemovingRecordBatch.java:94)
at org.apache.drill.exec.physical.impl.ScreenCreator$ScreenRoot.next(ScreenCreator.java:80)
at org.apache.drill.exec.work.fragment.FragmentExecutor.run(FragmentExecutor.java:104)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744) Caused by: org.apache.drill.exec.exception.ClassTransformationException: Failure
Generating transformation classes for value:
package org.apache.drill.exec.test.generated;
import org.apache.drill.exec.exception.SchemaChangeException;
import org.apache.drill.exec.expr.holders.BitHolder;
import org.apache.drill.exec.expr.holders.VarCharHolder;
import org.apache.drill.exec.ops.FragmentContext;
import org.apache.drill.exec.record.RecordBatch;
import org.apache.drill.exec.vector.RepeatedVarCharVector;
import org.apache.drill.exec.vector.VarCharVector;
import org.apache.drill.exec.vector.complex.impl.RepeatedVarCharReaderImpl;
public class ProjectorGen0 {
RepeatedVarCharVector vv0;
RepeatedVarCharReaderImpl reader4;
VarCharVector vv5;
public boolean doEval(int inIndex, int outIndex)
throws SchemaChangeException
{
{
VarCharHolder out3 = new VarCharHolder();
complex:
vv0 .getAccessor().getReader().setPosition((inIndex));
reader4 .read(0, out3);
BitHolder out8 = new BitHolder();
out8 .value = 1;
if (!vv5 .getMutator().setSafe((outIndex), out3)) {
out8 .value = 0;
}
if (out8 .value == 0) {
return false;
}
}
{
return true;
}
}
public void doSetup(FragmentContext context, RecordBatch incoming, RecordBatch outgoing)
throws SchemaChangeException
{
{
int[] fieldIds1 = new int[ 1 ] ;
fieldIds1 [ 0 ] = 0;
Object tmp2 = (incoming).getValueAccessorById(RepeatedVarCharVector.class, fieldIds1).getValueVector();
if (tmp2 == null) {
throw new SchemaChangeException("Failure while loading vector vv0 with id: org.apache.drill.exec.record.TypedFieldId#1cf4a5a0.");
}
vv0 = ((RepeatedVarCharVector) tmp2);
reader4 = ((RepeatedVarCharReaderImpl) vv0 .getAccessor().getReader());
int[] fieldIds6 = new int[ 1 ] ;
fieldIds6 [ 0 ] = 0;
Object tmp7 = (outgoing).getValueAccessorById(VarCharVector.class, fieldIds6).getValueVector();
if (tmp7 == null) {
throw new SchemaChangeException("Failure while loading vector vv5 with id: org.apache.drill.exec.record.TypedFieldId#1ce776c0.");
}
vv5 = ((VarCharVector) tmp7);
}
}
}
at
org.apache.drill.exec.compile.ClassTransformer.getImplementationClass(ClassTransformer.java:302)
at
org.apache.drill.exec.ops.FragmentContext.getImplementationClass(FragmentContext.java:185)
at
org.apache.drill.exec.physical.impl.project.ProjectRecordBatch.setupNewSchema(ProjectRecordBatch.java:240)
at
org.apache.drill.exec.record.AbstractSingleRecordBatch.next(AbstractSingleRecordBatch.java:57)
at
org.apache.drill.exec.physical.impl.project.ProjectRecordBatch.next(ProjectRecordBatch.java:83)
at
org.apache.drill.exec.record.AbstractSingleRecordBatch.next(AbstractSingleRecordBatch.java:45)
at
org.apache.drill.exec.physical.impl.limit.LimitRecordBatch.next(LimitRecordBatch.java:99)
at
org.apache.drill.exec.record.AbstractSingleRecordBatch.next(AbstractSingleRecordBatch.java:45)
at
org.apache.drill.exec.physical.impl.svremover.RemovingRecordBatch.next(RemovingRecordBatch.java:94)
at
org.apache.drill.exec.physical.impl.ScreenCreator$ScreenRoot.next(ScreenCreator.java:80)
at
org.apache.drill.exec.work.fragment.FragmentExecutor.run(FragmentExecutor.java:104)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744) Caused by:
org.codehaus.commons.compiler.CompileException: Line 4, Column 8:
Imported class "org.apache.drill.exec.exception.SchemaChangeException"
could not be loaded at
org.codehaus.janino.UnitCompiler.compileError(UnitCompiler.java:9014)
at org.codehaus.janino.UnitCompiler.import2(UnitCompiler.java:192) at
org.codehaus.janino.UnitCompiler.access$000(UnitCompiler.java:104) at
org.codehaus.janino.UnitCompiler$1.visitSingleTypeImportDeclaration(UnitCompiler.java:166)
at
org.codehaus.janino.Java$CompilationUnit$SingleTypeImportDeclaration.accept(Java.java:171)
at org.codehaus.janino.UnitCompiler.(UnitCompiler.java:164) at
org.apache.drill.exec.compile.JaninoClassCompiler.getClassByteCode(JaninoClassCompiler.java:53)
at
org.apache.drill.exec.compile.QueryClassLoader.getClassByteCode(QueryClassLoader.java:69)
at
org.apache.drill.exec.compile.ClassTransformer.getImplementationClass(ClassTransformer.java:256)
at
org.apache.drill.exec.ops.FragmentContext.getImplementationClass(FragmentContext.java:185)
at
org.apache.drill.exec.physical.impl.project.ProjectRecordBatch.setupNewSchema(ProjectRecordBatch.java:240)
at
org.apache.drill.exec.record.AbstractSingleRecordBatch.next(AbstractSingleRecordBatch.java:57)
at
org.apache.drill.exec.physical.impl.project.ProjectRecordBatch.next(ProjectRecordBatch.java:83)
at
org.apache.drill.exec.record.AbstractSingleRecordBatch.next(AbstractSingleRecordBatch.java:45)
at
org.apache.drill.exec.physical.impl.limit.LimitRecordBatch.next(LimitRecordBatch.java:99)
at
org.apache.drill.exec.record.AbstractSingleRecordBatch.next(AbstractSingleRecordBatch.java:45)
at
org.apache.drill.exec.physical.impl.svremover.RemovingRecordBatch.next(RemovingRecordBatch.java:94)
at
org.apache.drill.exec.physical.impl.ScreenCreator$ScreenRoot.next(ScreenCreator.java:80)
at
org.apache.drill.exec.work.fragment.FragmentExecutor.run(FragmentExecutor.java:104)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
As you can see, the type of the exception is SchemaChangeException but the internal exception is a ClassNotFoundException for SchemaChangeException:
Line 4, Column 8: Imported class
"org.apache.drill.exec.exception.SchemaChangeException" could not be
loaded
So there is something wrong with the class loader, which changes when the application is run with Apache Twill. It works stand alone, but in both cases the underlying jars are identical.
Apache Twill also has a function to add additional resources, but adding my jar there didn't work either, instead I got an exception, that the jar is already included:
Exception in thread "ServiceDelegate STARTING" java.lang.RuntimeException: java.util.zip.ZipException: duplicate entry: lib/drill-java-exec-1.0.0-m2-incubating-SNAPSHOT-rebuffed.jar
at com.google.common.base.Throwables.propagate(Throwables.java:160) at
org.apache.twill.yarn.YarnTwillController.doStartUp(YarnTwillController.java:133)
at
org.apache.twill.internal.AbstractZKServiceController.startUp(AbstractZKServiceController.java:82)
at
org.apache.twill.internal.AbstractExecutionServiceController$ServiceDelegate.startUp(AbstractExecutionServiceController.java:109)
at
com.google.common.util.concurrent.AbstractIdleService$1$1.run(AbstractIdleService.java:43)
at java.lang.Thread.run(Thread.java:744) Caused by:
java.util.zip.ZipException: duplicate entry:
lib/drill-java-exec-1.0.0-m2-incubating-SNAPSHOT-rebuffed.jar at
java.util.zip.ZipOutputStream.putNextEntry(ZipOutputStream.java:215)
at
java.util.jar.JarOutputStream.putNextEntry(JarOutputStream.java:109)
at
org.apache.twill.internal.ApplicationBundler.copyResource(ApplicationBundler.java:347)
at
org.apache.twill.internal.ApplicationBundler.createBundle(ApplicationBundler.java:140)
at
org.apache.twill.yarn.YarnTwillPreparer.createContainerJar(YarnTwillPreparer.java:388)
at
org.apache.twill.yarn.YarnTwillPreparer.access$300(YarnTwillPreparer.java:106)
at
org.apache.twill.yarn.YarnTwillPreparer$1.call(YarnTwillPreparer.java:264)
at
org.apache.twill.yarn.YarnTwillPreparer$1.call(YarnTwillPreparer.java:253)
at
org.apache.twill.yarn.YarnTwillController.doStartUp(YarnTwillController.java:98)
... 4 more
The underlying classloader used is the URLClassLoader. It's initialized with an empty array, but it works for the stand alone application, the problem is only when it runs with Apache Twill, where does it get the URLs it should look up from? How could I check it?
The classloader definition:
public class QueryClassLoader extends URLClassLoader {
static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(QueryClassLoader.class);
private final ClassCompiler classCompiler;
private AtomicLong index = new AtomicLong(0);
private ConcurrentMap<String, byte[]> customClasses = new MapMaker().concurrencyLevel(4).makeMap();
public QueryClassLoader(boolean useJanino) {
super(new URL[0]);
if (useJanino) {
this.classCompiler = new JaninoClassCompiler(this);
} else {
throw new UnsupportedOperationException("Drill no longer supports using the JDK class compiler.");
}
}
...
Any ideas where I could look into, why the error occurs or how to solve it?

The same question was asked in the Apache Twill mailing list. Here is the discussion and proposed solution to it.
http://mail-archives.apache.org/mod_mbox/twill-dev/201406.mbox/%3CCAHqY-MOa8jBYs%3DEZENxxNZg-9YGMR5SASg76P_k6%2Bm6p2L9JuQ%40mail.gmail.com%3E
Repeat my answer in the mail content:
I am not familiar with how janino works, but it seems to me that it may not be using context ClassLoader to load classes or as least the thread that is compiling the generated class does not have the context
ClassLoader set properly.
The way that Twill works is pretty straightforward. It creates a "launcher.jar", which has no dependency on any library and start the JVM in a YARN container like this:
java -cp launcher.jar ....
Hence the system classloader has no user/library classes, but only the Launcher class.
Then in the Launcher.main() method, it creates a URLClassLoader, using all the jars + .class files inside the "container.jar" file, to load the user TwillRunnable. It also sets it as the context ClassLoader of the thread that calls the "run()" method. So, if you want to load class manually (through ClassLoader or Class.forName) in a different thread than the "run()" thread, you'll have to use set the context ClassLoader of that thread or explicitly construct the ClassLoader with the correct parent ClassLoader.

Related

Why is NoClassDefFoundError being thrown after static initialization failed?

Could anyone please help with understanding of the following. Here is the code:
public class GoLoose {
public static void main(String[] args) {
try{
new Lost();
}catch (Throwable e){
e.printStackTrace();
}
new Lost();
}
}
class Lost{
final static int i = 1 / 0;
}
the result will be like:
java.lang.ExceptionInInitializerError
at test_linkage.GoLoose.main(GoLoose.java:7)
Caused by: java.lang.ArithmeticException: / by zero
at test_linkage.Lost.<clinit>(GoLoose.java:17)
... 1 more
Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class test_linkage.Lost
at test_linkage.GoLoose.main(GoLoose.java:11)
As far as I can understand, it loads Lost's class file, then compiles and then tries to initialize static variable 'i' of the the Lost class - it fails with ArithmeticException wrapped by ExceptionInInitializerError. We catch it and only print and go further. Next, while trying to create a new instance of Lost again, it throws NoClassDefFoundError like it doesn't try to initialize Lost class now. And that is what I don't understand-why it don't try again? Why there is no ArithmeticException again?
It's said in the spec under 5.5. Initialization part: "If the Class object for C is in an erroneous state, then initialization is not possible. Release LC and throw a NoClassDefFoundError."
May it be that this is exactly what happens in my code? Like, after first attempt of initialization, if it goes wrong, class gets some "erroneous state" and having this state the class will never be eligible for further attempts of initialization. But then, what exactly is this state and where is it stored?
Thanks!

Resiliency4j CircuitBreaker tried to call circuitBreaker logic in AOP in order to achieve not to call circuit breaker when it is disabled in config

Conditionally I want to switch the circuit breaker switch off/on by setting spring.cloud.circuitbreaker.resilience4j.enabled=false. My logic should stay intact from circuit-breaker logic.
I tried using the below demo example to extend to my requirements, I am trying to bind circuit breaker call on target method based on circuit breaker flag spring.cloud.circuitbreaker.resilience4j.enabled=true in application.property, true and false case. There could be a simpler way to achieve this, help me if any other solution than what I tried.
Example:
spring cloud circuit-breaker-resiliency4j example
Tried calling happy path - Work fine when there is no exception [response comes within 3 seconds as time limiter set to 3seconds in bean creation]
application.properties:
spring.cloud.circuitbreaker.resilience4j.enabled=true
spring.cloud.config.enabled=false
spring.cloud.config.import-check.enabled=false
spring.main.allow-bean-definition-overriding=true
Controller:
#GetMapping("/delay/{seconds}")
public Map delay(#PathVariable int seconds) {
return mockService.delay(seconds);
}
MockService:
#ApplyCircuitBreaker
public Map delay(int seconds) {
return rest.getForObject("https://httpbin.org/delay/" + seconds, Map.class);
}
Config class:
#Configuration
#ConditionalOnProperty(name = { "spring.cloud.circuitbreaker.resilience4j.enabled"}, matchIfMissing = true)
public class ResiliencyConfig {
#Bean
public Customizer<Resilience4JCircuitBreakerFactory> defaultCustomizer() {
return factory -> factory.configureDefault(id -> new Resilience4JConfigBuilder(id)
.timeLimiterConfig(TimeLimiterConfig.custom().timeoutDuration(Duration.ofSeconds(3)).build())
.circuitBreakerConfig(CircuitBreakerConfig.ofDefaults())
.build());
}
}
ApplyCircuitBreaker - Custom annotation to Apply circuit breaker only for required methods:
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface ApplyCircuitBreaker {
}
AOP: CircuitBreakerAroundAspect:
#Aspect
#Component
#ConditionalOnProperty(name = { "spring.cloud.circuitbreaker.resilience4j.enabled",
"spring.cloud.circuitbreaker.resilience4j.reactive.enabled" }, matchIfMissing = true)
public class CircuitBreakerAroundAspect {
#Autowired
CircuitBreakerFactory circuitBreakerFactory;
#Around("#annotation(com.ravibeli.circuitbreaker.aspects.ApplyCircuitBreaker)")
public Object aroundAdvice(final ProceedingJoinPoint joinPoint) throws Throwable {
log.info("Arguments passed to method are: {}", Arrays.toString(joinPoint.getArgs()));
AtomicReference<Map<String, String>> fallback = new AtomicReference<>();
Object proceed = circuitBreakerFactory.create(joinPoint.getSignature().toString())
.run(() -> {
try {
log.info("Inside CircuitBreaker logic in Aspect");
return joinPoint.proceed();
} catch (Throwable t) {
log.error(t.getMessage());
}
return null;
}, Throwable::getMessage);
log.info("Result from method is: {}", proceed);
return proceed;
}
}
My requirement:
circuitBreakerFactory.create(joinPoint.getSignature().toString()) .run(() -> ....) at this line, when target method throws exception, controll should go to fallback mechanism call. Since joinPoint.proceed() throws exception, it is forcing to handle exception - So I am doing wrong here, need suggestion to fix this to solve the requirement.
Error log:
{
"timestamp": "2021-07-10T01:33:10.558+00:00",
"status": 500,
"error": "Internal Server Error",
"trace": "java.lang.ClassCastException: class java.lang.String cannot be cast to class java.util.Map (java.lang.String and java.util.Map are in module java.base of loader 'bootstrap')\r\n\tat com.ravibeli.circuitbreaker.service.MockService$$EnhancerBySpringCGLIB$$3e293bd0.delay(<generated>)\r\n\tat com.ravibeli.circuitbreaker.controllers.DemoController.delay(DemoController.java:53)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)\r\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1063)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)\r\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)\r\n\tat org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:655)\r\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:764)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:228)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163)\r\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163)\r\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163)\r\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163)\r\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163)\r\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)\r\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)\r\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)\r\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)\r\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\r\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)\r\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)\r\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)\r\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)\r\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)\r\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1723)\r\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\r\n\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)\r\n\tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)\r\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\r\n\tat java.base/java.lang.Thread.run(Thread.java:834)\r\n",
"message": "class java.lang.String cannot be cast to class java.util.Map (java.lang.String and java.util.Map are in module java.base of loader 'bootstrap')",
"path": "/delay/3"
}
You seem to be asking a couple different questions here.
The title seems to be asking why the aspect is still present when
spring.cloud.circuitbreaker.resilience4j.enabled=false
The problem is with your conditional
#ConditionalOnProperty(name = { "spring.cloud.circuitbreaker.resilience4j.enabled",
"spring.cloud.circuitbreaker.resilience4j.reactive.enabled" }, matchIfMissing = true)
It's simply requiring the property be present, it's not checking what it's set to. You need to set havingValue=true as well.
That said, I would strongly suggest not making your own pointcut for circuit breakers. Use the annotations provided by Resiliancy4j and just specify the fallback method there. I would expect that to clear up any other issues you're having with fallbacks.
#Bulkhead(name = 'myService', fallbackMethod = "myFallback")
#CircuitBreaker(name = 'myService', fallbackMethod = "myFallback")
#RateLimiter(name = 'myService', fallbackMethod = "myFallback")
#TimeLimiter(name = 'myService', fallbackMethod = "myFallback")
For enabling the circuit breaker dynamically you can use Profiles or Externalized Configuration (preferred approach would be to use Profiles and you can google more about them)
As far as your aspect's code goes, it looks and runs fine for me. Link to Code. It would be better if you could share the link to the code-base so that the issue can be investigated a bit further. Nevertheless, it seems a minor issue.
Thanks, guys for your comments, got the simple idea to fix this.
I resolved it with a custom factory implementation to make enable/disable feature working.
My GitHub example code: spring-cloud-resiliency4j

After trying all solutions still facing - system.property org.testng.TestNGException: Cannot instantiate class

I am getting above error (org.testng.TestNGException: Cannot instantiate class) while running my first TestNG program. I have already gone through all the solutions but still issue persists.
I have already downloaded ChromeDriver, set it's correct path in class by using syste.property. Added required jars also. I have set system.setproprty() for chrome Driver, still gettimg the same error. Do I need to add any specific dependency in pom.xml or need to add main() in class?
Below is my class: My question is not getting posted due to less content explanation even thouguh I have written a lot, so adding this also. Parden me for this.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Unit test for simple App.
*/
public class AppTest {
/**
* Create the test case
*
* #param testName
* name of the test case
*/
public AppTest(String testName) {
super();
System.setProperty("webdriver.chrome.driver", "C:/Users/Dell/Downloads/chromedriver_win32/chromedriver.exe");
}
// public static void main()
// {
//
// }
public WebDriver driver = new ChromeDriver();
String appUrl = "https://google.com";
#Test
public void gmailLogin() {
// launch the fire fox browser and open the application url
driver.get(appUrl);
System.out.println("Suceessfully opened the browser URL");
// maximize the browser window
driver.manage().window().maximize();
// declare and initialize the variable to store the expected title of
// the web page.
String expectedTitle = "Sign in - Google Accounts";
// fetch the title of the web page and save it into a string variable
String actualTitle = driver.getTitle();
Assert.assertEquals(expectedTitle, actualTitle);
// enter a valid user name in the email text box
WebElement username = driver.findElement(By.id("Email"));
username.clear();
username.sendKeys("TestSelenium");
// enter a valid password in the password text box
WebElement password = driver.findElement(By.id("Passwd"));
password.clear();
password.sendKeys("password123");
// click on the Sign in button
WebElement SignInButton = driver.findElement(By.id("signIn"));
SignInButton.click();
// close the web browser
driver.close();
}
}
Below are the error logs: I have set System.setProperty() for chrome Driver, still getting the same error. Do I need to add any specific dependency in pom.xml or need to add main() in class?
[RemoteTestNG] detected TestNG version 6.14.2
org.testng.TestNGException:
Cannot instantiate class com.selenium.SampleDemo1.AppTest
at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:30)
at org.testng.internal.ClassHelper.createInstance1(ClassHelper.java:423)
at org.testng.internal.ClassHelper.createInstance(ClassHelper.java:336)
at org.testng.internal.ClassImpl.getDefaultInstance(ClassImpl.java:125)
at org.testng.internal.ClassImpl.getInstances(ClassImpl.java:190)
at org.testng.TestClass.getInstances(TestClass.java:95)
at org.testng.TestClass.initTestClassesAndInstances(TestClass.java:81)
at org.testng.TestClass.init(TestClass.java:73)
at org.testng.TestClass.<init>(TestClass.java:38)
at org.testng.TestRunner.initMethods(TestRunner.java:389)
at org.testng.TestRunner.init(TestRunner.java:271)
at org.testng.TestRunner.init(TestRunner.java:241)
at org.testng.TestRunner.<init>(TestRunner.java:192)
at org.testng.remote.support.RemoteTestNG6_12$1.newTestRunner(RemoteTestNG6_12.java:33)
at org.testng.remote.support.RemoteTestNG6_12$DelegatingTestRunnerFactory.newTestRunner(RemoteTestNG6_12.java:66)
at org.testng.SuiteRunner$ProxyTestRunnerFactory.newTestRunner(SuiteRunner.java:713)
at org.testng.SuiteRunner.init(SuiteRunner.java:260)
at org.testng.TestNG.run(TestNG.java:1017)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:24)
... 25 more
Caused by: java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://chromedriver.storage.googleapis.com/index.html
I have set system.setproprty() for chrome Driver, still gettimg the same error. Do I need to add any specific dependency in pom.xml or need to add main() in class?I have set system.setproprty() for chrome Driver, still gettimg the same error. Do I need to add any specific dependency in pom.xml or need to add main() in class?
The AppTest constructor method where you are setting the system property for chrome driver is not being invoked during execution as per the current code. You can add a new setUpAppTest method with #BeforeClass annotation, so that, the system property can be set for chrome before initializing the chrome driver, as shown below:
#BeforeClass
public void setUpAppTest(String testName) {
System.setProperty("webdriver.chrome.driver", "C:/Users/Dell/Downloads/chromedriver_win32/chromedriver.exe");
}
You will have to import org.testng.annotations.BeforeClass in order to use BeforeClass. Additionally, I would suggest you to use driver.quit(); instead of driver.close(); to ensure proper clean-up of webdriver instance.
I see few issues with the way above method is implemented. Above code is more of the sequential flow where you are defining the initialization in later part of the code, hence you are seeing the above exception.
Try to have a superclass where initialization of the drivers, system property are required to run the test cases. For example: (Define a driver class like below)
public class OnUIStart{
protected void starting(Description description) {
super.starting(description);
if (!DriverManager.INSTANCE.getDriver().isDriverStarted()) {
String testBrowser = System.getenv("TEST_BROWSER");
BrowserType browserType;
if (!StringUtils.isBlank(testBrowser)) {
browserType = BrowserType.valueOf(testBrowser.toUpperCase());
} else {
browserType = BrowserType.CHROME;
}
DriverManager.INSTANCE.setDriverConfiguration(getDriverConfiguration(browserType));
DriverManager.INSTANCE.startDriver();
String url = LocalConfig.INSTANCE.getUrlWithProtocol();
ChangeResolution.setDesktop();
log.info("URL: " + url);
DriverManager.INSTANCE.get(url);
}
}
}
With the above code you can set all the system properties and initialization required. Make sure you have proper modularization of the methods which you defining.
In your test case
public class testClass extends OnUIStart {
}
Above implementation make sure all the initialization happening properly.

How to programmatically create a vertex in aws neptune using java

I am running the following java code (a very small modification on the example posted here https://docs.aws.amazon.com/neptune/latest/userguide/access-graph-gremlin-java.html) and getting a null pointer exception. I see the vertex is created in Neptune, but the driver seems to bomb on the response.
Am I doing something wrong here? Has anyone been successful in programmatically creating a vertex in Neptune using Java.
public class NeptuneMain {
public static void main(String[] args) {
Cluster.Builder builder = Cluster.build();
builder.addContactPoint("<enter cluster url here>");
builder.port(8182);
Cluster cluster = builder.create();
GraphTraversalSource g = EmptyGraph.instance().traversal().withRemote(DriverRemoteConnection.using(cluster));
GraphTraversal t = g.addV("Aspect");
t.forEachRemaining(
e -> System.out.println(e)
);
cluster.close();
}
}
Stack trace is :
Exception in thread "main" java.util.concurrent.CompletionException: java.lang.NullPointerException
at java.util.concurrent.CompletableFuture.reportJoin(CompletableFuture.java:375)
at java.util.concurrent.CompletableFuture.join(CompletableFuture.java:1934)
at org.apache.tinkerpop.gremlin.driver.ResultSet.one(ResultSet.java:107)
at org.apache.tinkerpop.gremlin.driver.ResultSet$1.hasNext(ResultSet.java:159)
at org.apache.tinkerpop.gremlin.driver.ResultSet$1.next(ResultSet.java:166)
at org.apache.tinkerpop.gremlin.driver.ResultSet$1.next(ResultSet.java:153)
at org.apache.tinkerpop.gremlin.driver.remote.DriverRemoteTraversal$TraverserIterator.next(DriverRemoteTraversal.java:142)
at
You might be using an older version (3.2.x) of the gremlin-driver package. Try upgrading to >= 3.3.2 and let us know if you still observe this problem.

Add trycatch inside method code failing with JSR/RET are not supported with computeFrames option

I am writing a Java agent which is supposed to be attached
to a running JVM. On that running JVM, there is a class already loaded and agent wants to instrument a method of that class.
The agent uses the ASM framework to add a try/catch block in the method content which is to be instrumented.
Below is the code I have written to add the try/catch block:
public void visitCode() {
if (mMethodName.equals("test")) {
mv.visitLabel(startFinally);
super.visitCode();
}
}
public void visitMaxs(int maxStack, int maxLocals) {
Label endFinally = new Label();
mv.visitTryCatchBlock(startFinally,endFinally,endFinally,
"java/lang/Exception");
mv.visitLabel(endFinally);
mv.visitVarInsn(ASTORE, 1);
mv.visitVarInsn(ALOAD, 1);
mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Exception",
"printStackTrace", "()V"););
}
I am using ClassWriter.COMPUTE_FRAMES in ClassWriter, but I'm getting an error:
java.lang.RuntimeException: JSR/RET are not supported with computeFrames option
at com.bea.objectweb.asm.Frame.a(Unknown Source)
at com.bea.objectweb.asm.MethodWriter.visitJumpInsn(Unknown Source)
at com.bea.objectweb.asm.ClassReader.a(Unknown Source)