Skip to content

Instantly share code, notes, and snippets.

@alxfv
Created September 15, 2014 13:51
Show Gist options
  • Save alxfv/85c30a7fa62b56150597 to your computer and use it in GitHub Desktop.
Save alxfv/85c30a7fa62b56150597 to your computer and use it in GitHub Desktop.
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.boot;
import java.lang.reflect.Constructor;
import java.nio.charset.Charset;
import java.security.AccessControlException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.boot.Banner;
import org.springframework.boot.BeanDefinitionLoader;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.boot.StartupInfoLogger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.GenericTypeResolver;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.SimpleCommandLinePropertySource;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.SpringFactoriesLoader;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StopWatch;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.StandardServletEnvironment;
public class SpringApplication {
private static final String DEFAULT_CONTEXT_CLASS = "org.springframework.context.annotation.AnnotationConfigApplicationContext";
public static final String DEFAULT_WEB_CONTEXT_CLASS = "org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext";
private static final String[] WEB_ENVIRONMENT_CLASSES = new String[]{"javax.servlet.Servlet", "org.springframework.web.context.ConfigurableWebApplicationContext"};
private static final String SYSTEM_PROPERTY_JAVA_AWT_HEADLESS = "java.awt.headless";
private final Log log = LogFactory.getLog(this.getClass());
private final Set<Object> sources = new LinkedHashSet();
private Class<?> mainApplicationClass;
private boolean showBanner = true;
private boolean logStartupInfo = true;
private boolean addCommandLineProperties = true;
private ResourceLoader resourceLoader;
private BeanNameGenerator beanNameGenerator;
private ConfigurableEnvironment environment;
private Class<? extends ConfigurableApplicationContext> applicationContextClass;
private boolean webEnvironment;
private boolean headless = true;
private boolean registerShutdownHook = true;
private List<ApplicationContextInitializer<?>> initializers;
private List<ApplicationListener<?>> listeners;
private Map<String, Object> defaultProperties;
private Set<String> profiles = new HashSet();
public SpringApplication(Object ... sources) {
this.initialize(sources);
}
public SpringApplication(ResourceLoader resourceLoader, Object ... sources) {
this.resourceLoader = resourceLoader;
this.initialize(sources);
}
private void initialize(Object[] sources) {
if(sources != null && sources.length > 0) {
this.sources.addAll(Arrays.asList(sources));
}
this.webEnvironment = this.deduceWebEnvironment();
this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = this.deduceMainApplicationClass();
}
private boolean deduceWebEnvironment() {
String[] arr$ = WEB_ENVIRONMENT_CLASSES;
int len$ = arr$.length;
for(int i$ = 0; i$ < len$; ++i$) {
String className = arr$[i$];
if(!ClassUtils.isPresent(className, (ClassLoader)null)) {
return false;
}
}
return true;
}
private Class<?> deduceMainApplicationClass() {
try {
StackTraceElement[] ex = (new RuntimeException()).getStackTrace();
StackTraceElement[] arr$ = ex;
int len$ = ex.length;
for(int i$ = 0; i$ < len$; ++i$) {
StackTraceElement stackTraceElement = arr$[i$];
if("main".equals(stackTraceElement.getMethodName())) {
return Class.forName(stackTraceElement.getClassName());
}
}
} catch (ClassNotFoundException var6) {
;
}
return null;
}
public ConfigurableApplicationContext run(String ... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
System.setProperty("java.awt.headless", System.getProperty("java.awt.headless", Boolean.toString(this.headless)));
Collection runListeners = this.getRunListeners(args);
Iterator ex = runListeners.iterator();
while(ex.hasNext()) {
SpringApplicationRunListener i$ = (SpringApplicationRunListener)ex.next();
i$.started();
}
SpringApplicationRunListener runListener;
Iterator i$1;
try {
ConfigurableEnvironment ex2 = this.getOrCreateEnvironment();
this.configureEnvironment(ex2, args);
i$1 = runListeners.iterator();
while(i$1.hasNext()) {
runListener = (SpringApplicationRunListener)i$1.next();
runListener.environmentPrepared(ex2);
}
if(this.showBanner) {
this.printBanner(ex2);
}
context = this.createApplicationContext();
if(this.registerShutdownHook) {
try {
context.registerShutdownHook();
} catch (AccessControlException var13) {
;
}
}
context.setEnvironment(ex2);
this.postProcessApplicationContext(context);
this.applyInitializers(context);
i$1 = runListeners.iterator();
while(i$1.hasNext()) {
runListener = (SpringApplicationRunListener)i$1.next();
runListener.contextPrepared(context);
}
if(this.logStartupInfo) {
this.logStartupInfo(context.getParent() == null);
}
Set i$2 = this.getSources();
Assert.notEmpty(i$2, "Sources must not be empty");
this.load(context, i$2.toArray(new Object[i$2.size()]));
Iterator runListener2 = runListeners.iterator();
SpringApplicationRunListener runListener1;
while(runListener2.hasNext()) {
runListener1 = (SpringApplicationRunListener)runListener2.next();
runListener1.contextLoaded(context);
}
this.refresh(context);
this.afterRefresh(context, args);
runListener2 = runListeners.iterator();
while(runListener2.hasNext()) {
runListener1 = (SpringApplicationRunListener)runListener2.next();
runListener1.finished(context, (Throwable)null);
}
stopWatch.stop();
if(this.logStartupInfo) {
(new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
}
return context;
} catch (Exception var15) {
Exception ex1 = var15;
try {
i$1 = runListeners.iterator();
while(true) {
if(!i$1.hasNext()) {
this.log.error("Application startup failed", ex1);
break;
}
runListener = (SpringApplicationRunListener)i$1.next();
this.finishWithException(runListener, context, ex1);
}
} finally {
if(context != null) {
context.close();
}
}
ReflectionUtils.rethrowRuntimeException(ex1);
return context;
}
}
private Collection<SpringApplicationRunListener> getRunListeners(String[] args) {
ArrayList listeners = new ArrayList();
listeners.addAll(this.getSpringFactoriesInstances(SpringApplicationRunListener.class, new Class[]{SpringApplication.class, String[].class}, new Object[]{this, args}));
return listeners;
}
private <T> Collection<? extends T> getSpringFactoriesInstances(Class<T> type) {
return this.getSpringFactoriesInstances(type, new Class[0], new Object[0]);
}
private <T> Collection<? extends T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object ... args) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
LinkedHashSet names = new LinkedHashSet(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
ArrayList instances = new ArrayList(names.size());
Iterator i$ = names.iterator();
while(i$.hasNext()) {
String name = (String)i$.next();
try {
Class ex = ClassUtils.forName(name, classLoader);
Assert.isAssignable(type, ex);
Constructor constructor = ex.getConstructor(parameterTypes);
Object instance = constructor.newInstance(args);
instances.add(instance);
} catch (Throwable var12) {
throw new IllegalArgumentException("Cannot instantiate " + type + " : " + name, var12);
}
}
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
private ConfigurableEnvironment getOrCreateEnvironment() {
return (ConfigurableEnvironment)(this.environment != null?this.environment:(this.webEnvironment?new StandardServletEnvironment():new StandardEnvironment()));
}
protected void configureEnvironment(ConfigurableEnvironment environment, String[] args) {
this.configurePropertySources(environment, args);
this.configureProfiles(environment, args);
}
protected void configurePropertySources(ConfigurableEnvironment environment, String[] args) {
MutablePropertySources sources = environment.getPropertySources();
if(this.defaultProperties != null && !this.defaultProperties.isEmpty()) {
sources.addLast(new MapPropertySource("defaultProperties", this.defaultProperties));
}
if(this.addCommandLineProperties && args.length > 0) {
String name = "commandLineArgs";
if(sources.contains(name)) {
PropertySource source = sources.get(name);
CompositePropertySource composite = new CompositePropertySource(name);
composite.addPropertySource(new SimpleCommandLinePropertySource(name + "-" + args.hashCode(), args));
composite.addPropertySource(source);
sources.replace(name, composite);
} else {
sources.addFirst(new SimpleCommandLinePropertySource(args));
}
}
}
protected void configureProfiles(ConfigurableEnvironment environment, String[] args) {
LinkedHashSet profiles = new LinkedHashSet();
environment.getActiveProfiles();
Iterator i$ = this.profiles.iterator();
while(i$.hasNext()) {
String profile = (String)i$.next();
profiles.add(profile);
}
profiles.addAll(Arrays.asList(environment.getActiveProfiles()));
environment.setActiveProfiles((String[])profiles.toArray(new String[profiles.size()]));
}
protected void printBanner(Environment environment) {
String location = environment.getProperty("banner.location", "banner.txt");
Object resourceLoader = this.resourceLoader != null?this.resourceLoader:new DefaultResourceLoader(this.getClassLoader());
Resource resource = ((ResourceLoader)resourceLoader).getResource(location);
if(resource.exists()) {
try {
String ex = StreamUtils.copyToString(resource.getInputStream(), (Charset)environment.getProperty("banner.charset", Charset.class, Charset.forName("UTF-8")));
System.out.println(environment.resolvePlaceholders(ex));
return;
} catch (Exception var6) {
this.log.warn("Banner not printable: " + resource + " (" + var6.getClass() + ": \'" + var6.getMessage() + "\')", var6);
}
}
this.printBanner();
}
protected void printBanner() {
Banner.write(System.out);
}
protected ConfigurableApplicationContext createApplicationContext() {
Class contextClass = this.applicationContextClass;
if(contextClass == null) {
try {
contextClass = Class.forName(this.webEnvironment?"org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext":"org.springframework.context.annotation.AnnotationConfigApplicationContext");
} catch (ClassNotFoundException var3) {
throw new IllegalStateException("Unable create a default ApplicationContext, please specify an ApplicationContextClass", var3);
}
}
return (ConfigurableApplicationContext)BeanUtils.instantiate(contextClass);
}
protected void postProcessApplicationContext(ConfigurableApplicationContext context) {
if(this.webEnvironment && context instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext configurableContext = (ConfigurableWebApplicationContext)context;
if(this.beanNameGenerator != null) {
configurableContext.getBeanFactory().registerSingleton("org.springframework.context.annotation.internalConfigurationBeanNameGenerator", this.beanNameGenerator);
}
}
if(this.resourceLoader != null) {
if(context instanceof GenericApplicationContext) {
((GenericApplicationContext)context).setResourceLoader(this.resourceLoader);
}
if(context instanceof DefaultResourceLoader) {
((DefaultResourceLoader)context).setClassLoader(this.resourceLoader.getClassLoader());
}
}
}
protected void applyInitializers(ConfigurableApplicationContext context) {
Iterator i$ = this.getInitializers().iterator();
while(i$.hasNext()) {
ApplicationContextInitializer initializer = (ApplicationContextInitializer)i$.next();
Class requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(), ApplicationContextInitializer.class);
Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
initializer.initialize(context);
}
}
protected void logStartupInfo(boolean isRoot) {
if(isRoot) {
(new StartupInfoLogger(this.mainApplicationClass)).logStarting(this.getApplicationLog());
}
}
protected Log getApplicationLog() {
return this.mainApplicationClass == null?this.log:LogFactory.getLog(this.mainApplicationClass);
}
protected void load(ApplicationContext context, Object[] sources) {
if(this.log.isDebugEnabled()) {
this.log.debug("Loading source " + StringUtils.arrayToCommaDelimitedString(sources));
}
BeanDefinitionLoader loader = this.createBeanDefinitionLoader(this.getBeanDefinitionRegistry(context), sources);
if(this.beanNameGenerator != null) {
loader.setBeanNameGenerator(this.beanNameGenerator);
}
if(this.resourceLoader != null) {
loader.setResourceLoader(this.resourceLoader);
}
if(this.environment != null) {
loader.setEnvironment(this.environment);
}
loader.load();
}
public ResourceLoader getResourceLoader() {
return this.resourceLoader;
}
public ClassLoader getClassLoader() {
return this.resourceLoader != null?this.resourceLoader.getClassLoader():ClassUtils.getDefaultClassLoader();
}
private BeanDefinitionRegistry getBeanDefinitionRegistry(ApplicationContext context) {
if(context instanceof BeanDefinitionRegistry) {
return (BeanDefinitionRegistry)context;
} else if(context instanceof AbstractApplicationContext) {
return (BeanDefinitionRegistry)((AbstractApplicationContext)context).getBeanFactory();
} else {
throw new IllegalStateException("Could not locate BeanDefinitionRegistry");
}
}
protected BeanDefinitionLoader createBeanDefinitionLoader(BeanDefinitionRegistry registry, Object[] sources) {
return new BeanDefinitionLoader(registry, sources);
}
private void runCommandLineRunners(ApplicationContext context, String ... args) {
ArrayList runners = new ArrayList(context.getBeansOfType(CommandLineRunner.class).values());
AnnotationAwareOrderComparator.sort(runners);
Iterator i$ = runners.iterator();
while(i$.hasNext()) {
CommandLineRunner runner = (CommandLineRunner)i$.next();
try {
runner.run(args);
} catch (Exception var7) {
throw new IllegalStateException("Failed to execute CommandLineRunner", var7);
}
}
}
protected void refresh(ApplicationContext applicationContext) {
Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
((AbstractApplicationContext)applicationContext).refresh();
}
protected void afterRefresh(ConfigurableApplicationContext context, String[] args) {
this.runCommandLineRunners(context, args);
}
private void finishWithException(SpringApplicationRunListener runListener, ConfigurableApplicationContext context, Exception exception) {
try {
runListener.finished(context, exception);
} catch (Exception var6) {
if(this.log.isDebugEnabled()) {
this.log.error("Error handling failed", var6);
} else {
String message = var6.getMessage();
message = message == null?"no error message":message;
this.log.warn("Error handling failed (" + message + ")");
}
}
}
public void setMainApplicationClass(Class<?> mainApplicationClass) {
this.mainApplicationClass = mainApplicationClass;
}
public void setWebEnvironment(boolean webEnvironment) {
this.webEnvironment = webEnvironment;
}
public void setHeadless(boolean headless) {
this.headless = headless;
}
public void setRegisterShutdownHook(boolean registerShutdownHook) {
this.registerShutdownHook = registerShutdownHook;
}
public void setShowBanner(boolean showBanner) {
this.showBanner = showBanner;
}
public void setLogStartupInfo(boolean logStartupInfo) {
this.logStartupInfo = logStartupInfo;
}
public void setAddCommandLineProperties(boolean addCommandLineProperties) {
this.addCommandLineProperties = addCommandLineProperties;
}
public void setDefaultProperties(Map<String, Object> defaultProperties) {
this.defaultProperties = defaultProperties;
}
public void setDefaultProperties(Properties defaultProperties) {
this.defaultProperties = new HashMap();
Iterator i$ = Collections.list(defaultProperties.propertyNames()).iterator();
while(i$.hasNext()) {
Object key = i$.next();
this.defaultProperties.put((String)key, defaultProperties.get(key));
}
}
public void setAdditionalProfiles(String ... profiles) {
this.profiles = new LinkedHashSet(Arrays.asList(profiles));
}
public void setBeanNameGenerator(BeanNameGenerator beanNameGenerator) {
this.beanNameGenerator = beanNameGenerator;
}
public void setEnvironment(ConfigurableEnvironment environment) {
this.environment = environment;
}
public Set<Object> getSources() {
return this.sources;
}
public void setSources(Set<Object> sources) {
Assert.notNull(sources, "Sources must not be null");
this.sources.addAll(sources);
}
public void setResourceLoader(ResourceLoader resourceLoader) {
Assert.notNull(resourceLoader, "ResourceLoader must not be null");
this.resourceLoader = resourceLoader;
}
public void setApplicationContextClass(Class<? extends ConfigurableApplicationContext> applicationContextClass) {
this.applicationContextClass = applicationContextClass;
if(!WebApplicationContext.class.isAssignableFrom(applicationContextClass)) {
this.webEnvironment = false;
}
}
public void setInitializers(Collection<? extends ApplicationContextInitializer<?>> initializers) {
this.initializers = new ArrayList();
this.initializers.addAll(initializers);
}
public void addInitializers(ApplicationContextInitializer<?> ... initializers) {
this.initializers.addAll(Arrays.asList(initializers));
}
public Set<ApplicationContextInitializer<?>> getInitializers() {
return asUnmodifiableOrderedSet(this.initializers);
}
public void setListeners(Collection<? extends ApplicationListener<?>> listeners) {
this.listeners = new ArrayList();
this.listeners.addAll(listeners);
}
public void addListeners(ApplicationListener<?> ... listeners) {
this.listeners.addAll(Arrays.asList(listeners));
}
public Set<ApplicationListener<?>> getListeners() {
return asUnmodifiableOrderedSet(this.listeners);
}
public static ConfigurableApplicationContext run(Object source, String ... args) {
return run((Object[])(new Object[]{source}), args);
}
public static ConfigurableApplicationContext run(Object[] sources, String[] args) {
return (new SpringApplication(sources)).run(args);
}
public static void main(String[] args) throws Exception {
run((Object[])(new Object[0]), args);
}
public static int exit(ApplicationContext context, ExitCodeGenerator ... exitCodeGenerators) {
byte exitCode = 0;
int exitCode1;
try {
try {
ArrayList ex = new ArrayList();
ex.addAll(Arrays.asList(exitCodeGenerators));
ex.addAll(context.getBeansOfType(ExitCodeGenerator.class).values());
exitCode1 = getExitCode(ex);
} finally {
close(context);
}
} catch (Exception var8) {
var8.printStackTrace();
exitCode1 = exitCode == 0?1:exitCode;
}
return exitCode1;
}
private static int getExitCode(List<ExitCodeGenerator> exitCodeGenerators) {
int exitCode = 0;
Iterator i$ = exitCodeGenerators.iterator();
while(i$.hasNext()) {
ExitCodeGenerator exitCodeGenerator = (ExitCodeGenerator)i$.next();
try {
int ex = exitCodeGenerator.getExitCode();
if(ex > 0 && ex > exitCode || ex < 0 && ex < exitCode) {
exitCode = ex;
}
} catch (Exception var5) {
exitCode = exitCode == 0?1:exitCode;
var5.printStackTrace();
}
}
return exitCode;
}
private static void close(ApplicationContext context) {
if(context instanceof ConfigurableApplicationContext) {
ConfigurableApplicationContext closable = (ConfigurableApplicationContext)context;
closable.close();
}
}
private static <E> Set<E> asUnmodifiableOrderedSet(Collection<E> elements) {
ArrayList list = new ArrayList();
list.addAll(elements);
Collections.sort(list, AnnotationAwareOrderComparator.INSTANCE);
return new LinkedHashSet(list);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment