springcloud支持外嵌tomcat且支持zookeeper注册与发现

来源:互联网 发布:js构造函数的使用实例 编辑:程序博客网 时间:2024/05/18 13:46
package com.pa.springcloud;


import java.util.Collections;
import java.util.HashSet;
import java.util.Set;


import javax.servlet.ServletContext;
import javax.servlet.ServletException;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.StandardServletEnvironment;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;


import com.pa.openapi.gateway.core.ApplicationContextInitializerImpl;
import com.pa.openapi.gateway.core.CustomAnnotationConfigEmbeddedWebApplicationContext;


@EnableWebMvc
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class,
JpaRepositoriesAutoConfiguration.class })
@EnableDiscoveryClient
//@ImportResource("classpath*:applicationContext.xml")
public class SpringBootApplications extends SpringApplication
implements  WebApplicationInitializer {



public static final String CONTEXT_INITIALIZER_CLASSES_PARAM = "contextInitializerClasses";
public static final String CONTEXT_CLASS_PARAM = "contextClass";
private static final Set<String> SERVLET_ENVIRONMENT_SOURCE_NAMES;



static {
Set<String> names = new HashSet<String>();
names.add(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME);
names.add(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME);
names.add(StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME);
SERVLET_ENVIRONMENT_SOURCE_NAMES = Collections.unmodifiableSet(names);
}


@Override
public void onStartup(ServletContext servletContext) throws ServletException {

try {

String clazzName = ApplicationContextInitializerImpl.class.getName();
String className = servletContext.getInitParameter(CONTEXT_INITIALIZER_CLASSES_PARAM);
if (className != null && className != "") {
className = className + "," + clazzName;
} else {
className = clazzName;
}
servletContext.setInitParameter(CONTEXT_INITIALIZER_CLASSES_PARAM, className);

servletContext.setInitParameter(CONTEXT_CLASS_PARAM, CustomAnnotationConfigEmbeddedWebApplicationContext.class.getName());

} catch (Throwable ex) {
throw new IllegalStateException(ex);
}


}
//
// public static void main(String[] args) {
// System.out.println("*********************Application***************************************");
// SpringApplication.run(SpringBootApplications.class, args);
//
// }

}


package com.pa.openapi.gateway.core;


import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
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.BeanNameGenerator;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.Banner;
import org.springframework.boot.Banner.Mode;
import org.springframework.boot.DefaultApplicationArguments;
import org.springframework.boot.ExitCodeEvent;
import org.springframework.boot.ExitCodeExceptionMapper;
import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.diagnostics.FailureAnalyzers;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigUtils;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.GenericTypeResolver;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.env.CommandLinePropertySource;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
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.ResourceLoader;
import org.springframework.core.io.support.SpringFactoriesLoader;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.StandardServletEnvironment;




public class ApplicationContextInitializerImpl extends SpringApplication implements ApplicationContextInitializer {


private static final Log logger = LogFactory.getLog(ApplicationContextInitializerImpl.class);
private boolean webEnvironment;
private static final String CONFIGURABLE_WEB_ENVIRONMENT_CLASS = "org.springframework.web.context.ConfigurableWebEnvironment";
private ResourceLoader resourceLoader;
private static final String[] WEB_ENVIRONMENT_CLASSES = { "javax.servlet.Servlet",
"org.springframework.web.context.ConfigurableWebApplicationContext" };
private ConfigurableEnvironment environment;
private Map<String, Object> defaultProperties;
private boolean addCommandLineProperties = true;
private Set<String> additionalProfiles = new HashSet<String>();
private Banner.Mode bannerMode = Banner.Mode.CONSOLE;
private Banner banner;
private final Set<Object> sources = new LinkedHashSet<Object>();
private boolean logStartupInfo = true;
private BeanNameGenerator beanNameGenerator;
private List<ApplicationContextInitializer<?>> initializers;
private Class<?> mainApplicationClass;
public static final String CONTEXT_INITIALIZER_CLASSES_PARAM = "contextInitializerClasses";

private static final Set<String> SERVLET_ENVIRONMENT_SOURCE_NAMES;


static {
Set<String> names = new HashSet<String>();
names.add(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME);
names.add(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME);
names.add(StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME);
SERVLET_ENVIRONMENT_SOURCE_NAMES = Collections.unmodifiableSet(names);
}

@SuppressWarnings({ "unchecked", "rawtypes" })
private void initialize(Object[] sources) {
if (sources != null && sources.length > 0) {
this.sources.addAll(Arrays.asList(sources));
}
this.webEnvironment = deduceWebEnvironment();
setInitializers((Collection) getSpringFactoriesInstances(
ApplicationContextInitializer.class));
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = deduceMainApplicationClass();
}

private boolean deduceWebEnvironment() {
for (String className : WEB_ENVIRONMENT_CLASSES) {
if (!ClassUtils.isPresent(className, null)) {
return false;
}
}
return true;
}

private Class<?> deduceMainApplicationClass() {
try {
StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
for (StackTraceElement stackTraceElement : stackTrace) {
if ("main".equals(stackTraceElement.getMethodName())) {
return Class.forName(stackTraceElement.getClassName());
}
}
}
catch (ClassNotFoundException ex) {
// Swallow and continue
}
return null;
}


public void setInitializers(
Collection<? extends ApplicationContextInitializer<?>> initializers) {
this.initializers = new ArrayList<ApplicationContextInitializer<?>>();
this.initializers.addAll(initializers);
super.setInitializers(initializers);
}


@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
String[] args = new String[] {};
ConfigurableApplicationContext context = null;
FailureAnalyzers analyzers = null;
//SpringApplicationRunListeners listeners = null;
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
Banner printedBanner = printBanner(environment);

context = applicationContext;
analyzers = new FailureAnalyzers(context);
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);

}catch(Throwable ex) {
handleRunFailure(context, listeners, analyzers, ex);
throw new IllegalStateException(ex);
}
}

