sonar web 启动过程,sonar-web 下面含有的代码了还是很大的,主main入口是webserver:

webserver类代码:

/** SonarQube* Copyright (C) 2009-2016 SonarSource SA* mailto:contact AT sonarsource DOT com** This program is free software; you can redistribute it and/or* modify it under the terms of the GNU Lesser General Public* License as published by the Free Software Foundation; either* version 3 of the License, or (at your option) any later version.** This program is distributed in the hope that it will be useful,* but WITHOUT ANY WARRANTY; without even the implied warranty of* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU* Lesser General Public License for more details.** You should have received a copy of the GNU Lesser General Public License* along with this program; if not, write to the Free Software Foundation,* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.*/
package org.sonar.server.app;import com.google.common.collect.ImmutableMap;
import org.sonar.process.MinimumViableSystem;
import org.sonar.process.Monitored;
import org.sonar.process.ProcessEntryPoint;
import org.sonar.process.Props;public class WebServer implements Monitored {private final EmbeddedTomcat tomcat;WebServer(Props props) {new MinimumViableSystem().checkWritableTempDir().checkRequiredJavaOptions(ImmutableMap.of("file.encoding", "UTF-8"));this.tomcat = new EmbeddedTomcat(props);}@Overridepublic void start() {tomcat.start();}@Overridepublic boolean isUp() {return tomcat.isUp();}@Overridepublic void stop() {tomcat.terminate();}@Overridepublic void awaitStop() {tomcat.awaitTermination();}/*** Can't be started as is. Needs to be bootstrapped by sonar-application*/public static void main(String[] args) {ProcessEntryPoint entryPoint = ProcessEntryPoint.createForArguments(args);Props props = entryPoint.getProps();new WebServerProcessLogging().configure(props);WebServer server = new WebServer(props);entryPoint.launch(server);}
}

EmbededTomcat:

