View Javadoc
1   package net.avcompris.commons3.web;
2   
3   import static com.google.common.base.Preconditions.checkNotNull;
4   import static org.apache.commons.lang3.StringUtils.repeat;
5   
6   import java.io.PrintStream;
7   import java.util.Map;
8   import java.util.TreeMap;
9   
10  import javax.annotation.Nullable;
11  
12  import org.springframework.context.ApplicationContext;
13  
14  public abstract class ApplicationUtils {
15  
16  	/**
17  	 * Dump the list of custom beans created for the application.
18  	 *
19  	 * @param packagePrefixes e.g. "net.avcompris.commons3.examples.users" (without
20  	 *                      the trailing ".")
21  	 */
22  	public static void dumpBeans(final ApplicationContext context, final PrintStream ps,
23  			final String... packagePrefixes) {
24  
25  		checkNotNull(context, "context");
26  		checkNotNull(ps, "ps");
27  		checkNotNull(packagePrefixes, "packagePrefixes");
28  
29  		System.out.println("Beans:");
30  
31  		final Map<String, String> beanNames = new TreeMap<>();
32  
33  		int beanClassNameMaxLength = 0;
34  
35  		for (final String beanName : context.getBeanDefinitionNames()) {
36  
37  			final Object bean = context.getBean(beanName);
38  			final Class<?> beanClass = bean.getClass();
39  
40  			final Package beanPackage = beanClass.getPackage();
41  
42  			if (!containsPackagePrefix(packagePrefixes, beanPackage)) {
43  				continue;
44  			}
45  
46  			final String beanClassName = beanClass.getName();
47  
48  			beanNames.put(beanClassName, beanName);
49  
50  			beanClassNameMaxLength = Math.max(beanClassNameMaxLength, beanClassName.length());
51  		}
52  
53  		for (final String beanClassName : beanNames.keySet()) {
54  
55  			final String beanName = beanNames.get(beanClassName);
56  
57  			System.out.println("  - " + beanClassName
58  
59  					+ repeat(' ', beanClassNameMaxLength - beanClassName.length() + 1)
60  
61  					+ "(" + beanName + ")");
62  		}
63  	}
64  
65  	private static boolean containsPackagePrefix(final String[] packagePrefixes, @Nullable final Package beanPackage) {
66  
67  		if (beanPackage == null) {
68  			return false;
69  		}
70  
71  		for (final String packagePrefix : packagePrefixes) {
72  
73  			if (beanPackage.getName().startsWith(packagePrefix + ".")) {
74  
75  				return true;
76  			}
77  		}
78  
79  		return false;
80  	}
81  }