public ConfigurableApplicationContext run(String... args) {
ConfigurableApplicationContext context = null;
return context;
}



protected SpringApplicationBuilder createSpringApplicationBuilder() {
return new SpringApplicationBuilder();
}

private void prepareContext(ConfigurableApplicationContext context,
ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
ApplicationArguments applicationArguments, Banner printedBanner) {
context.setEnvironment(environment);
postProcessApplicationContext(context);
applyInitializers(context);
listeners.contextPrepared(context);
if (this.logStartupInfo) {
logStartupInfo(context.getParent() == null);
logStartupProfileInfo(context);
}


// Add boot specific singleton beans
/*context.getBeanFactory().registerSingleton("springApplicationArguments",
applicationArguments);
if (printedBanner != null) {
context.getBeanFactory().registerSingleton("springBootBanner", printedBanner);
}*/


// Load the sources
/*Set<Object> sources = getSources();
Assert.notEmpty(sources, "Sources must not be empty");
load(context, sources.toArray(new Object[sources.size()]));*/
listeners.contextLoaded(context);
}

/*protected void load(ApplicationContext context, Object[] sources) {
if (logger.isDebugEnabled()) {
logger.debug(
"Loading source " + StringUtils.arrayToCommaDelimitedString(sources));
}
BeanDefinitionLoader loader = createBeanDefinitionLoader(
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();
}


protected BeanDefinitionLoader createBeanDefinitionLoader(
BeanDefinitionRegistry registry, Object[] sources) {
return new BeanDefinitionLoader(registry, sources);
}

private BeanDefinitionRegistry getBeanDefinitionRegistry(ApplicationContext context) {
if (context instanceof BeanDefinitionRegistry) {
return (BeanDefinitionRegistry) context;
}
if (context instanceof AbstractApplicationContext) {
return (BeanDefinitionRegistry) ((AbstractApplicationContext) context)
.getBeanFactory();
}
throw new IllegalStateException("Could not locate BeanDefinitionRegistry");
}

public Set<Object> getSources() {
return this.sources;
}*/

protected void logStartupProfileInfo(ConfigurableApplicationContext context) {
Log log = getApplicationLog();
if (log.isInfoEnabled()) {
String[] activeProfiles = context.getEnvironment().getActiveProfiles();
if (ObjectUtils.isEmpty(activeProfiles)) {
String[] defaultProfiles = context.getEnvironment().getDefaultProfiles();
log.info("No active profile set, falling back to default profiles: "
+ StringUtils.arrayToCommaDelimitedString(defaultProfiles));
}
else {
log.info("The following profiles are active: "
+ StringUtils.arrayToCommaDelimitedString(activeProfiles));
}
}
}

protected Log getApplicationLog() {
if (this.mainApplicationClass == null) {
return logger;
}
return LogFactory.getLog(this.mainApplicationClass);
}

protected void postProcessApplicationContext(ConfigurableApplicationContext context) {
if (this.beanNameGenerator != null) {
context.getBeanFactory().registerSingleton(
AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR,
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());
}
}
}

@SuppressWarnings({ "rawtypes", "unchecked" })
protected void applyInitializers(ConfigurableApplicationContext context) {
for (ApplicationContextInitializer initializer : getInitializers()) {
Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(
initializer.getClass(), ApplicationContextInitializer.class);
Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
initializer.initialize(context);
}
}

public Set<ApplicationContextInitializer<?>> getInitializers() {
return asUnmodifiableOrderedSet(this.initializers);
}

private static <E> Set<E> asUnmodifiableOrderedSet(Collection<E> elements) {
List<E> list = new ArrayList<E>();
list.addAll(elements);
Collections.sort(list, AnnotationAwareOrderComparator.INSTANCE);
return new LinkedHashSet<E>(list);
}

protected void logStartupInfo(boolean isRoot) {
if (isRoot) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarting(getApplicationLog());
}
}


private Banner printBanner(ConfigurableEnvironment environment) {
if (this.bannerMode == Banner.Mode.OFF) {
return null;
}
ResourceLoader resourceLoader = this.resourceLoader != null ? this.resourceLoader
: new DefaultResourceLoader(getClassLoader());
SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter(
resourceLoader, this.banner);
if (this.bannerMode == Mode.LOG) {
return bannerPrinter.print(environment, this.mainApplicationClass, logger);
}
return bannerPrinter.print(environment, this.mainApplicationClass, System.out);
}

private void handleRunFailure(ConfigurableApplicationContext context,
SpringApplicationRunListeners listeners, FailureAnalyzers analyzers,
Throwable exception) {
try {
try {
handleExitCode(context, exception);
listeners.finished(context, exception);
}
finally {
reportFailure(analyzers, exception);
if (context != null) {
context.close();
}
}
}
catch (Exception ex) {
logger.warn("Unable to close ApplicationContext", ex);
}
ReflectionUtils.rethrowRuntimeException(exception);
}

private void handleExitCode(ConfigurableApplicationContext context,
Throwable exception) {
int exitCode = getExitCodeFromException(context, exception);
if (exitCode != 0) {
if (context != null) {
context.publishEvent(new ExitCodeEvent(context, exitCode));
}
SpringBootExceptionHandler handler = getSpringBootExceptionHandler();
if (handler != null) {
handler.registerExitCode(exitCode);
}
}
}

private int getExitCodeFromException(ConfigurableApplicationContext context,
Throwable exception) {
int exitCode = getExitCodeFromMappedException(context, exception);
if (exitCode == 0) {
exitCode = getExitCodeFromExitCodeGeneratorException(exception);
}
return exitCode;
}

private int getExitCodeFromMappedException(ConfigurableApplicationContext context,
Throwable exception) {
if (context == null || !context.isActive()) {
return 0;
}
ExitCodeGenerators generators = new ExitCodeGenerators();
Collection<ExitCodeExceptionMapper> beans = context
.getBeansOfType(ExitCodeExceptionMapper.class).values();
generators.addAll(exception, beans);
return generators.getExitCode();
}