/** SonarQube* Copyright (C) 2009-2016 SonarSource SA* mailto:contact AT sonarsource DOT com** This program is free software; you can redistribute it and/or* modify it under the terms of the GNU Lesser General Public* License as published by the Free Software Foundation; either* version 3 of the License, or (at your option) any later version.** This program is distributed in the hope that it will be useful,* but WITHOUT ANY WARRANTY; without even the implied warranty of* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU* Lesser General Public License for more details.** You should have received a copy of the GNU Lesser General Public License* along with this program; if not, write to the Free Software Foundation,* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.*/
package org.sonar.server.app;import com.google.common.base.Throwables;
import java.io.File;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.sonar.api.utils.log.Loggers;
import org.sonar.process.ProcessProperties;
import org.sonar.process.Props;import static org.sonar.core.util.FileUtils.deleteQuietly;class EmbeddedTomcat {private final Props props;private Tomcat tomcat = null;private volatile StandardContext webappContext;EmbeddedTomcat(Props props) {this.props = props;}void start() {// '%2F' (slash /) and '%5C' (backslash \) are permitted as path delimiters in URLs// See Ruby on Rails url_forSystem.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true");System.setProperty("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE", "true");tomcat = new Tomcat();// Initialize directoriesString basedir = tomcatBasedir().getAbsolutePath();tomcat.setBaseDir(basedir);tomcat.getHost().setAppBase(basedir);tomcat.getHost().setAutoDeploy(false);tomcat.getHost().setCreateDirs(false);tomcat.getHost().setDeployOnStartup(true);new TomcatAccessLog().configure(tomcat, props);TomcatConnectors.configure(tomcat, props);webappContext = new TomcatContexts().configure(tomcat, props);try {tomcat.start();new TomcatStartupLogs(Loggers.get(getClass())).log(tomcat);} catch (LifecycleException e) {Throwables.propagate(e);}}boolean isUp() {if (webappContext == null) {return false;}switch (webappContext.getState()) {case NEW:case INITIALIZING:case INITIALIZED:case STARTING_PREP:case STARTING:return false;case STARTED:return true;default:// problem, stopped or failedthrow new IllegalStateException("Webapp did not start");}}private File tomcatBasedir() {return new File(props.value(ProcessProperties.PATH_TEMP), "tc");}void terminate() {if (tomcat.getServer().getState().isAvailable()) {try {tomcat.stop();tomcat.destroy();} catch (Exception e) {Loggers.get(EmbeddedTomcat.class).error("Fail to stop web server", e);}}deleteQuietly(tomcatBasedir());}void awaitTermination() {tomcat.getServer().await();}
}

从代码上,是调用Tomcat start方法,Tomacat 类是sonar-web 主pom中依赖的jar 包

tomcat类来自tomcat-embad-core.jar

package org.apache.catalina.startup;import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.SingleThreadModel;
import javax.servlet.annotation.WebServlet;
import org.apache.catalina.Container;
import org.apache.catalina.Context;
import org.apache.catalina.Engine;
import org.apache.catalina.Host;
import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.Pipeline;
import org.apache.catalina.Realm;
import org.apache.catalina.Server;
import org.apache.catalina.Service;
import org.apache.catalina.Wrapper;
import org.apache.catalina.authenticator.NonLoginAuthenticator;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.ContainerBase;
import org.apache.catalina.core.NamingContextListener;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.core.StandardServer;
import org.apache.catalina.core.StandardService;
import org.apache.catalina.core.StandardWrapper;
import org.apache.catalina.realm.GenericPrincipal;
import org.apache.catalina.realm.RealmBase;
import org.apache.tomcat.util.descriptor.web.LoginConfig;public class Tomcat
{private final Map<String, Logger> pinnedLoggers = new HashMap();protected Server server;protected Service service;protected Engine engine;protected Connector connector;protected Host host;protected int port = 8080;protected String hostname = "localhost";protected String basedir;private final Map<String, String> userPass = new HashMap();private final Map<String, List<String>> userRoles = new HashMap();private final Map<String, Principal> userPrincipals = new HashMap();public void setBaseDir(String basedir){this.basedir = basedir;}public void setPort(int port){this.port = port;}public void setHostname(String s){this.hostname = s;}public Context addWebapp(String contextPath, String docBase)throws ServletException{return addWebapp(getHost(), contextPath, docBase);}public Context addContext(String contextPath, String docBase){return addContext(getHost(), contextPath, docBase);}public Wrapper addServlet(String contextPath, String servletName, String servletClass){Container ctx = getHost().findChild(contextPath);return addServlet((Context)ctx, servletName, servletClass);}public static Wrapper addServlet(Context ctx, String servletName, String servletClass){Wrapper sw = ctx.createWrapper();sw.setServletClass(servletClass);sw.setName(servletName);ctx.addChild(sw);return sw;}public Wrapper addServlet(String contextPath, String servletName, Servlet servlet){Container ctx = getHost().findChild(contextPath);return addServlet((Context)ctx, servletName, servlet);}public static Wrapper addServlet(Context ctx, String servletName, Servlet servlet){Wrapper sw = new ExistingStandardWrapper(servlet);sw.setName(servletName);ctx.addChild(sw);return sw;}public void init()throws LifecycleException{getServer();getConnector();this.server.init();}public void start()throws LifecycleException{getServer();getConnector();this.server.start();}public void stop()throws LifecycleException{getServer();this.server.stop();}public void destroy()throws LifecycleException{getServer();this.server.destroy();}public void addUser(String user, String pass){this.userPass.put(user, pass);}public void addRole(String user, String role){List<String> roles = (List)this.userRoles.get(user);if (roles == null){roles = new ArrayList();this.userRoles.put(user, roles);}roles.add(role);}public Connector getConnector(){getServer();if (this.connector != null) {return this.connector;}this.connector = new Connector("HTTP/1.1");this.connector.setPort(this.port);this.service.addConnector(this.connector);return this.connector;}public void setConnector(Connector connector){this.connector = connector;}public Service getService(){getServer();return this.service;}public void setHost(Host host){this.host = host;}public Host getHost(){if (this.host == null){this.host = new StandardHost();this.host.setName(this.hostname);getEngine().addChild(this.host);}return this.host;}public Engine getEngine(){if (this.engine == null){getServer();this.engine = new StandardEngine();this.engine.setName("Tomcat");this.engine.setDefaultHost(this.hostname);this.engine.setRealm(createDefaultRealm());this.service.setContainer(this.engine);}return this.engine;}public Server getServer(){if (this.server != null) {return this.server;}System.setProperty("catalina.useNaming", "false");this.server = new StandardServer();initBaseDir();this.server.setPort(-1);this.service = new StandardService();this.service.setName("Tomcat");this.server.addService(this.service);return this.server;}public Context addContext(Host host, String contextPath, String dir){return addContext(host, contextPath, contextPath, dir);}public Context addContext(Host host, String contextPath, String contextName, String dir){silence(host, contextName);Context ctx = createContext(host, contextPath);ctx.setName(contextName);ctx.setPath(contextPath);ctx.setDocBase(dir);ctx.addLifecycleListener(new FixContextListener());if (host == null) {getHost().addChild(ctx);} else {host.addChild(ctx);}return ctx;}public Context addWebapp(Host host, String contextPath, String docBase){return addWebapp(host, contextPath, docBase, new ContextConfig());}@Deprecatedpublic Context addWebapp(Host host, String contextPath, String name, String docBase){return addWebapp(host, contextPath, docBase, new ContextConfig());}public Context addWebapp(Host host, String contextPath, String docBase, ContextConfig config){silence(host, contextPath);Context ctx = createContext(host, contextPath);ctx.setPath(contextPath);ctx.setDocBase(docBase);ctx.addLifecycleListener(new DefaultWebXmlListener());ctx.setConfigFile(getWebappConfigFile(docBase, contextPath));ctx.addLifecycleListener(config);config.setDefaultWebXml(noDefaultWebXmlPath());if (host == null) {getHost().addChild(ctx);} else {host.addChild(ctx);}return ctx;}public LifecycleListener getDefaultWebXmlListener(){return new DefaultWebXmlListener();}public String noDefaultWebXmlPath(){return "org/apache/catalina/startup/NO_DEFAULT_XML";}protected Realm createDefaultRealm(){new RealmBase(){protected String getName(){return "Simple";}protected String getPassword(String username){return (String)Tomcat.this.userPass.get(username);}protected Principal getPrincipal(String username){Principal p = (Principal)Tomcat.this.userPrincipals.get(username);if (p == null){String pass = (String)Tomcat.this.userPass.get(username);if (pass != null){p = new GenericPrincipal(username, pass, (List)Tomcat.this.userRoles.get(username));Tomcat.this.userPrincipals.put(username, p);}}return p;}};}protected void initBaseDir(){String catalinaHome = System.getProperty("catalina.home");if (this.basedir == null) {this.basedir = System.getProperty("catalina.base");}if (this.basedir == null) {this.basedir = catalinaHome;}if (this.basedir == null) {this.basedir = (System.getProperty("user.dir") + "/tomcat." + this.port);}File baseFile = new File(this.basedir);baseFile.mkdirs();try{baseFile = baseFile.getCanonicalFile();}catch (IOException e){baseFile = baseFile.getAbsoluteFile();}this.server.setCatalinaBase(baseFile);System.setProperty("catalina.base", baseFile.getPath());this.basedir = baseFile.getPath();if (catalinaHome == null){this.server.setCatalinaHome(baseFile);}else{File homeFile = new File(catalinaHome);homeFile.mkdirs();try{homeFile = homeFile.getCanonicalFile();}catch (IOException e){homeFile = homeFile.getAbsoluteFile();}this.server.setCatalinaHome(homeFile);}System.setProperty("catalina.home", this.server.getCatalinaHome().getPath());}static final String[] silences = { "org.apache.coyote.http11.Http11Protocol", "org.apache.catalina.core.StandardService", "org.apache.catalina.core.StandardEngine", "org.apache.catalina.startup.ContextConfig", "org.apache.catalina.core.ApplicationContext", "org.apache.catalina.core.AprLifecycleListener" };private boolean silent = false;public void setSilent(boolean silent){this.silent = silent;for (String s : silences){Logger logger = Logger.getLogger(s);this.pinnedLoggers.put(s, logger);if (silent) {logger.setLevel(Level.WARNING);} else {logger.setLevel(Level.INFO);}}}private void silence(Host host, String contextPath){String loggerName = getLoggerName(host, contextPath);Logger logger = Logger.getLogger(loggerName);this.pinnedLoggers.put(loggerName, logger);if (this.silent) {logger.setLevel(Level.WARNING);} else {logger.setLevel(Level.INFO);}}private String getLoggerName(Host host, String contextName){if (host == null) {host = getHost();}StringBuilder loggerName = new StringBuilder();loggerName.append(ContainerBase.class.getName());loggerName.append(".[");loggerName.append(host.getParent().getName());loggerName.append("].[");loggerName.append(host.getName());loggerName.append("].[");if ((contextName == null) || (contextName.equals(""))){loggerName.append("/");}else if (contextName.startsWith("##")){loggerName.append("/");loggerName.append(contextName);}loggerName.append(']');return loggerName.toString();}private Context createContext(Host host, String url){String contextClass = StandardContext.class.getName();if (host == null) {host = getHost();}if ((host instanceof StandardHost)) {contextClass = ((StandardHost)host).getContextClass();}try{return (Context)Class.forName(contextClass).getConstructor(new Class[0]).newInstance(new Object[0]);}catch (InstantiationException|IllegalAccessException|IllegalArgumentException|InvocationTargetException|NoSuchMethodException|SecurityException|ClassNotFoundException e){throw new IllegalArgumentException("Can't instantiate context-class " + contextClass + " for host " + host + " and url " + url, e);}}public void enableNaming(){getServer();this.server.addLifecycleListener(new NamingContextListener());System.setProperty("catalina.useNaming", "true");String value = "org.apache.naming";String oldValue = System.getProperty("java.naming.factory.url.pkgs");if (oldValue != null) {if (oldValue.contains(value)) {value = oldValue;} else {value = value + ":" + oldValue;}}System.setProperty("java.naming.factory.url.pkgs", value);value = System.getProperty("java.naming.factory.initial");if (value == null) {System.setProperty("java.naming.factory.initial", "org.apache.naming.java.javaURLContextFactory");}}public void initWebappDefaults(String contextPath){Container ctx = getHost().findChild(contextPath);initWebappDefaults((Context)ctx);}public static void initWebappDefaults(Context ctx){Wrapper servlet = addServlet(ctx, "default", "org.apache.catalina.servlets.DefaultServlet");servlet.setLoadOnStartup(1);servlet.setOverridable(true);servlet = addServlet(ctx, "jsp", "org.apache.jasper.servlet.JspServlet");servlet.addInitParameter("fork", "false");servlet.setLoadOnStartup(3);servlet.setOverridable(true);ctx.addServletMapping("/", "default");ctx.addServletMapping("*.jsp", "jsp");ctx.addServletMapping("*.jspx", "jsp");ctx.setSessionTimeout(30);for (int i = 0; i < DEFAULT_MIME_MAPPINGS.length;) {ctx.addMimeMapping(DEFAULT_MIME_MAPPINGS[(i++)], DEFAULT_MIME_MAPPINGS[(i++)]);}ctx.addWelcomeFile("index.html");ctx.addWelcomeFile("index.htm");ctx.addWelcomeFile("index.jsp");}public static class FixContextListenerimplements LifecycleListener{public void lifecycleEvent(LifecycleEvent event){try{Context context = (Context)event.getLifecycle();if (event.getType().equals("configure_start")) {context.setConfigured(true);}if (context.getLoginConfig() == null){context.setLoginConfig(new LoginConfig("NONE", null, null, null));context.getPipeline().addValve(new NonLoginAuthenticator());}}catch (ClassCastException e) {}}}public static class DefaultWebXmlListenerimplements LifecycleListener{public void lifecycleEvent(LifecycleEvent event){if ("before_start".equals(event.getType())) {Tomcat.initWebappDefaults((Context)event.getLifecycle());}}}public static class ExistingStandardWrapperextends StandardWrapper{private final Servlet existing;public ExistingStandardWrapper(Servlet existing){this.existing = existing;if ((existing instanceof SingleThreadModel)){this.singleThreadModel = true;this.instancePool = new Stack();}this.asyncSupported = hasAsync(existing);}private static boolean hasAsync(Servlet existing){boolean result = false;Class<?> clazz = existing.getClass();WebServlet ws = (WebServlet)clazz.getAnnotation(WebServlet.class);if (ws != null) {result = ws.asyncSupported();}return result;}public synchronized Servlet loadServlet()throws ServletException{if (this.singleThreadModel){try{instance = (Servlet)this.existing.getClass().newInstance();}catch (InstantiationException e){Servlet instance;throw new ServletException(e);}catch (IllegalAccessException e){throw new ServletException(e);}Servlet instance;instance.init(this.facade);return instance;}if (!this.instanceInitialized){this.existing.init(this.facade);this.instanceInitialized = true;}return this.existing;}public long getAvailable(){return 0L;}public boolean isUnavailable(){return false;}public Servlet getServlet(){return this.existing;}public String getServletClass(){return this.existing.getClass().getName();}}private static final String[] DEFAULT_MIME_MAPPINGS = { "abs", "audio/x-mpeg", "ai", "application/postscript", "aif", "audio/x-aiff", "aifc", "audio/x-aiff", "aiff", "audio/x-aiff", "aim", "application/x-aim", "art", "image/x-jg", "asf", "video/x-ms-asf", "asx", "video/x-ms-asf", "au", "audio/basic", "avi", "video/x-msvideo", "avx", "video/x-rad-screenplay", "bcpio", "application/x-bcpio", "bin", "application/octet-stream", "bmp", "image/bmp", "body", "text/html", "cdf", "application/x-cdf", "cer", "application/pkix-cert", "class", "application/java", "cpio", "application/x-cpio", "csh", "application/x-csh", "css", "text/css", "dib", "image/bmp", "doc", "application/msword", "dtd", "application/xml-dtd", "dv", "video/x-dv", "dvi", "application/x-dvi", "eps", "application/postscript", "etx", "text/x-setext", "exe", "application/octet-stream", "gif", "image/gif", "gtar", "application/x-gtar", "gz", "application/x-gzip", "hdf", "application/x-hdf", "hqx", "application/mac-binhex40", "htc", "text/x-component", "htm", "text/html", "html", "text/html", "ief", "image/ief", "jad", "text/vnd.sun.j2me.app-descriptor", "jar", "application/java-archive", "java", "text/x-java-source", "jnlp", "application/x-java-jnlp-file", "jpe", "image/jpeg", "jpeg", "image/jpeg", "jpg", "image/jpeg", "js", "application/javascript", "jsf", "text/plain", "jspf", "text/plain", "kar", "audio/midi", "latex", "application/x-latex", "m3u", "audio/x-mpegurl", "mac", "image/x-macpaint", "man", "text/troff", "mathml", "application/mathml+xml", "me", "text/troff", "mid", "audio/midi", "midi", "audio/midi", "mif", "application/x-mif", "mov", "video/quicktime", "movie", "video/x-sgi-movie", "mp1", "audio/mpeg", "mp2", "audio/mpeg", "mp3", "audio/mpeg", "mp4", "video/mp4", "mpa", "audio/mpeg", "mpe", "video/mpeg", "mpeg", "video/mpeg", "mpega", "audio/x-mpeg", "mpg", "video/mpeg", "mpv2", "video/mpeg2", "nc", "application/x-netcdf", "oda", "application/oda", "odb", "application/vnd.oasis.opendocument.database", "odc", "application/vnd.oasis.opendocument.chart", "odf", "application/vnd.oasis.opendocument.formula", "odg", "application/vnd.oasis.opendocument.graphics", "odi", "application/vnd.oasis.opendocument.image", "odm", "application/vnd.oasis.opendocument.text-master", "odp", "application/vnd.oasis.opendocument.presentation", "ods", "application/vnd.oasis.opendocument.spreadsheet", "odt", "application/vnd.oasis.opendocument.text", "otg", "application/vnd.oasis.opendocument.graphics-template", "oth", "application/vnd.oasis.opendocument.text-web", "otp", "application/vnd.oasis.opendocument.presentation-template", "ots", "application/vnd.oasis.opendocument.spreadsheet-template ", "ott", "application/vnd.oasis.opendocument.text-template", "ogx", "application/ogg", "ogv", "video/ogg", "oga", "audio/ogg", "ogg", "audio/ogg", "spx", "audio/ogg", "flac", "audio/flac", "anx", "application/annodex", "axa", "audio/annodex", "axv", "video/annodex", "xspf", "application/xspf+xml", "pbm", "image/x-portable-bitmap", "pct", "image/pict", "pdf", "application/pdf", "pgm", "image/x-portable-graymap", "pic", "image/pict", "pict", "image/pict", "pls", "audio/x-scpls", "png", "image/png", "pnm", "image/x-portable-anymap", "pnt", "image/x-macpaint", "ppm", "image/x-portable-pixmap", "ppt", "application/vnd.ms-powerpoint", "pps", "application/vnd.ms-powerpoint", "ps", "application/postscript", "psd", "image/vnd.adobe.photoshop", "qt", "video/quicktime", "qti", "image/x-quicktime", "qtif", "image/x-quicktime", "ras", "image/x-cmu-raster", "rdf", "application/rdf+xml", "rgb", "image/x-rgb", "rm", "application/vnd.rn-realmedia", "roff", "text/troff", "rtf", "application/rtf", "rtx", "text/richtext", "sh", "application/x-sh", "shar", "application/x-shar", "sit", "application/x-stuffit", "snd", "audio/basic", "src", "application/x-wais-source", "sv4cpio", "application/x-sv4cpio", "sv4crc", "application/x-sv4crc", "svg", "image/svg+xml", "svgz", "image/svg+xml", "swf", "application/x-shockwave-flash", "t", "text/troff", "tar", "application/x-tar", "tcl", "application/x-tcl", "tex", "application/x-tex", "texi", "application/x-texinfo", "texinfo", "application/x-texinfo", "tif", "image/tiff", "tiff", "image/tiff", "tr", "text/troff", "tsv", "text/tab-separated-values", "txt", "text/plain", "ulw", "audio/basic", "ustar", "application/x-ustar", "vxml", "application/voicexml+xml", "xbm", "image/x-xbitmap", "xht", "application/xhtml+xml", "xhtml", "application/xhtml+xml", "xls", "application/vnd.ms-excel", "xml", "application/xml", "xpm", "image/x-xpixmap", "xsl", "application/xml", "xslt", "application/xslt+xml", "xul", "application/vnd.mozilla.xul+xml", "xwd", "image/x-xwindowdump", "vsd", "application/vnd.visio", "wav", "audio/x-wav", "wbmp", "image/vnd.wap.wbmp", "wml", "text/vnd.wap.wml", "wmlc", "application/vnd.wap.wmlc", "wmls", "text/vnd.wap.wmlsc", "wmlscriptc", "application/vnd.wap.wmlscriptc", "wmv", "video/x-ms-wmv", "wrl", "model/vrml", "wspolicy", "application/wspolicy+xml", "Z", "application/x-compress", "z", "application/x-compress", "zip", "application/zip" };protected URL getWebappConfigFile(String path, String contextName){File docBase = new File(path);if (docBase.isDirectory()) {return getWebappConfigFileFromDirectory(docBase, contextName);}return getWebappConfigFileFromJar(docBase, contextName);}private URL getWebappConfigFileFromDirectory(File docBase, String contextName){URL result = null;File webAppContextXml = new File(docBase, "META-INF/context.xml");if (webAppContextXml.exists()) {try{result = webAppContextXml.toURI().toURL();}catch (MalformedURLException e){Logger.getLogger(getLoggerName(getHost(), contextName)).log(Level.WARNING, "Unable to determine web application context.xml " + docBase, e);}}return result;}private URL getWebappConfigFileFromJar(File docBase, String contextName){URL result = null;try{JarFile jar = new JarFile(docBase);Throwable localThrowable2 = null;try{JarEntry entry = jar.getJarEntry("META-INF/context.xml");if (entry != null) {result = new URL("jar:" + docBase.toURI().toString() + "!/" + "META-INF/context.xml");}}catch (Throwable localThrowable1){localThrowable2 = localThrowable1;throw localThrowable1;}finally{if (jar != null) {if (localThrowable2 != null) {try{jar.close();}catch (Throwable x2){localThrowable2.addSuppressed(x2);}} else {jar.close();}}}}catch (IOException e){Logger.getLogger(getLoggerName(getHost(), contextName)).log(Level.WARNING, "Unable to determine web application context.xml " + docBase, e);}return result;}
}

getServer()方法调用StandardService:

package org.apache.catalina.core;import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import javax.management.ObjectName;
import org.apache.catalina.Container;
import org.apache.catalina.Engine;
import org.apache.catalina.Executor;
import org.apache.catalina.JmxEnabled;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleState;
import org.apache.catalina.Server;
import org.apache.catalina.Service;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.mapper.Mapper;
import org.apache.catalina.mapper.MapperListener;
import org.apache.catalina.util.LifecycleMBeanBase;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.res.StringManager;public class StandardServiceextends LifecycleMBeanBaseimplements Service
{private static final Log log = LogFactory.getLog(StandardService.class);private String name = null;private static final StringManager sm = StringManager.getManager("org.apache.catalina.core");private Server server = null;protected final PropertyChangeSupport support = new PropertyChangeSupport(this);protected Connector[] connectors = new Connector[0];private final Object connectorsLock = new Object();protected final ArrayList<Executor> executors = new ArrayList();@Deprecatedprotected Container container = null;private ClassLoader parentClassLoader = null;protected final Mapper mapper = new Mapper();protected final MapperListener mapperListener = new MapperListener(this.mapper, this);public Mapper getMapper(){return this.mapper;}public Container getContainer(){return this.container;}public void setContainer(Container container){setContainer((Engine)container);}public void setContainer(Engine engine){Container oldContainer = this.container;if ((oldContainer != null) && ((oldContainer instanceof Engine))) {((Engine)oldContainer).setService(null);}this.container = engine;if ((this.container != null) && ((this.container instanceof Engine))) {((Engine)this.container).setService(this);}if ((getState().isAvailable()) && (this.container != null)) {try{this.container.start();}catch (LifecycleException localLifecycleException) {}}if ((getState().isAvailable()) && (oldContainer != null)) {try{oldContainer.stop();}catch (LifecycleException localLifecycleException1) {}}this.support.firePropertyChange("container", oldContainer, this.container);}public String getName(){return this.name;}public void setName(String name){this.name = name;}public Server getServer(){return this.server;}public void setServer(Server server){this.server = server;}public void addConnector(Connector connector){synchronized (this.connectorsLock){connector.setService(this);Connector[] results = new Connector[this.connectors.length + 1];System.arraycopy(this.connectors, 0, results, 0, this.connectors.length);results[this.connectors.length] = connector;this.connectors = results;if (getState().isAvailable()) {try{connector.start();}catch (LifecycleException e){log.error(sm.getString("standardService.connector.startFailed", new Object[] { connector }), e);}}this.support.firePropertyChange("connector", null, connector);}}public ObjectName[] getConnectorNames(){ObjectName[] results = new ObjectName[this.connectors.length];for (int i = 0; i < results.length; i++) {results[i] = this.connectors[i].getObjectName();}return results;}public void addPropertyChangeListener(PropertyChangeListener listener){this.support.addPropertyChangeListener(listener);}public Connector[] findConnectors(){return this.connectors;}public void removeConnector(Connector connector){synchronized (this.connectorsLock){int j = -1;for (int i = 0; i < this.connectors.length; i++) {if (connector == this.connectors[i]){j = i;break;}}if (j < 0) {return;}if (this.connectors[j].getState().isAvailable()) {try{this.connectors[j].stop();}catch (LifecycleException e){log.error(sm.getString("standardService.connector.stopFailed", new Object[] { this.connectors[j] }), e);}}connector.setService(null);int k = 0;Connector[] results = new Connector[this.connectors.length - 1];for (int i = 0; i < this.connectors.length; i++) {if (i != j) {results[(k++)] = this.connectors[i];}}this.connectors = results;this.support.firePropertyChange("connector", connector, null);}}public void removePropertyChangeListener(PropertyChangeListener listener){this.support.removePropertyChangeListener(listener);}public String toString(){StringBuilder sb = new StringBuilder("StandardService[");sb.append(getName());sb.append("]");return sb.toString();}public void addExecutor(Executor ex){synchronized (this.executors){if (!this.executors.contains(ex)){this.executors.add(ex);if (getState().isAvailable()) {try{ex.start();}catch (LifecycleException x){log.error("Executor.start", x);}}}}}public Executor[] findExecutors(){synchronized (this.executors){Executor[] arr = new Executor[this.executors.size()];this.executors.toArray(arr);return arr;}}public Executor getExecutor(String executorName){synchronized (this.executors){for (Executor executor : this.executors) {if (executorName.equals(executor.getName())) {return executor;}}}return null;}public void removeExecutor(Executor ex){synchronized (this.executors){if ((this.executors.remove(ex)) && (getState().isAvailable())) {try{ex.stop();}catch (LifecycleException e){log.error("Executor.stop", e);}}}}protected void startInternal()throws LifecycleException{if (log.isInfoEnabled()) {log.info(sm.getString("standardService.start.name", new Object[] { this.name }));}setState(LifecycleState.STARTING);if (this.container != null) {synchronized (this.container){this.container.start();}}synchronized (this.executors){for (Executor executor : this.executors) {executor.start();}}this.mapperListener.start();synchronized (this.connectorsLock){for (Connector connector : this.connectors) {try{if (connector.getState() != LifecycleState.FAILED) {connector.start();}}catch (Exception e){log.error(sm.getString("standardService.connector.startFailed", new Object[] { connector }), e);}}}}protected void stopInternal()throws LifecycleException{synchronized (this.connectorsLock){for (Connector connector : this.connectors) {try{connector.pause();}catch (Exception e){log.error(sm.getString("standardService.connector.pauseFailed", new Object[] { connector }), e);}}}if (log.isInfoEnabled()) {log.info(sm.getString("standardService.stop.name", new Object[] { this.name }));}setState(LifecycleState.STOPPING);if (this.container != null) {synchronized (this.container){this.container.stop();}}synchronized (this.connectorsLock){for (Connector connector : this.connectors) {if (LifecycleState.STARTED.equals(connector.getState())) {try{connector.stop();}catch (Exception e){log.error(sm.getString("standardService.connector.stopFailed", new Object[] { connector }), e);}}}}if (this.mapperListener.getState() != LifecycleState.INITIALIZED) {this.mapperListener.stop();}synchronized (this.executors){for (Executor executor : this.executors) {executor.stop();}}}protected void initInternal()throws LifecycleException{super.initInternal();if (this.container != null) {this.container.init();}for (Executor executor : findExecutors()){if ((executor instanceof JmxEnabled)) {((JmxEnabled)executor).setDomain(getDomain());}executor.init();}this.mapperListener.init();synchronized (this.connectorsLock){for (Connector connector : this.connectors) {try{connector.init();}catch (Exception e){String message = sm.getString("standardService.connector.initFailed", new Object[] { connector });log.error(message, e);if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) {throw new LifecycleException(message);}}}}}protected void destroyInternal()throws LifecycleException{this.mapperListener.destroy();synchronized (this.connectorsLock){for (Connector connector : this.connectors) {try{connector.destroy();}catch (Exception e){log.error(sm.getString("standardService.connector.destroyFailed", new Object[] { connector }), e);}}}for (Executor executor : findExecutors()) {executor.destroy();}if (this.container != null) {this.container.destroy();}super.destroyInternal();}public ClassLoader getParentClassLoader(){if (this.parentClassLoader != null) {return this.parentClassLoader;}if (this.server != null) {return this.server.getParentClassLoader();}return ClassLoader.getSystemClassLoader();}public void setParentClassLoader(ClassLoader parent){ClassLoader oldParentClassLoader = this.parentClassLoader;this.parentClassLoader = parent;this.support.firePropertyChange("parentClassLoader", oldParentClassLoader, this.parentClassLoader);}protected String getDomainInternal(){String domain = null;Container engine = getContainer();if (engine != null) {domain = engine.getName();}if (domain == null) {domain = getName();}return domain;}public final String getObjectNameKeyProperties(){return "type=Service";}
}

