HOAB

History of a bug

Spring @ControllerAdvice order and precedence

Rédigé par gorki Aucun commentaire

Problem :

I added a second @ControllerAdvice to handle my 404 pages in addition to an existing @ControllerAdvice that was handling a REST Api for the backend part.

My newer controller advice has : 

    @ExceptionHandler(NoHandlerFoundException.class)
    public ModelAndView handleError404(HttpServletRequest request, Exception e) {
        if (request.getRequestURI().startsWith("/api")) {
            throw new ResourceNotFoundException();
        } else {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("forward:/index.html");
            return mv;
        }
    }

The existing one has : 

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ErrorDTO handleException(Exception e) {
        log.error(e.getMessage(), e);
        return new ErrorDTO(e.getMessage(), "E01");
    }

On dev environment, it works.

On production environment, it fails : only the REST API exception handler was used.

A remote debug show me that I was in : @ExceptionHandler(Exception.class)

the general exception handler, and the exception thrown is NoHandlerFoundException

Solution :

I tried this solution : 

  • Use @Order on each class
  • as seen here

But it also fails and as noted in the answers : 

I also found in the documentation that :

https://docs.spring.io/spring-framework/docs/4.3.4.RELEASE/javadoc-api/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolver.html#getExceptionHandlerMethod-org.springframework.web.method.HandlerMethod-java.lang.Exception-

ExceptionHandlerMethod

protected ServletInvocableHandlerMethod getExceptionHandlerMethod(HandlerMethod handlerMethod, Exception exception)

Find an @ExceptionHandler method for the given exception. The default implementation searches methods in the class hierarchy of the controller first and if not found, it continues searching for additional @ExceptionHandler methods assuming some @ControllerAdvice Spring-managed beans were detected. Parameters: handlerMethod - the method where the exception was raised (may be null) exception - the raised exception Returns: a method to handle the exception, or null

So I merged the both classes and it works.

But it's not really clear : 

  • Older exception handler is not in the class hierarchy
  • I did not check if my latest exception handler was well detected on production (code is the same and it works in dev)

So not yet the final word, but too late for today :)

 

 

 

AtomicLong vs Long

Rédigé par gorki Aucun commentaire

Problem :

I searched for an simple example of AtomicLong vs Long problem.

Thanks to Ecosia IA (ChatGPT), here is a simple example

Solution :

Result is : 

  • Counter value (Long): 34938
  • Counter value (AtomicLong): 100000

Here is the code :

package tools;
import java.util.concurrent.atomic.AtomicLong;

public class AtomicLongExample {
    private static Long counter = 0L;
    private static AtomicLong atomicCounter = new AtomicLong(0);

    public static void main(String[] args) {
        // Create and start multiple threads
        Thread[] threads = new Thread[100];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(new CounterRunnable());
            threads[i].start();
        }

        // Wait for all threads to finish
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("Counter value (Long): " + counter);
        System.out.println("Counter value (AtomicLong): " + atomicCounter.get());
    }

    static class CounterRunnable implements Runnable {
        @Override
        public void run() {
            // Increment the counter using Long variable within a loop
            // This may lead to race conditions and incorrect results
            for (int i = 0; i < 1000; i++) {
                counter++;
            }

            // Increment the counter using AtomicLong within a loop
            // This ensures atomicity and thread-safety
            for (int i = 0; i < 1000; i++) {
                atomicCounter.incrementAndGet();
            }
        }
    }
}

SpringBoot OSGI and templated OSGI modules with external constrant Jetty

Rédigé par gorki Aucun commentaire

Problem :

A very specific and particular problem.

I want to deploy  a SpringBoot application, in an OSGI environment, in a external Jetty server…

So I found solution do deploy Springboot in OSGI : here or here. Very good by the wat.

And also to deploy Springboot as war for an external Tomcat…