private int getExitCodeFromExitCodeGeneratorException(Throwable exception) {
if (exception == null) {
return 0;
}
if (exception instanceof ExitCodeGenerator) {
return ((ExitCodeGenerator) exception).getExitCode();
}
return getExitCodeFromExitCodeGeneratorException(exception.getCause());
}

private void reportFailure(FailureAnalyzers analyzers, Throwable failure) {
try {
if (analyzers != null && analyzers.analyzeAndReport(failure)) {
registerLoggedException(failure);
return;
}
}
catch (Throwable ex) {
// Continue with normal handling of the original failure
}
if (logger.isErrorEnabled()) {
logger.error("Application startup failed", failure);
registerLoggedException(failure);
}
}

protected void registerLoggedException(Throwable exception) {
SpringBootExceptionHandler handler = getSpringBootExceptionHandler();
if (handler != null) {
handler.registerLoggedException(exception);
}
}

SpringBootExceptionHandler getSpringBootExceptionHandler() {
if (isMainThread(Thread.currentThread())) {
return SpringBootExceptionHandler.forCurrentThread();
}
return null;
}

private boolean isMainThread(Thread currentThread) {
return ("main".equals(currentThread.getName())
|| "restartedMain".equals(currentThread.getName()))
&& "main".equals(currentThread.getThreadGroup().getName());
}



private ConfigurableEnvironment prepareEnvironment(
SpringApplicationRunListeners listeners,
ApplicationArguments applicationArguments) {
// Create and configure the environment
ConfigurableEnvironment environment = getOrCreateEnvironment();
configureEnvironment(environment, applicationArguments.getSourceArgs());
listeners.environmentPrepared(environment);
if (isWebEnvironment(environment) && !this.webEnvironment) {
environment = convertToStandardEnvironment(environment);
}
return environment;
}


private boolean isWebEnvironment(ConfigurableEnvironment environment) {
try {
Class<?> webEnvironmentClass = ClassUtils
.forName(CONFIGURABLE_WEB_ENVIRONMENT_CLASS, getClassLoader());
return (webEnvironmentClass.isInstance(environment));
}
catch (Throwable ex) {
return false;
}
}

public ClassLoader getClassLoader() {
if (this.resourceLoader != null) {
return this.resourceLoader.getClassLoader();
}
return ClassUtils.getDefaultClassLoader();
}

private ConfigurableEnvironment convertToStandardEnvironment(
ConfigurableEnvironment environment) {
StandardEnvironment result = new StandardEnvironment();
removeAllPropertySources(result.getPropertySources());
result.setActiveProfiles(environment.getActiveProfiles());
for (PropertySource<?> propertySource : environment.getPropertySources()) {
if (!SERVLET_ENVIRONMENT_SOURCE_NAMES.contains(propertySource.getName())) {
result.getPropertySources().addLast(propertySource);
}
}
return result;
}
private void removeAllPropertySources(MutablePropertySources propertySources) {
Set<String> names = new HashSet<String>();
for (PropertySource<?> propertySource : propertySources) {
names.add(propertySource.getName());
}
for (String name : names) {
propertySources.remove(name);
}
}

private ConfigurableEnvironment getOrCreateEnvironment() {
if (this.environment != null) {
return this.environment;
}
if (this.webEnvironment) {
return new StandardServletEnvironment();
}
return new StandardEnvironment();
}

protected void configureEnvironment(ConfigurableEnvironment environment,
String[] args) {
configurePropertySources(environment, args);
configureProfiles(environment, args);
}

protected void configureProfiles(ConfigurableEnvironment environment, String[] args) {
environment.getActiveProfiles(); // ensure they are initialized
// But these ones should go first (last wins in a property key clash)
Set<String> profiles = new LinkedHashSet<String>(this.additionalProfiles);
profiles.addAll(Arrays.asList(environment.getActiveProfiles()));
environment.setActiveProfiles(profiles.toArray(new String[profiles.size()]));
}

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 = CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME;
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));
}
}
}

private SpringApplicationRunListeners getRunListeners(String[] args) {

Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class };
return new SpringApplicationRunListeners(logger, getSpringFactoriesInstances(
SpringApplicationRunListener.class, types, this, args));
}

private <T> Collection<? extends T> getSpringFactoriesInstances(Class<T> type) {
return getSpringFactoriesInstances(type, new Class<?>[] {});
}


private <T> Collection<? extends T> getSpringFactoriesInstances(Class<T> type,
Class<?>[] parameterTypes, Object... args) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// Use names and ensure unique to protect against duplicates
Set<String> names = new LinkedHashSet<String>(
SpringFactoriesLoader.loadFactoryNames(type, classLoader));
List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
classLoader, args, names);
AnnotationAwareOrderComparator.sort(instances);
return instances;
}

@SuppressWarnings("unchecked")
private <T> List<T> createSpringFactoriesInstances(Class<T> type,
Class<?>[] parameterTypes, ClassLoader classLoader, Object[] args,
Set<String> names) {
List<T> instances = new ArrayList<T>(names.size());
for (String name : names) {
try {
Class<?> instanceClass = ClassUtils.forName(name, classLoader);
Assert.isAssignable(type, instanceClass);
Constructor<?> constructor = instanceClass
.getDeclaredConstructor(parameterTypes);
T instance = (T) BeanUtils.instantiateClass(constructor, args);
instances.add(instance);
}
catch (Throwable ex) {
throw new IllegalArgumentException(
"Cannot instantiate " + type + " : " + name, ex);
}
}
return instances;
}
}