start方法是来自:LifecycleMBeanBase->LifecycleBase

package org.apache.catalina.util;import javax.management.InstanceNotFoundException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.apache.catalina.JmxEnabled;
import org.apache.catalina.LifecycleException;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.modeler.Registry;
import org.apache.tomcat.util.res.StringManager;public abstract class LifecycleMBeanBaseextends LifecycleBaseimplements JmxEnabled
{private static final Log log = LogFactory.getLog(LifecycleMBeanBase.class);private static final StringManager sm = StringManager.getManager("org.apache.catalina.util");private String domain = null;private ObjectName oname = null;protected MBeanServer mserver = null;protected void initInternal()throws LifecycleException{if (this.oname == null){this.mserver = Registry.getRegistry(null, null).getMBeanServer();this.oname = register(this, getObjectNameKeyProperties());}}protected void destroyInternal()throws LifecycleException{unregister(this.oname);}public final void setDomain(String domain){this.domain = domain;}public final String getDomain(){if (this.domain == null) {this.domain = getDomainInternal();}if (this.domain == null) {this.domain = "Catalina";}return this.domain;}protected abstract String getDomainInternal();public final ObjectName getObjectName(){return this.oname;}protected abstract String getObjectNameKeyProperties();protected final ObjectName register(Object obj, String objectNameKeyProperties){StringBuilder name = new StringBuilder(getDomain());name.append(':');name.append(objectNameKeyProperties);ObjectName on = null;try{on = new ObjectName(name.toString());Registry.getRegistry(null, null).registerComponent(obj, on, null);}catch (MalformedObjectNameException e){log.warn(sm.getString("lifecycleMBeanBase.registerFail", new Object[] { obj, name }), e);}catch (Exception e){log.warn(sm.getString("lifecycleMBeanBase.registerFail", new Object[] { obj, name }), e);}return on;}protected final void unregister(ObjectName on){if (on == null) {return;}if (this.mserver == null){log.warn(sm.getString("lifecycleMBeanBase.unregisterNoServer", new Object[] { on }));return;}try{this.mserver.unregisterMBean(on);}catch (MBeanRegistrationException e){log.warn(sm.getString("lifecycleMBeanBase.unregisterFail", new Object[] { on }), e);}catch (InstanceNotFoundException e){log.warn(sm.getString("lifecycleMBeanBase.unregisterFail", new Object[] { on }), e);}}public final void postDeregister() {}public final void postRegister(Boolean registrationDone) {}public final void preDeregister()throws Exception{}public final ObjectName preRegister(MBeanServer server, ObjectName name)throws Exception{this.mserver = server;this.oname = name;this.domain = name.getDomain();return this.oname;}
}
package org.apache.catalina.util;import org.apache.catalina.Lifecycle;
import org.apache.catalina.Lifecycle.SingleUse;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.LifecycleState;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.res.StringManager;public abstract class LifecycleBaseimplements Lifecycle
{private static final Log log = LogFactory.getLog(LifecycleBase.class);private static final StringManager sm = StringManager.getManager("org.apache.catalina.util");private final LifecycleSupport lifecycle = new LifecycleSupport(this);private volatile LifecycleState state = LifecycleState.NEW;public void addLifecycleListener(LifecycleListener listener){this.lifecycle.addLifecycleListener(listener);}public LifecycleListener[] findLifecycleListeners(){return this.lifecycle.findLifecycleListeners();}public void removeLifecycleListener(LifecycleListener listener){this.lifecycle.removeLifecycleListener(listener);}protected void fireLifecycleEvent(String type, Object data){this.lifecycle.fireLifecycleEvent(type, data);}public final synchronized void init()throws LifecycleException{if (!this.state.equals(LifecycleState.NEW)) {invalidTransition("before_init");}setStateInternal(LifecycleState.INITIALIZING, null, false);try{initInternal();}catch (Throwable t){ExceptionUtils.handleThrowable(t);setStateInternal(LifecycleState.FAILED, null, false);throw new LifecycleException(sm.getString("lifecycleBase.initFail", new Object[] { toString() }), t);}setStateInternal(LifecycleState.INITIALIZED, null, false);}protected abstract void initInternal()throws LifecycleException;public final synchronized void start()throws LifecycleException{if ((LifecycleState.STARTING_PREP.equals(this.state)) || (LifecycleState.STARTING.equals(this.state)) || (LifecycleState.STARTED.equals(this.state))){if (log.isDebugEnabled()){Exception e = new LifecycleException();log.debug(sm.getString("lifecycleBase.alreadyStarted", new Object[] { toString() }), e);}else if (log.isInfoEnabled()){log.info(sm.getString("lifecycleBase.alreadyStarted", new Object[] { toString() }));}return;}if (this.state.equals(LifecycleState.NEW)) {init();} else if (this.state.equals(LifecycleState.FAILED)) {stop();} else if ((!this.state.equals(LifecycleState.INITIALIZED)) && (!this.state.equals(LifecycleState.STOPPED))) {invalidTransition("before_start");}setStateInternal(LifecycleState.STARTING_PREP, null, false);try{startInternal();}catch (Throwable t){ExceptionUtils.handleThrowable(t);setStateInternal(LifecycleState.FAILED, null, false);throw new LifecycleException(sm.getString("lifecycleBase.startFail", new Object[] { toString() }), t);}if (this.state.equals(LifecycleState.FAILED)) {stop();} else if (!this.state.equals(LifecycleState.STARTING)) {invalidTransition("after_start");} else {setStateInternal(LifecycleState.STARTED, null, false);}}protected abstract void startInternal()throws LifecycleException;public final synchronized void stop()throws LifecycleException{if ((LifecycleState.STOPPING_PREP.equals(this.state)) || (LifecycleState.STOPPING.equals(this.state)) || (LifecycleState.STOPPED.equals(this.state))){if (log.isDebugEnabled()){Exception e = new LifecycleException();log.debug(sm.getString("lifecycleBase.alreadyStopped", new Object[] { toString() }), e);}else if (log.isInfoEnabled()){log.info(sm.getString("lifecycleBase.alreadyStopped", new Object[] { toString() }));}return;}if (this.state.equals(LifecycleState.NEW)){this.state = LifecycleState.STOPPED;return;}if ((!this.state.equals(LifecycleState.STARTED)) && (!this.state.equals(LifecycleState.FAILED))) {invalidTransition("before_stop");}if (this.state.equals(LifecycleState.FAILED)) {fireLifecycleEvent("before_stop", null);} else {setStateInternal(LifecycleState.STOPPING_PREP, null, false);}try{stopInternal();}catch (Throwable t){ExceptionUtils.handleThrowable(t);setStateInternal(LifecycleState.FAILED, null, false);throw new LifecycleException(sm.getString("lifecycleBase.stopFail", new Object[] { toString() }), t);}finally{if ((this instanceof Lifecycle.SingleUse)){setStateInternal(LifecycleState.STOPPED, null, false);destroy();return;}}if ((!this.state.equals(LifecycleState.STOPPING)) && (!this.state.equals(LifecycleState.FAILED))) {invalidTransition("after_stop");}setStateInternal(LifecycleState.STOPPED, null, false);}protected abstract void stopInternal()throws LifecycleException;public final synchronized void destroy()throws LifecycleException{if (LifecycleState.FAILED.equals(this.state)) {try{stop();}catch (LifecycleException e){log.warn(sm.getString("lifecycleBase.destroyStopFail", new Object[] { toString() }), e);}}if ((LifecycleState.DESTROYING.equals(this.state)) || (LifecycleState.DESTROYED.equals(this.state))){if (log.isDebugEnabled()){Exception e = new LifecycleException();log.debug(sm.getString("lifecycleBase.alreadyDestroyed", new Object[] { toString() }), e);}else if ((log.isInfoEnabled()) && (!(this instanceof Lifecycle.SingleUse))){log.info(sm.getString("lifecycleBase.alreadyDestroyed", new Object[] { toString() }));}return;}if ((!this.state.equals(LifecycleState.STOPPED)) && (!this.state.equals(LifecycleState.FAILED)) && (!this.state.equals(LifecycleState.NEW)) && (!this.state.equals(LifecycleState.INITIALIZED))) {invalidTransition("before_destroy");}setStateInternal(LifecycleState.DESTROYING, null, false);try{destroyInternal();}catch (Throwable t){ExceptionUtils.handleThrowable(t);setStateInternal(LifecycleState.FAILED, null, false);throw new LifecycleException(sm.getString("lifecycleBase.destroyFail", new Object[] { toString() }), t);}setStateInternal(LifecycleState.DESTROYED, null, false);}protected abstract void destroyInternal()throws LifecycleException;public LifecycleState getState(){return this.state;}public String getStateName(){return getState().toString();}protected synchronized void setState(LifecycleState state)throws LifecycleException{setStateInternal(state, null, true);}protected synchronized void setState(LifecycleState state, Object data)throws LifecycleException{setStateInternal(state, data, true);}private synchronized void setStateInternal(LifecycleState state, Object data, boolean check)throws LifecycleException{if (log.isDebugEnabled()) {log.debug(sm.getString("lifecycleBase.setState", new Object[] { this, state }));}if (check){if (state == null){invalidTransition("null");return;}if ((state != LifecycleState.FAILED) && ((this.state != LifecycleState.STARTING_PREP) || (state != LifecycleState.STARTING)) && ((this.state != LifecycleState.STOPPING_PREP) || (state != LifecycleState.STOPPING)) && ((this.state != LifecycleState.FAILED) || (state != LifecycleState.STOPPING))) {invalidTransition(state.name());}}this.state = state;String lifecycleEvent = state.getLifecycleEvent();if (lifecycleEvent != null) {fireLifecycleEvent(lifecycleEvent, data);}}private void invalidTransition(String type)throws LifecycleException{String msg = sm.getString("lifecycleBase.invalidTransition", new Object[] { type, toString(), this.state });throw new LifecycleException(msg);}
}