Too easy, my external Jetty server was rejecting Servlet 3.0 application startup… (hard coding for : 

context.setAttribute("org.eclipse.jetty.containerInitializers", initializers);

Yes, it's better, starting a 1,25 days of try and success !

Solution :

My first web application was deployed with Spring Dispatcher Servlet with a BundleActivator

My second web application was deployed with Spring DispatcherServlet AND a SpringBootApplication intialized with the ressource loader of the BundleActivator (as in the OSGI example) : component-scan is working ! 

My third web application was switching to an initialization Servlet 3.0 with an extension of ServletContainerInitializer, thanks to harded jetty configuration, it's not working

My third and a half remove all web.xml content to keep only a context listener as my Jetty was doing nothing : 

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    <!-- ServletContainerInitializer can not be used here -->
    <!-- XXXXXXX is putting in hard : context.setAttribute("org.eclipse.jetty.containerInitializers with only Jasper -->

    <!-- At the end, it's possible to load SpringBoot with this context listener -->
    <listener>
        <listener-class>
            com.hexagon.introscope.extension.MyContextLoaderListener
        </listener-class>
    </listener>

</web-app>

My fourth web application was trying to load the Springboot application file as a YAML file (why so simple !), resolved with a “hack” :

  • The ServletContext has a way to store the configuration directory, during the initialization, I saved it somewhere : HpaContextLoaderListener.getConfigDirectory() 

The listener loader : 

package com.xxxxx.extension;

import org.eclipse.jetty.webapp.WebAppContext;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import java.io.File;
import java.nio.file.Path;

public class MyContextLoaderListener implements ServletContextListener {

    private static File configDirectory;

    public static File getConfigDirectory() {
        return configDirectory;
    }

    public void contextInitialized(ServletContextEvent event) {
        ServletContext servletContext = event.getServletContext();
        MySpringBootHexagonActivator app = new MySpringBootHexagonActivator();

        try {
            configDirectory = servletContext.getAttribute("introscope.em"));
            
            InstantiateHelper.getValueByMethod(servletContext, "setExtendedListenerTypes", new Class[]{boolean.class}, true);

            app.onStartup(event.getServletContext());
        } catch (ServletException e) {
            throw new RuntimeException(e);
        }
    }

    public void contextDestroyed(ServletContextEvent event) {
    }
}

 

@SpringBootApplication
public class MySpringBootHexagonActivator extends SpringBootServletInitializer {

    protected SpringApplicationBuilder createSpringApplicationBuilder() {
        SpringApplicationBuilder builder = super.createSpringApplicationBuilder();
        Map<String, Object> properties = new HashMap<>();
        Path propertyFile = Path.of(MyContextLoaderListener.getConfigDirectory().getPath(), "application-extension.yml");
        properties.put("spring.config.location", propertyFile.toString());
        builder.properties(properties);
        builder.resourceLoader(HpaHexagonActivator.getResourceResolver());

        return builder;
    }
}

The HpaHexagonActivator.getResourceResolver() is the trick from SpringBoot OSGI example to load classes from Bundle classpath. I store the ressources resolver in a static variable that I can access from everywhere.

A word on that one : 

InstantiateHelper.getValueByMethod(servletContext, "setExtendedListenerTypes", new Class[]{boolean.class}, true);

I'm in OSGI, Jetty controls the listener class, and Springboot is unknown. You can authorized additional listeners but in my case, Jetty is not exported by the other OSGI package, not able to call it simply so… reflection : InstantiateHelper is basically a helper class to call methods by reflection.

 

At the end : 

  1. Springboot starts
  2. Springboot scans package offered by BundleActivator ressource locator
  3. Springboot can use an external configuration file, in YAML
  4. Springboot starts REST & Database
  5. It was hard.

Of course, lot of tries between these big steps !

The goal is to extend a 3rd party product without having source code.

CA Apm Introscope and tracer not executed

Rédigé par gorki Aucun commentaire

Problem :

Silent code :) Configuration was OK, or seems to be, logs was OK but nothing happen.

For a project, I use Broadcom CA APM, formely Introscope, I created a custom Tracer, adding the required configuration but my tracer was not executed. Furthermore, another “standard” tracer was not executed also.

Solution :

Easy steps : 

  • Check the agent logs : ERROR is displayed :
    • [IntroscopeAgent.Agent] Unable to create tracer factories for the following class (library not found): 
  • Put agent logs in VERBOSE mode, I would had the solution directly
    • Same information class not found.
  • But because I everything for remote debug ready, I lost time but learn things
    • My tracer was using the same flag as the standard one : if one tracer can not be created, the whole flag is not enabled.
  • You can trace the classes to check if they are correctly instrumented compared to AutoProbe log. I never, never had a difference hier. If it says it's instrumented, then it is.
  •  

At the end the problem is "class not found" for one of the 2 tracers. So simple

And the class was of course present in the jar file. So it was related to the declaration of this class in the MANIFEST.MF required for CA APM Introscope extension : 

com-wily-Extension-Plugin-XXXX-Name: XXXX Frontend Tracer
com-wily-Extension-Plugin-XXXX-Type: tracer
com-wily-Extension-Plugin-XXXX-Version: 1
com-wily-Extension-Plugin-XXXX-Entry-Point-Class: com.xxx.xxxx.MyTracer

 

Lire la suite de CA Apm Introscope and tracer not executed

Introscope intrumentation static / final method

Rédigé par gorki Aucun commentaire

Problem :

It seems that I have no metric on one particular method while it works for all the others.

This is method is  :

public final boolean myMethod(myArgs) 

Does the fact that this method is final is a problem for bytecode instrumentation of Introscope ?

Solution :

No. It works :) As usual. My problem is somewhere else.

3 classes : 

Parent

package com.test.caapm.finalmethodtest;

public class ParentClass {
    public void finalMethod() {
        System.out.println("parentFinalMethod");
    }
}

Middle

package com.test.caapm.finalmethodtest;

public class TestFinalMethodAgent extends ParentClass {

    public static void staticMethod() {
        System.out.println("staticMethod");
    }

    public final static void finalStaticMethod() {
        System.out.println("finalStaticMethod");
    }

    public final void finalMethod() {
        System.out.println("finalMethod");
    }

    public static void main(String... args) {
        TestFinalMethodAgent test = new TestFinalMethodAgent();

        while(true) {
            test.finalMethod();
            TestFinalMethodAgent.staticMethod();
            TestFinalMethodAgent.finalStaticMethod();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

}

Child

package com.test.caapm.finalmethodtest;

public class ChildClass extends TestFinalMethodAgent{
}

Pbd

SetFlag: TestFinalMethod
TurnOn: TestFinalMethod

IdentifyDeepInheritedAs: com.test.caapm.finalmethodtest.ParentClass TestFinalMethod

TraceAllMethodsIfFlagged: TestFinalMethod PerIntervalCounter "{classname} - {method}"

 

 

 

 

 

 

Fil RSS des articles de cette catégorie