/*package com.pa.openapi.gateway.core;


import java.io.IOException;
import java.util.HashSet;
import java.util.Set;


import groovy.lang.Closure;




import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader;
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotatedBeanDefinitionReader;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.filter.AbstractTypeHierarchyTraversingFilter;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;




class BeanDefinitionLoader {


private final Object[] sources;


private final AnnotatedBeanDefinitionReader annotatedReader;


private final XmlBeanDefinitionReader xmlReader;


private BeanDefinitionReader groovyReader;


private final ClassPathBeanDefinitionScanner scanner;


private ResourceLoader resourceLoader;


*//**
* Create a new {@link BeanDefinitionLoader} that will load beans into the specified
* {@link BeanDefinitionRegistry}.
* @param registry the bean definition registry that will contain the loaded beans
* @param sources the bean sources
*//*
BeanDefinitionLoader(BeanDefinitionRegistry registry, Object... sources) {
Assert.notNull(registry, "Registry must not be null");
Assert.notEmpty(sources, "Sources must not be empty");
this.sources = sources;
this.annotatedReader = new AnnotatedBeanDefinitionReader(registry);
this.xmlReader = new XmlBeanDefinitionReader(registry);
if (isGroovyPresent()) {
this.groovyReader = new GroovyBeanDefinitionReader(registry);
}
this.scanner = new ClassPathBeanDefinitionScanner(registry);
this.scanner.addExcludeFilter(new ClassExcludeFilter(sources));
}


*//**
* Set the bean name generator to be used by the underlying readers and scanner.
* @param beanNameGenerator the bean name generator
*//*
public void setBeanNameGenerator(BeanNameGenerator beanNameGenerator) {
this.annotatedReader.setBeanNameGenerator(beanNameGenerator);
this.xmlReader.setBeanNameGenerator(beanNameGenerator);
this.scanner.setBeanNameGenerator(beanNameGenerator);
}


*//**
* Set the resource loader to be used by the underlying readers and scanner.
* @param resourceLoader the resource loader
*//*
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
this.xmlReader.setResourceLoader(resourceLoader);
this.scanner.setResourceLoader(resourceLoader);
}


*//**
* Set the environment to be used by the underlying readers and scanner.
* @param environment the environment
*//*
public void setEnvironment(ConfigurableEnvironment environment) {
this.annotatedReader.setEnvironment(environment);
this.xmlReader.setEnvironment(environment);
this.scanner.setEnvironment(environment);
}


*//**
* Load the sources into the reader.
* @return the number of loaded beans
*//*
public int load() {
int count = 0;
for (Object source : this.sources) {
count += load(source);
}
return count;
}


private int load(Object source) {
Assert.notNull(source, "Source must not be null");
if (source instanceof Class<?>) {
return load((Class<?>) source);
}
if (source instanceof Resource) {
return load((Resource) source);
}
if (source instanceof Package) {
return load((Package) source);
}
if (source instanceof CharSequence) {
return load((CharSequence) source);
}
throw new IllegalArgumentException("Invalid source type " + source.getClass());
}


private int load(Class<?> source) {
if (isGroovyPresent()) {
// Any GroovyLoaders added in beans{} DSL can contribute beans here
if (GroovyBeanDefinitionSource.class.isAssignableFrom(source)) {
GroovyBeanDefinitionSource loader = BeanUtils.instantiateClass(source,
GroovyBeanDefinitionSource.class);
load(loader);
}
}
if (isComponent(source)) {
this.annotatedReader.register(source);
return 1;
}
return 0;
}


private int load(GroovyBeanDefinitionSource source) {
int before = this.xmlReader.getRegistry().getBeanDefinitionCount();
((GroovyBeanDefinitionReader) this.groovyReader).beans(source.getBeans());
int after = this.xmlReader.getRegistry().getBeanDefinitionCount();
return after - before;
}


private int load(Resource source) {
if (source.getFilename().endsWith(".groovy")) {
if (this.groovyReader == null) {
throw new BeanDefinitionStoreException(
"Cannot load Groovy beans without Groovy on classpath");
}
return this.groovyReader.loadBeanDefinitions(source);
}
return this.xmlReader.loadBeanDefinitions(source);
}


private int load(Package source) {
return this.scanner.scan(source.getName());
}


private int load(CharSequence source) {
String resolvedSource = this.xmlReader.getEnvironment()
.resolvePlaceholders(source.toString());
// Attempt as a Class
try {
return load(ClassUtils.forName(resolvedSource, null));
}
catch (IllegalArgumentException ex) {
// swallow exception and continue
}
catch (ClassNotFoundException ex) {
// swallow exception and continue
}
// Attempt as resources
Resource[] resources = findResources(resolvedSource);
int loadCount = 0;
boolean atLeastOneResourceExists = false;
for (Resource resource : resources) {
if (isLoadCandidate(resource)) {
atLeastOneResourceExists = true;
loadCount += load(resource);
}
}
if (atLeastOneResourceExists) {
return loadCount;
}
// Attempt as package
Package packageResource = findPackage(resolvedSource);
if (packageResource != null) {
return load(packageResource);
}
throw new IllegalArgumentException("Invalid source '" + resolvedSource + "'");
}


private boolean isGroovyPresent() {
return ClassUtils.isPresent("groovy.lang.MetaClass", null);
}


private Resource[] findResources(String source) {
ResourceLoader loader = (this.resourceLoader != null ? this.resourceLoader
: new PathMatchingResourcePatternResolver());
try {
if (loader instanceof ResourcePatternResolver) {
return ((ResourcePatternResolver) loader).getResources(source);
}
return new Resource[] { loader.getResource(source) };
}
catch (IOException ex) {
throw new IllegalStateException("Error reading source '" + source + "'");
}
}


private boolean isLoadCandidate(Resource resource) {
if (resource == null || !resource.exists()) {
return false;
}
if (resource instanceof ClassPathResource) {
// A simple package without a '.' may accidentally get loaded as an XML
// document if we're not careful. The result of getInputStream() will be
// a file list of the package content. We double check here that it's not
// actually a package.
String path = ((ClassPathResource) resource).getPath();
if (path.indexOf(".") == -1) {
try {
return Package.getPackage(path) == null;
}
catch (Exception ex) {
// Ignore
}
}
}
return true;
}


private Package findPackage(CharSequence source) {
Package pkg = Package.getPackage(source.toString());
if (pkg != null) {
return pkg;
}
try {
// Attempt to find a class in this package
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(
getClass().getClassLoader());
Resource[] resources = resolver.getResources(
ClassUtils.convertClassNameToResourcePath(source.toString())
+ "/*.class");
for (Resource resource : resources) {
String className = StringUtils
.stripFilenameExtension(resource.getFilename());
load(Class.forName(source.toString() + "." + className));
break;
}
}
catch (Exception ex) {
// swallow exception and continue
}
return Package.getPackage(source.toString());
}


private boolean isComponent(Class<?> type) {
// This has to be a bit of a guess. The only way to be sure that this type is
// eligible is to make a bean definition out of it and try to instantiate it.
if (AnnotationUtils.findAnnotation(type, Component.class) != null) {
return true;
}
// Nested anonymous classes are not eligible for registration, nor are groovy
// closures
if (type.getName().matches(".*\\$_.*closure.*") || type.isAnonymousClass()
|| type.getConstructors() == null || type.getConstructors().length == 0) {
return false;
}
return true;
}


*//**
* Simple {@link TypeFilter} used to ensure that specified {@link Class} sources are
* not accidentally re-added during scanning.
*//*
private static class ClassExcludeFilter
extends AbstractTypeHierarchyTraversingFilter {


private final Set<String> classNames = new HashSet<String>();


ClassExcludeFilter(Object... sources) {
super(false, false);
for (Object source : sources) {
if (source instanceof Class<?>) {
this.classNames.add(((Class<?>) source).getName());
}
}
}


@Override
protected boolean matchClassName(String className) {
return this.classNames.contains(className);
}


}


*//**
* Source for Bean definitions defined in Groovy.
*//*
protected interface GroovyBeanDefinitionSource {


Closure<?> getBeans();


}


}
*/