最终核心调用的方法是startInternal()

protected void startInternal()throws LifecycleException{fireLifecycleEvent("configure_start", null);setState(LifecycleState.STARTING);this.globalNamingResources.start();synchronized (this.servicesLock){for (int i = 0; i < this.services.length; i++) {this.services[i].start();}}}

SonarQube6.2源码解析(三)相关推荐

  1. Disruptor源码解析三 RingBuffer解析

    目录 系列索引 前言 主要内容 RingBuffer的要点 源码解析 系列索引 Disruptor源码解析一 Disruptor高性能之道 Disruptor源码解析二 Sequence相关类解析 D ...

  2. OkHttp3源码解析(三)——连接池复用

    OKHttp3源码解析系列 OkHttp3源码解析(一)之请求流程 OkHttp3源码解析(二)--拦截器链和缓存策略 本文基于OkHttp3的3.11.0版本 implementation 'com ...

  3. ReactiveSwift源码解析(三) Signal代码的基本实现

    上篇博客我们详细的聊了ReactiveSwift源码中的Bag容器,详情请参见<ReactiveSwift源码解析之Bag容器>.本篇博客我们就来聊一下信号量,也就是Signal的的几种状 ...

  4. 并发编程与源码解析 (三)

    并发编程 (三) 1 Fork/Join分解合并框架 1.1 什么是fork/join ​ Fork/Join框架是JDK1.7提供的一个用于并行执行任务的框架,开发者可以在不去了解如Thread.R ...

  5. SonarQube6.2源码解析(一)

    首先看sonar后台的启动进程: [root@uranuspreweb34 logs]# ps -ef | grep java root 3169 3167 0 Apr19 ? 00:06:04 ja ...

  6. 前端入门之(vuex源码解析三)

    上两节前端入门之(vuex源码解析二)我们把vuex的源码大概的撸了一遍,还剩下(插件.getters跟module),我们继续哈~ 插件童鞋们可以去看看vuex在各个浏览器的状态显示插件,小伙伴可以 ...

  7. 拆轮子-RxDownload2源码解析(三)

    本文为博主原创文章,未经允许不得转载 造轮子者:Season_zlc 轮子用法请戳作者链接 ↑ 前言 本文主要讲述 RxDownload2 的多线程断点下载技术. 断点下载技术前提 服务器必须支持按 ...

  8. Tomcat源码解析三:tomcat的启动过程

    Tomcat组件生命周期管理 在Tomcat总体结构 (Tomcat源代码解析之二)中,我们列出了Tomcat中Server,Service,Connector,Engine,Host,Context ...

  9. 【Vue.js源码解析 三】-- 模板编译和组件化

    前言 笔记来源:拉勾教育 大前端高薪训练营 阅读建议:建议通过左侧导航栏进行阅读 模板编译 模板编译的主要目的是将模板 (template) 转换为渲染函数 (render) <div> ...

  10. Cesium源码解析三(metadata元数据拓展中行列号的分块规则解析)

    目录 1.前言 2.layer.json中available参数意义 3.EPSG:4626切片及terrain分块原理 4.Cesium的terrain分块规则 5.自定义terrain分块规则 6 ...

