001package org.kuali.common.util.main; 002 003import java.util.Collections; 004import java.util.Map; 005 006import org.kuali.common.util.spring.SpringExecutable; 007import org.kuali.common.util.spring.service.SpringContext; 008import org.kuali.common.util.spring.service.SpringService; 009 010public class MainUtils { 011 012 public static final String MAIN_CONTEXT_BEAN_NAME = "mainContext"; 013 public static final String MAIN_PROFILE_NAME = "main"; 014 015 /** 016 * Load the @Configuration <code>mainClass</code> using Spring and then terminate the JVM. 017 */ 018 public static void runAndExit(Class<?> mainClass, String[] args) { 019 runAndExit(mainClass, args, false); 020 } 021 022 /** 023 * Load the @Configuration <code>mainClass</code> using Spring and then terminate the JVM. 024 */ 025 public static void runAndExit(Class<?> mainClass, String[] args, boolean stacktrace) { 026 run(mainClass, args, stacktrace, true); 027 } 028 029 /** 030 * Load the @Configuration <code>mainClass</code> using Spring 031 */ 032 public static void run(Class<?> mainClass, String[] args, boolean stacktrace) { 033 run(mainClass, args, stacktrace, false); 034 } 035 036 /** 037 * Load the @Configuration <code>mainClass</code> using Spring 038 */ 039 public static void run(Class<?> mainClass, String[] args) { 040 run(mainClass, args, true, false); 041 } 042 043 /** 044 * 045 */ 046 public static void run(Class<?> mainClass, String[] args, boolean stacktrace, boolean exit) { 047 try { 048 // Preserve the context info from the class where main(String[] args) was invoked 049 MainContext mainContext = new MainContext(mainClass, args); 050 051 // Create a map containing the context so we can register it with Spring 052 Map<String, Object> beans = Collections.singletonMap(MAIN_CONTEXT_BEAN_NAME, (Object) mainContext); 053 054 // Create a SpringContext using the map and main class, with 1 active profile called "main" 055 SpringContext context = new SpringContext(beans, mainClass, MAIN_PROFILE_NAME); 056 057 // DefaultSpringService does what we need 058 SpringService service = SpringExecutable.DEFAULT_SPRING_SERVICE; 059 060 // This causes Spring to load the @Configuration annotated main class 061 new SpringExecutable(service, context).execute(); 062 063 // Exit with zero if there is no exception 064 if (exit) { 065 System.exit(Status.SUCCESS.getValue()); 066 } 067 } catch (Exception e) { 068 handleException(e, stacktrace, exit); 069 } 070 } 071 072 protected static void handleException(Exception e, boolean stacktrace, boolean exit) { 073 if (stacktrace) { 074 e.printStackTrace(); 075 } else { 076 System.err.print(e.getMessage()); 077 } 078 if (exit) { 079 System.exit(Status.FAILURE.getValue()); 080 } 081 } 082 083}