package com.pa.openapi.gateway.core;


import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.ResourceEntityResolver;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;


import com.pa.springcloud.SpringBootApplications;


public class CustomAnnotationConfigEmbeddedWebApplicationContext
extends AnnotationConfigEmbeddedWebApplicationContext {

public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml";


public static final String DEFAULT_CONFIG_LOCATION_PREFIX = "/WEB-INF/";


public static final String DEFAULT_CONFIG_LOCATION_SUFFIX = ".xml";




private final XmlBeanDefinitionReader beanDefinitionReader;
private String[] configLocations;

public CustomAnnotationConfigEmbeddedWebApplicationContext(){
beanDefinitionReader = new XmlBeanDefinitionReader(this);
Class<?>[] annotatedClasses = new Class<?>[]{SpringBootApplications.class};
register(annotatedClasses);
}

public void setEnvironment(ConfigurableEnvironment environment) {
super.setEnvironment(environment);
this.beanDefinitionReader.setEnvironment(environment);
}

public final BeanDefinitionRegistry getRegistry() {
return this.beanDefinitionReader.getRegistry();
}


public String generateBeanName(BeanDefinition beanDefinition) {
return this.beanDefinitionReader.getBeanNameGenerator().generateBeanName(beanDefinition, getRegistry());
}

public String registerWithGeneratedName(BeanDefinition beanDefinition) {
String generatedName = generateBeanName(beanDefinition);
getRegistry().registerBeanDefinition(generatedName, beanDefinition);
return generatedName;
}



public void setConfigLocation(String location) {
setConfigLocations(StringUtils.tokenizeToStringArray(location, CONFIG_LOCATION_DELIMITERS));
}


public void setConfigLocations(String... locations) {
if (locations != null) {
Assert.noNullElements(locations, "Config locations must not be null");
this.configLocations = new String[locations.length];
for (int i = 0; i < locations.length; i++) {
this.configLocations[i] = resolvePath(locations[i]).trim();
}
}
else {
this.configLocations = null;
}
}
protected String resolvePath(String path) {
return getEnvironment().resolveRequiredPlaceholders(path);
}


protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
super.postProcessBeanFactory(beanFactory);
DefaultListableBeanFactory beanFactorys = (DefaultListableBeanFactory) beanFactory;
if(this.configLocations != null && this.configLocations.length > 0){
loadBeanDefinitions(beanFactorys);
}
}


protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) {

beanDefinitionReader.setEnvironment(getEnvironment());
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));


// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
initBeanDefinitionReader(beanDefinitionReader);
loadBeanDefinitions(beanDefinitionReader);

}

protected void initBeanDefinitionReader(XmlBeanDefinitionReader beanDefinitionReader) {
}

protected void loadBeanDefinitions(XmlBeanDefinitionReader reader){
String[] configLocations = getConfigLocations();

if (configLocations != null) {
for (String configLocation : configLocations) {
reader.loadBeanDefinitions(configLocation);
}
}
}

public String[] getConfigLocations(){
return this.configLocations;
}

protected String[] getDefaultConfigLocations() {
if (getNamespace() != null) {
return new String[] {DEFAULT_CONFIG_LOCATION_PREFIX + getNamespace() + DEFAULT_CONFIG_LOCATION_SUFFIX};
}
else {
return new String[] {DEFAULT_CONFIG_LOCATION};
}
}
}



package com.pa.openapi.gateway.core;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;


import org.springframework.boot.ExitCodeExceptionMapper;
import org.springframework.boot.ExitCodeGenerator;
import org.springframework.util.Assert;


