1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.mycore.common.events;
20
21 import java.io.File;
22 import java.io.IOException;
23 import java.net.URL;
24 import java.security.CodeSource;
25 import java.security.ProtectionDomain;
26 import java.util.Enumeration;
27 import java.util.Set;
28
29 import org.apache.logging.log4j.LogManager;
30 import org.apache.logging.log4j.Logger;
31 import org.mycore.common.MCRClassTools;
32
33 import jakarta.servlet.ServletContainerInitializer;
34 import jakarta.servlet.ServletContext;
35 import jakarta.servlet.ServletException;
36 import se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor;
37 import se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventorFactory;
38
39
40
41
42 public class MCRServletContainerInitializer implements ServletContainerInitializer {
43
44
45
46
47 @Override
48 public void onStartup(final Set<Class<?>> c, final ServletContext ctx) throws ServletException {
49 final boolean runClassLoaderLeakPreventor = runClassLoaderLeakPreventor();
50 ClassLoaderLeakPreventor leakPreventor = null;
51 if (runClassLoaderLeakPreventor) {
52 final ClassLoaderLeakPreventorFactory leakPreventorFactory = new ClassLoaderLeakPreventorFactory();
53 ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
54 leakPreventor = leakPreventorFactory.newLeakPreventor(classLoader);
55 leakPreventor.runPreClassLoaderInitiators();
56 }
57 MCRShutdownHandler shutdownHandler = MCRShutdownHandler.getInstance();
58 shutdownHandler.isWebAppRunning = true;
59 shutdownHandler.leakPreventor = leakPreventor;
60 MCRStartupHandler.startUp(ctx);
61
62 final Logger logger = LogManager.getLogger();
63 if (logger.isDebugEnabled()) {
64 try {
65 Enumeration<URL> resources = MCRClassTools.getClassLoader().getResources("META-INF/web-fragment.xml");
66 while (resources.hasMoreElements()) {
67 logger.debug("Found: {}", resources.nextElement());
68 }
69 } catch (IOException e) {
70
71 e.printStackTrace();
72 }
73 logger.debug("This class is here: {}", getSource(this.getClass()));
74 }
75 }
76
77 private static String getSource(final Class<? extends MCRServletContainerInitializer> clazz) {
78 if (clazz == null) {
79 return null;
80 }
81 ProtectionDomain protectionDomain = clazz.getProtectionDomain();
82 CodeSource codeSource = protectionDomain.getCodeSource();
83 if (codeSource == null) {
84 LogManager.getLogger().warn("Cannot get CodeSource.");
85 return null;
86 }
87 URL location = codeSource.getLocation();
88 String fileName = location.getFile();
89 File sourceFile = new File(fileName);
90 return sourceFile.getName();
91 }
92
93 private boolean runClassLoaderLeakPreventor() {
94
95 String defaultValue = (Runtime.version().feature() > 11) ? Boolean.FALSE.toString() : Boolean.TRUE.toString();
96 final String propValue = System.getProperty("MCR.ClassLoaderLeakPreventor", defaultValue);
97 return Boolean.parseBoolean(propValue);
98 }
99
100 }