1 17 package org.alfresco.util.exec; 18 19 import java.util.Collections ; 20 import java.util.List ; 21 22 import org.alfresco.util.exec.RuntimeExec.ExecutionResult; 23 import org.apache.commons.logging.Log; 24 import org.apache.commons.logging.LogFactory; 25 import org.springframework.context.ApplicationEvent; 26 import org.springframework.context.ApplicationListener; 27 import org.springframework.context.event.ContextClosedEvent; 28 import org.springframework.context.event.ContextRefreshedEvent; 29 30 37 public class RuntimeExecShutdownBean implements ApplicationListener 38 { 39 private static Log logger = LogFactory.getLog(RuntimeExecShutdownBean.class); 40 41 42 private List <RuntimeExec> shutdownCommands; 43 44 private Thread shutdownHook; 45 46 private boolean executed; 47 48 51 public RuntimeExecShutdownBean() 52 { 53 this.shutdownCommands = Collections.emptyList(); 54 this.executed = false; 55 } 56 57 63 public void setShutdownCommands(List <RuntimeExec> startupCommands) 64 { 65 this.shutdownCommands = startupCommands; 66 } 67 68 72 public synchronized void onApplicationEvent(ApplicationEvent event) 73 { 74 if (event instanceof ContextRefreshedEvent) 75 { 76 shutdownHook = new ShutdownThread(); 78 Runtime.getRuntime().addShutdownHook(shutdownHook); 79 80 if (logger.isDebugEnabled()) 81 { 82 logger.debug("Registered shutdown hook"); 83 } 84 } 85 else if (event instanceof ContextClosedEvent) 86 { 87 if (shutdownHook != null) 89 { 90 execute(); 92 try 94 { 95 Runtime.getRuntime().removeShutdownHook(shutdownHook); 96 } 97 catch (IllegalStateException e) 98 { 99 } 101 shutdownHook = null; 102 103 if (logger.isDebugEnabled()) 104 { 105 logger.debug("Deregistered shutdown hook"); 106 } 107 } 108 } 109 } 110 111 private synchronized void execute() 112 { 113 if (executed) 115 { 116 return; 117 } 118 executed = true; 119 for (RuntimeExec command : shutdownCommands) 120 { 121 ExecutionResult result = command.execute(); 122 if (!result.getSuccess()) 124 { 125 logger.error("Shutdown command execution failed. Continuing with other commands.: \n" + result); 126 } 127 } 128 if (logger.isDebugEnabled()) 130 { 131 logger.debug("Executed shutdown commands"); 132 } 133 } 134 135 140 private class ShutdownThread extends Thread 141 { 142 private ShutdownThread() 143 { 144 this.setDaemon(true); 145 } 146 147 @Override 148 public void run() 149 { 150 execute(); 151 } 152 } 153 } 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 | Popular Tags |