class ExitCodeGenerators implements Iterable<ExitCodeGenerator> {


private List<ExitCodeGenerator> generators = new ArrayList<ExitCodeGenerator>();


public void addAll(Throwable exception, ExitCodeExceptionMapper... mappers) {
Assert.notNull(exception, "Exception must not be null");
Assert.notNull(mappers, "Mappers must not be null");
addAll(exception, Arrays.asList(mappers));
}


public void addAll(Throwable exception,
Iterable<? extends ExitCodeExceptionMapper> mappers) {
Assert.notNull(exception, "Exception must not be null");
Assert.notNull(mappers, "Mappers must not be null");
for (ExitCodeExceptionMapper mapper : mappers) {
add(exception, mapper);
}
}


public void add(Throwable exception, ExitCodeExceptionMapper mapper) {
Assert.notNull(exception, "Exception must not be null");
Assert.notNull(mapper, "Mapper must not be null");
add(new MappedExitCodeGenerator(exception, mapper));
}


public void addAll(ExitCodeGenerator... generators) {
Assert.notNull(generators, "Generators must not be null");
addAll(Arrays.asList(generators));
}


public void addAll(Iterable<? extends ExitCodeGenerator> generators) {
Assert.notNull(generators, "Generators must not be null");
for (ExitCodeGenerator generator : generators) {
add(generator);
}
}


public void add(ExitCodeGenerator generator) {
Assert.notNull(generator, "Generator must not be null");
this.generators.add(generator);
}


@Override
public Iterator<ExitCodeGenerator> iterator() {
return this.generators.iterator();
}


/**
* Get the final exit code that should be returned based on all contained generators.
* @return the final exit code.
*/
public int getExitCode() {
int exitCode = 0;
for (ExitCodeGenerator generator : this.generators) {
try {
int value = generator.getExitCode();
if (value > 0 && value > exitCode || value < 0 && value < exitCode) {
exitCode = value;
}
}
catch (Exception ex) {
exitCode = (exitCode == 0 ? 1 : exitCode);
ex.printStackTrace();
}
}
return exitCode;
}


/**
* Adapts an {@link ExitCodeExceptionMapper} to an {@link ExitCodeGenerator}.
*/
private static class MappedExitCodeGenerator implements ExitCodeGenerator {


private final Throwable exception;


private final ExitCodeExceptionMapper mapper;


MappedExitCodeGenerator(Throwable exception, ExitCodeExceptionMapper mapper) {
this.exception = exception;
this.mapper = mapper;
}


@Override
public int getExitCode() {
return this.mapper.getExitCode(this.exception);
}


}


}


package com.pa.openapi.gateway.core;


import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;


import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;


import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.DefaultApplicationArguments;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.web.context.WebApplicationContext;




@WebListener
public class ServletContextListenerImpl implements ServletContextListener{


@Override
public void contextInitialized(ServletContextEvent sce) {

String[] args = new String[] {};
ServletContext servletContext = sce.getServletContext();
ConfigurableApplicationContext context =(ConfigurableApplicationContext) servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
afterRefresh(context, applicationArguments);

}


@Override
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub


}



protected void afterRefresh(ConfigurableApplicationContext context, ApplicationArguments args) {
callRunners(context, args);
}


private void callRunners(ApplicationContext context, ApplicationArguments args) {
List<Object> runners = new ArrayList<Object>();
runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
AnnotationAwareOrderComparator.sort(runners);
for (Object runner : new LinkedHashSet<Object>(runners)) {
if (runner instanceof ApplicationRunner) {
callRunner((ApplicationRunner) runner, args);
}
if (runner instanceof CommandLineRunner) {
callRunner((CommandLineRunner) runner, args);
}
}
}


private void callRunner(ApplicationRunner runner, ApplicationArguments args) {
try {
(runner).run(args);
} catch (Exception ex) {
throw new IllegalStateException("Failed to execute ApplicationRunner", ex);
}
}


private void callRunner(CommandLineRunner runner, ApplicationArguments args) {
try {
(runner).run(args.getSourceArgs());
} catch (Exception ex) {
throw new IllegalStateException("Failed to execute CommandLineRunner", ex);
}
}
}


package com.pa.openapi.gateway.core;


import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;


import org.apache.commons.logging.Log;
import org.springframework.boot.Banner;
import org.springframework.boot.ImageBanner;
import org.springframework.boot.ResourceBanner;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.StringUtils;


class SpringApplicationBannerPrinter {
static final String BANNER_LOCATION_PROPERTY = "banner.location";


static final String BANNER_IMAGE_LOCATION_PROPERTY = "banner.image.location";


static final String DEFAULT_BANNER_LOCATION = "banner.txt";


static final String[] IMAGE_EXTENSION = { "gif", "jpg", "png" };


private static final Banner DEFAULT_BANNER = new SpringBootBanner();


private final ResourceLoader resourceLoader;


private final Banner fallbackBanner;


SpringApplicationBannerPrinter(ResourceLoader resourceLoader, Banner fallbackBanner) {
this.resourceLoader = resourceLoader;
this.fallbackBanner = fallbackBanner;
}


public Banner print(Environment environment, Class<?> sourceClass, Log logger) {
Banner banner = getBanner(environment, this.fallbackBanner);
try {
logger.info(createStringFromBanner(banner, environment, sourceClass));
}
catch (UnsupportedEncodingException ex) {
logger.warn("Failed to create String for banner", ex);
}
return new PrintedBanner(banner, sourceClass);
}


public Banner print(Environment environment, Class<?> sourceClass, PrintStream out) {
Banner banner = getBanner(environment, this.fallbackBanner);
banner.printBanner(environment, sourceClass, out);
return new PrintedBanner(banner, sourceClass);
}


private Banner getBanner(Environment environment, Banner definedBanner) {
Banners banners = new Banners();
banners.addIfNotNull(getImageBanner(environment));
banners.addIfNotNull(getTextBanner(environment));
if (banners.hasAtLeastOneBanner()) {
return banners;
}
if (this.fallbackBanner != null) {
return this.fallbackBanner;
}
return DEFAULT_BANNER;
}


private Banner getTextBanner(Environment environment) {
String location = environment.getProperty(BANNER_LOCATION_PROPERTY,
DEFAULT_BANNER_LOCATION);
Resource resource = this.resourceLoader.getResource(location);
if (resource.exists()) {
return new ResourceBanner(resource);
}
return null;
}


private Banner getImageBanner(Environment environment) {
String location = environment.getProperty(BANNER_IMAGE_LOCATION_PROPERTY);
if (StringUtils.hasLength(location)) {
Resource resource = this.resourceLoader.getResource(location);
return (resource.exists() ? new ImageBanner(resource) : null);
}
for (String ext : IMAGE_EXTENSION) {
Resource resource = this.resourceLoader.getResource("banner." + ext);
if (resource.exists()) {
return new ImageBanner(resource);
}
}
return null;
}


private String createStringFromBanner(Banner banner, Environment environment,
Class<?> mainApplicationClass) throws UnsupportedEncodingException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
banner.printBanner(environment, mainApplicationClass, new PrintStream(baos));
String charset = environment.getProperty("banner.charset", "UTF-8");
return baos.toString(charset);
}