最新文章

  1. Valid Sudoku leetcode java
  2. python切片语法-Python切片符号(:)用法及示例
  3. win10+anaconda+cuda配置dlib,使用GPU对dlib的深度学习算法进行加速(以人脸检测为例)...
  4. httpRuntime 一点经验---引
  5. pythoncsv格式列变换_用Python将csv行转换为列
  6. 这个黑科技耳机方便又时尚,听歌也不怕坐过
  7. 作为刚開始学习的人应该怎样来学习FPGA
  8. Codeforce C. Bus
  9. 局部线性嵌入(LLE,Locally Linear Embedding)
  10. 工资的流水与真金、显性物价与隐性物价的名词说明
  11. 已经编译好的OpenCV4.5.1----win10(cuda10.0 cudnn7.6.5)
  12. 有机食品农产品电商网站HTML模板
  13. CheckException和UnCheckException的区别
  14. Redis高可用群集——主从复制+哨兵模式
  15. Linux scp命令复制文件报错: not a regular file
  16. oracle-DDL对表的操作
  17. 硬件使用74hc138的C语言程序,【Arduino教程】第三十一讲:74HC138实验
  18. c语言int型是什么意思,在c语言中,int代表什么意思
  19. 艾永亮:以超级产品战略的角度,写一份竞品分析
  20. nginx+https+自签名+各种云dns解析+浏览器安全可用include相对路径和绝对路径

热门文章

  1. App.vue文件報錯
  2. xfce的开始菜单增加搜索框
  3. 根据数据集获取概率密度图像和概率分布图像
  4. python必须使用try except而不是if else的场合
  5. 什么是OLAP和OLTP
  6. common.php下载,插件common.php全局函数文件
  7. python自动抠头像图_Python实现AI自动抠图实例解析
  8. ps命令---Linux学习笔记
  9. 企业门户项目实施方法论(IPS方法简介),适用于企业门户项目的项目管理方法论(上篇)...
  10. SpringBoot基础篇Bean之条件注入之注解使用