package org.datacite.mds.tools;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.stereotype.Component;

@Component
public abstract class AbstractTool {
    
    private static final String APPLICATION_CONTEXT = "META-INF/spring/applicationContext.xml";
    
    @Autowired
    private LocalContainerEntityManagerFactoryBean emFactory;
    
    protected void disableValidation() {
        emFactory.getJpaPropertyMap().put("javax.persistence.validation.mode", "ddl");
        emFactory.afterPropertiesSet();
    }
    
    @SuppressWarnings("unchecked")
    public static final void initAndRun(String[] args) {
        try {
            AbstractApplicationContext context = new ClassPathXmlApplicationContext(APPLICATION_CONTEXT);
            String callingClassName = Thread.currentThread().getStackTrace()[2].getClassName();
            Class<AbstractTool> callingClass = (Class<AbstractTool>) Class.forName(callingClassName);
            AbstractTool tool = context.getBean(callingClass);
            tool.run(args);
            context.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
    public abstract void run(String[] args) throws Exception;
}

@@ -871,26 +871,8 @@
 ) %7B%0A
-        try %7B%0A    
     
@@ -911,16 +911,58 @@
 ontext =
+ null;%0A        try %7B%0A            context =
  new Cla
@@ -1312,101 +1312,148 @@
     
-    context.close();%0A        %7D catch (Exception e) %7B%0A            throw new RuntimeException(e
+%7D catch (Exception e) %7B%0A            e.printStackTrace();%0A        %7D finally %7B%0A            if (context != null)%0A                context.close(
 );%0A 

fix non-exiting tools: always close application context