/**
* {@link Banner} comprised of other {@link Banner Banners}.
*/
private static class Banners implements Banner {


private final List<Banner> banners = new ArrayList<Banner>();


public void addIfNotNull(Banner banner) {
if (banner != null) {
this.banners.add(banner);
}
}


public boolean hasAtLeastOneBanner() {
return !this.banners.isEmpty();
}


@Override
public void printBanner(Environment environment, Class<?> sourceClass,
PrintStream out) {
for (Banner banner : this.banners) {
banner.printBanner(environment, sourceClass, out);
}
}


}


/**
* Decorator that allows a {@link Banner} to be printed again without needing to
* specify the source class.
*/
private static class PrintedBanner implements Banner {


private final Banner banner;


private final Class<?> sourceClass;


PrintedBanner(Banner banner, Class<?> sourceClass) {
this.banner = banner;
this.sourceClass = sourceClass;
}


@Override
public void printBanner(Environment environment, Class<?> sourceClass,
PrintStream out) {
sourceClass = (sourceClass == null ? this.sourceClass : sourceClass);
this.banner.printBanner(environment, sourceClass, out);
}


}
}



package com.pa.openapi.gateway.core;


import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


import org.apache.commons.logging.Log;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.util.ReflectionUtils;


class SpringApplicationRunListeners {
private final Log log;


private final List<SpringApplicationRunListener> listeners;


SpringApplicationRunListeners(Log log,
Collection<? extends SpringApplicationRunListener> listeners) {
this.log = log;
this.listeners = new ArrayList<SpringApplicationRunListener>(listeners);
}


public void starting() {
for (SpringApplicationRunListener listener : this.listeners) {
listener.starting();
}
}


public void environmentPrepared(ConfigurableEnvironment environment) {
for (SpringApplicationRunListener listener : this.listeners) {
listener.environmentPrepared(environment);
}
}


public void contextPrepared(ConfigurableApplicationContext context) {
for (SpringApplicationRunListener listener : this.listeners) {
listener.contextPrepared(context);
}
}


public void contextLoaded(ConfigurableApplicationContext context) {
for (SpringApplicationRunListener listener : this.listeners) {
listener.contextLoaded(context);
}
}


public void finished(ConfigurableApplicationContext context, Throwable exception) {
for (SpringApplicationRunListener listener : this.listeners) {
callFinishedListener(listener, context, exception);
}
}


private void callFinishedListener(SpringApplicationRunListener listener,
ConfigurableApplicationContext context, Throwable exception) {
try {
listener.finished(context, exception);
}
catch (Throwable ex) {
if (exception == null) {
ReflectionUtils.rethrowRuntimeException(ex);
}
if (this.log.isDebugEnabled()) {
this.log.error("Error handling failed", ex);
}
else {
String message = ex.getMessage();
message = (message == null ? "no error message" : message);
this.log.warn("Error handling failed (" + message + ")");
}
}
}


}



package com.pa.openapi.gateway.core;


import java.io.PrintStream;


import org.springframework.boot.Banner;
import org.springframework.boot.SpringBootVersion;
import org.springframework.boot.ansi.AnsiColor;
import org.springframework.boot.ansi.AnsiOutput;
import org.springframework.boot.ansi.AnsiStyle;
import org.springframework.core.env.Environment;


class SpringBootBanner implements Banner {


private static final String[] BANNER = { "",
"  .   ____          _            __ _ _",
" /\\\\ / ___'_ __ _ _(_)_ __  __ _ \\ \\ \\ \\",
"( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\",
" \\\\/  ___)| |_)| | | | | || (_| |  ) ) ) )",
"  '  |____| .__|_| |_|_| |_\\__, | / / / /",
" =========|_|==============|___/=/_/_/_/" };


private static final String SPRING_BOOT = " :: Spring Boot :: ";


private static final int STRAP_LINE_SIZE = 42;


@Override
public void printBanner(Environment environment, Class<?> sourceClass,
PrintStream printStream) {
for (String line : BANNER) {
printStream.println(line);
}
String version = SpringBootVersion.getVersion();
version = (version == null ? "" : " (v" + version + ")");
String padding = "";
while (padding.length() < STRAP_LINE_SIZE
- (version.length() + SPRING_BOOT.length())) {
padding += " ";
}


printStream.println(AnsiOutput.toString(AnsiColor.GREEN, SPRING_BOOT,
AnsiColor.DEFAULT, padding, AnsiStyle.FAINT, version));
printStream.println();
}




}


package com.pa.openapi.gateway.core;


import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;






