package atg.tools.dynunit;

import atg.nucleus.Nucleus;
import atg.nucleus.ServiceException;
import atg.tools.dynunit.inject.NucleusInjectorFactory;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.lang.reflect.Field;

/**
 * @author msicker
 * @version 1.0.0
 */
public class DynUnit {

    private static final Logger logger = LogManager.getLogger();

    public static void init(final Object testInstance) {
        logger.entry(testInstance);
        NucleusInjectorFactory.getInjector().init(testInstance);
        logger.exit();
    }

    public static void stop(final Object testInstance) {
        logger.entry(testInstance);
        boolean foundNucleus = false;
        final Field[] fields = testInstance.getClass().getDeclaredFields();
        for (final Field field : fields) {
            if (field.isAnnotationPresent(Nuke.class)) {
                foundNucleus = true;
                try {
                    final Nucleus nucleus = (Nucleus) FieldUtils.readField(field, testInstance, true);
                    logger.info("Found Nucleus: {}.", nucleus.getAbsoluteName());
                    if (nucleus.isRunning()) {
                        logger.info("Stopping Nucleus.");
                        nucleus.stopService();
                    }
                } catch (IllegalAccessException e) {
                    logger.catching(e);
                    logger.error("Can't access test instance's Nucleus. Strange.");
                } catch (ServiceException e) {
                    logger.catching(e);
                    logger.warn("Problem stopping Nucleus.");
                }
            }
        }
        if (!foundNucleus) {
            logger.error("Couldn't find nucleus field to stop!");
        }
        logger.exit();
    }

}

@@ -142,16 +142,107 @@
 actory;%0A
+import atg.tools.dynunit.util.PropertiesUtil;%0Aimport org.apache.commons.lang3.StringUtils;%0A
 import o
@@ -281,24 +281,24 @@
 FieldUtils;%0A
-
 import org.a
@@ -455,16 +455,22 @@
 %0Apublic 
+final 
 class Dy
@@ -478,16 +478,129 @@
 Unit %7B%0A%0A
+    public static final String DYNUNIT_HOME_PROPERTY = %22atg.tools.dynunit.home%22;%0A%0A    private DynUnit() %7B%0A    %7D%0A%0A
     priv
@@ -2073,10 +2073,532 @@
 %0A    %7D%0A%0A
+    public static String getHome() %7B%0A        logger.entry();%0A        String dynUnitHome = PropertiesUtil.getSystemProperty(DYNUNIT_HOME_PROPERTY);%0A        if (StringUtils.isEmpty(dynUnitHome)) %7B%0A            dynUnitHome = System.getenv(%22DYNUNIT_HOME%22);%0A            if (StringUtils.isEmpty(dynUnitHome)) %7B%0A                logger.error(%22Can't find DynUnit home directory. Please set the %7B%7D property.%22, DYNUNIT_HOME_PROPERTY);%0A            %7D%0A        %7D%0A        return logger.exit(StringUtils.defaultString(dynUnitHome));%0A    %7D%0A%0A
 %7D%0A

Update DynUnit base class.