package se.jiderhamn.classloader.leak.prevention.cleanup;

import java.lang.reflect.Field;
import java.util.Map;

import se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor;
import se.jiderhamn.classloader.leak.prevention.ClassLoaderPreMortemCleanUp;

/**
 * Clean up leak caused by {@link javax.xml.parsers.SAXParser} attribute/property being loaded by protected class loader
 * and cached in {@link com.sun.xml.internal.messaging.saaj.soap.EnvelopeFactory#parserPool}.
 * See <a href="https://issues.apache.org/jira/browse/XALANJ-2600">here</a>.
 * @author Mattias Jiderhamn
 */
public class SAAJEnvelopeFactoryParserPoolCleanUp implements ClassLoaderPreMortemCleanUp {
  @Override
  public void cleanUp(ClassLoaderLeakPreventor preventor) {
    Object /*com.sun.xml.internal.messaging.saaj.soap.ContextClassloaderLocal*/
        parserPool = preventor.getStaticFieldValue("com.sun.xml.internal.messaging.saaj.soap.EnvelopeFactory",
        "parserPool");
    if(parserPool == null) {
      // Try the package for the maven dependency if the internal one is not available
      parserPool = preventor.getStaticFieldValue("com.sun.xml.messaging.saaj.soap.EnvelopeFactory",
          "parserPool");
    }
    
    if(parserPool != null) {
      final Field CACHE = preventor.findField(parserPool.getClass().getSuperclass(), "CACHE");
      if(CACHE != null) {
        final Object cache = preventor.getFieldValue(CACHE, parserPool);
        if(cache instanceof Map) { // WeakHashMap
          ((Map) cache).remove(preventor.getClassLoader());
        }
      }
    }
  }
}
@@ -759,134 +759,261 @@
     
-Object /*com.sun.xml.internal.messaging.saaj.soap.ContextClassloaderLocal*/%0A        parserPool = preventor.getStaticFieldValue
+// Internal class from the JDK (Removed in JDK11)%0A    cleanupWithFactoryClass(preventor, preventor.findClass(%22com.sun.xml.internal.messaging.saaj.soap.EnvelopeFactory%22));%0A    // Maven dependency%0A    cleanupWithFactoryClass(preventor, preventor.findClass
 (%22co
@@ -1018,33 +1018,24 @@
 com.sun.xml.
-internal.
 messaging.sa
@@ -1062,258 +1062,196 @@
 ory%22
-,%0A        %22parserPool%22);%0A    if(parserPool == null) %7B%0A      // Try the package for the maven dependency if the internal one is not available%0A      parserPool = preventor.getStaticFieldValue(%22com.sun.xml.messaging.saaj.soap.EnvelopeFactory%22,%0A         
+));%0A  %7D%0A%0A  private void cleanupWithFactoryClass(final ClassLoaderLeakPreventor preventor, Class%3C?%3E factoryClass) %7B%0A    final Object parserPool = preventor.getStaticFieldValue(factoryClass,
  %22pa
@@ -1262,22 +1262,16 @@
 Pool%22);%0A
-    %7D%0A
     %0A   

Clean up internal class an dependency class