class SpringBootExceptionHandler implements UncaughtExceptionHandler {


private static Set<String> LOG_CONFIGURATION_MESSAGES;


static {
Set<String> messages = new HashSet<String>();
messages.add("Logback configuration error detected");
LOG_CONFIGURATION_MESSAGES = Collections.unmodifiableSet(messages);
}


private static LoggedExceptionHandlerThreadLocal handler = new LoggedExceptionHandlerThreadLocal();


private final UncaughtExceptionHandler parent;


private final List<Throwable> loggedExceptions = new ArrayList<Throwable>();


private int exitCode = 0;


SpringBootExceptionHandler(UncaughtExceptionHandler parent) {
this.parent = parent;
}


public void registerLoggedException(Throwable exception) {
this.loggedExceptions.add(exception);
}


public void registerExitCode(int exitCode) {
this.exitCode = exitCode;
}


@Override
public void uncaughtException(Thread thread, Throwable ex) {
try {
if (isPassedToParent(ex) && this.parent != null) {
this.parent.uncaughtException(thread, ex);
}
}
finally {
this.loggedExceptions.clear();
if (this.exitCode != 0) {
System.exit(this.exitCode);
}
}
}


private boolean isPassedToParent(Throwable ex) {
return isLogConfigurationMessage(ex) || !isRegistered(ex);
}


/**
* Check if the exception is a log configuration message, i.e. the log call might not
* have actually output anything.
* @param ex the source exception
* @return {@code true} if the exception contains a log configuration message
*/
private boolean isLogConfigurationMessage(Throwable ex) {
String message = ex.getMessage();
if (message != null) {
for (String candidate : LOG_CONFIGURATION_MESSAGES) {
if (message.contains(candidate)) {
return true;
}
}
}
return false;
}


private boolean isRegistered(Throwable ex) {
if (this.loggedExceptions.contains(ex)) {
return true;
}
if (ex instanceof InvocationTargetException) {
return isRegistered(ex.getCause());
}
return false;
}


static SpringBootExceptionHandler forCurrentThread() {
return handler.get();
}


/**
* Thread local used to attach and track handlers.
*/
private static class LoggedExceptionHandlerThreadLocal
extends ThreadLocal<SpringBootExceptionHandler> {


@Override
protected SpringBootExceptionHandler initialValue() {
SpringBootExceptionHandler handler = new SpringBootExceptionHandler(
Thread.currentThread().getUncaughtExceptionHandler());
Thread.currentThread().setUncaughtExceptionHandler(handler);
return handler;
};


}


}


package com.pa.openapi.gateway.core;


import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.util.concurrent.Callable;


import org.apache.commons.logging.Log;
import org.springframework.boot.ApplicationHome;
import org.springframework.context.ApplicationContext;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StopWatch;
import org.springframework.util.StringUtils;


class StartupInfoLogger {


private final Class<?> sourceClass;


StartupInfoLogger(Class<?> sourceClass) {
this.sourceClass = sourceClass;
}


public void logStarting(Log log) {
Assert.notNull(log, "Log must not be null");
if (log.isInfoEnabled()) {
log.info(getStartupMessage());
}
if (log.isDebugEnabled()) {
log.debug(getRunningMessage());
}
}


public void logStarted(Log log, StopWatch stopWatch) {
if (log.isInfoEnabled()) {
log.info(getStartedMessage(stopWatch));
}
}


private String getStartupMessage() {
StringBuilder message = new StringBuilder();
message.append("Starting ");
message.append(getApplicationName());
message.append(getVersion(this.sourceClass));
message.append(getOn());
message.append(getPid());
message.append(getContext());
return message.toString();
}


private StringBuilder getRunningMessage() {
StringBuilder message = new StringBuilder();
message.append("Running with Spring Boot");
message.append(getVersion(getClass()));
message.append(", Spring");
message.append(getVersion(ApplicationContext.class));
return message;
}


private StringBuilder getStartedMessage(StopWatch stopWatch) {
StringBuilder message = new StringBuilder();
message.append("Started ");
message.append(getApplicationName());
message.append(" in ");
message.append(stopWatch.getTotalTimeSeconds());
try {
double uptime = ManagementFactory.getRuntimeMXBean().getUptime() / 1000.0;
message.append(" seconds (JVM running for " + uptime + ")");
}
catch (Throwable ex) {
// No JVM time available
}
return message;
}


private String getApplicationName() {
return (this.sourceClass != null ? ClassUtils.getShortName(this.sourceClass)
: "application");
}


private String getVersion(final Class<?> source) {
return getValue(" v", new Callable<Object>() {
@Override
public Object call() throws Exception {
return source.getPackage().getImplementationVersion();
}
}, "");
}


private String getOn() {
return getValue(" on ", new Callable<Object>() {
@Override
public Object call() throws Exception {
return InetAddress.getLocalHost().getHostName();
}
});
}


private String getPid() {
return getValue(" with PID ", new Callable<Object>() {
@Override
public Object call() throws Exception {
return System.getProperty("PID");
}
});
}


private String getContext() {
String startedBy = getValue("started by ", new Callable<Object>() {
@Override
public Object call() throws Exception {
return System.getProperty("user.name");
}
});
String in = getValue("in ", new Callable<Object>() {
@Override
public Object call() throws Exception {
return System.getProperty("user.dir");
}
});
ApplicationHome home = new ApplicationHome(this.sourceClass);
String path = (home.getSource() == null ? ""
: home.getSource().getAbsolutePath());
if (startedBy == null && path == null) {
return "";
}
if (StringUtils.hasLength(startedBy) && StringUtils.hasLength(path)) {
startedBy = " " + startedBy;
}
if (StringUtils.hasLength(in) && StringUtils.hasLength(startedBy)) {
in = " " + in;
}
return " (" + path + startedBy + in + ")";
}


private String getValue(String prefix, Callable<Object> call) {
return getValue(prefix, call, "");
}


private String getValue(String prefix, Callable<Object> call, String defaultValue) {
try {
Object value = call.call();
if (value != null && StringUtils.hasLength(value.toString())) {
return prefix + value;
}
}
catch (Exception ex) {
// Swallow and continue
}
return defaultValue;
}


}

阅读全文
0 0
原创粉丝点击