View Javadoc

1   /*
2    * GUMS.java
3    *
4    * Created on June 3, 2004, 10:39 AM
5    */
6   
7   package gov.bnl.gums;
8   
9   import gov.bnl.gums.admin.CertCache;
10  import gov.bnl.gums.configuration.Configuration;
11  import gov.bnl.gums.configuration.ConfigurationToolkit;
12  import gov.bnl.gums.configuration.Version;
13  import gov.bnl.gums.persistence.HibernatePersistenceEngine;
14  import gov.bnl.gums.persistence.PersistenceEngine;
15  import gov.bnl.gums.userGroup.ManualUserGroup;
16  import gov.bnl.gums.util.QuietLog;
17  
18  import java.io.File;
19  import java.io.FileInputStream;
20  import java.io.FileNotFoundException;
21  import java.io.IOException;
22  import java.lang.reflect.InvocationTargetException;
23  import java.util.Collection;
24  import java.util.Properties;
25  import java.util.Timer;
26  import java.util.TimerTask;
27  
28  import org.apache.commons.digester.Digester;
29  import org.apache.log4j.Logger;
30  
31  
32  /** 
33   * Facade for the whole business logic available in GUMS. Using GUMS means
34   * instanciating an object of this class, and use it to reach the rest of the
35   * functionalities.
36   *
37   * @author  Gabriele Carcassi, Jay Packard
38   */
39  public class GUMS {
40      static final public String siteAdminLogName = "gums.siteAdmin";
41      static final public String gumsAdminLogName = "gums.gumsAdmin";
42  //    static private Logger log = Logger.getLogger(GUMS.class); // only use this log for particularly tricky aspects of this class - otherwise log within lower level classes
43      static public QuietLog gumsAdminEmailLog = new QuietLog("gums.gumsAdminEmail");
44      static protected Logger gumsAdminLog = Logger.getLogger(GUMS.gumsAdminLogName);
45      static protected String version = null;
46      
47      static public String getMajorMinorVersion() {
48      	String mmVersion = getVersion();
49      	if (mmVersion != null) {
50  	    	int dotIndex = mmVersion.lastIndexOf('.');
51  	    	if (dotIndex != -1) {
52  	    		return mmVersion.substring(0, dotIndex);
53  	    	}
54      	}
55      	return "";
56      }
57      
58      static public String getVersion() {
59      	if (version==null) {
60  			String pomFile;
61      		if (CertCache.getMetaDir() != null) {
62      			pomFile = CertCache.getMetaDir()+"/maven/gums/gums-service/pom.xml";
63      		}
64      		else {
65      			// For testing
66      			String curDir = System.getProperty("user.dir");
67      			if (curDir.endsWith("/WEB-INF/scripts"))
68      				curDir += "/../../../..";
69      			pomFile = curDir + "/pom.xml";
70      			
71      			// for command line scripts
72      			if (!new File(pomFile).exists()) {
73          			curDir = System.getProperty("user.dir");
74          			if (curDir.endsWith("/WEB-INF/scripts"))
75          				curDir += "/../../META-INF/maven/gums/gums-service";
76          			pomFile = curDir + "/pom.xml";    				
77      			}
78      		}
79      		
80  			Digester digester = new Digester();
81  			digester.addObjectCreate("project/version", Version.class);
82  			digester.addCallMethod("project/version","setVersion",0);
83  			Version versionCls = null;
84  			try {
85  				versionCls = (Version)digester.parse("file://"+pomFile);
86  			} catch (Exception e) {
87  				gumsAdminLog.warn("Cannot get GUMS version from "+pomFile);
88  				return "?";
89  			}
90  			if (versionCls == null) {
91  				gumsAdminLog.warn("Cannot get GUMS version from "+pomFile);
92  				return "?";
93  			}
94  			else
95  				gumsAdminLog.debug("Loaded GUMS version " + versionCls.getVersion() + " from '" + pomFile + "'" );
96  			version = versionCls.getVersion();
97  		}
98  		return version;
99      }
100 
101     static TimerTask updateTask = new TimerTask() {
102         public void run() {
103         	synchronized(this) {
104                 try {
105                     gumsAdminLog.info("Starting automatic updateGroups");
106                     gums.beginTransaction();
107                     gums.getConfiguration().updateUserGroupMembers();
108                     gums.commit();
109                     gumsAdminLog.info("Automatic updateGroups ended");
110                 } catch (Exception e) {
111                 	gums.rollback();
112                     gumsAdminLog.warn("Automatic group update had failures - " + e.getMessage());
113                     gumsAdminEmailLog.put("updateUserGroup", e.getMessage(), false);
114                 }
115         	}
116         }
117     };     
118     
119     static TimerTask updateBannedTask = new TimerTask() {
120         public void run() {
121         	synchronized(gums) {
122                 try {
123                     gumsAdminLog.info("Starting automatic updateBannedGroups");
124                     gums.beginTransaction();
125                     gums.getConfiguration().updateBannedUserGroupMembers();
126                     gums.commit();
127                     gumsAdminLog.info("Automatic updateBannedGroups ended");
128                 } catch (Exception e) {
129                 	gums.rollback();
130                     gumsAdminLog.warn("Automatic banned group update had failures - " + e.getMessage());
131                     gumsAdminEmailLog.put("updateBannedGroups", e.getMessage(), false);
132                 }
133         	}
134         }
135     };
136     
137     static TimerTask emailWarningTask = new TimerTask() {
138         public void run() {
139             synchronized(gums) {
140           	   if (gumsAdminEmailLog.hasMessages()) {
141              	   gumsAdminEmailLog.logMessages();
142           	   }
143             }
144          }
145      };  
146     
147     static TimerTask autoMergeTask = new TimerTask() {
148         public void run() {
149            synchronized(gums) {
150         	   try {
151                    gumsAdminLog.info("Starting automatic merging");
152                    gums.beginTransaction();
153                    Configuration conf = (Configuration)gums.getConfiguration().clone();
154                    if (conf!=null && conf.isAutoMerge() && 
155                 		   conf.getMergeURIs()!=null && !conf.getMergeURIs().isEmpty() &&
156                 		   conf.getMergeHostToGroupMapping()!=null && !conf.getMergeHostToGroupMapping().isEmpty()) {
157                 	   Configuration newConfig = ConfigurationToolkit.parseConfigurationTemplates(conf.getMergeURIs(), null);
158                 	   conf.mergeConfigurationTemplate(newConfig, conf.getMergeHostToGroupMapping(), true);
159                 	   gums.setConfiguration(conf);
160                    }
161                    gums.commit();
162                    gumsAdminLog.info("Automatic merging ended");
163                } 
164         	   catch (Exception e) {
165                    gums.rollback();
166                    gumsAdminLog.warn("Automatic merge had failures - " + e.getMessage());
167                    gumsAdminEmailLog.put("updateUserGroup", e.getMessage(), false);
168                }
169            }
170         }
171     };
172     
173     /**
174      * Create a thread that updates user group membership every so often
175      * 
176      * @param gums
177      */
178     static private synchronized void startWorkerThread(final GUMS gums) {
179     	Properties properties = gums.getProperties();
180     	
181         // If JNDI property is set, run the update every x minutes
182         if (gums.timer == null) {
183         	// update groups
184        	
185         	gums.timer = new Timer();
186         	
187         	// update user groups
188         	Integer updateMinutes = Integer.parseInt(properties.getProperty("updateGroupsMinutes", "720"));
189             gums.timer.scheduleAtFixedRate(updateTask, 10000, updateMinutes.intValue()*60*1000);
190             gumsAdminLog.info("Automatic group update set: will refresh every " + updateMinutes.intValue() + " minutes starting in 10 seconds.");
191             
192             // update banned groups
193         	Integer updateBannedMinutes = Integer.parseInt(properties.getProperty("updateBannedGroupsMinutes", "60"));     
194             gums.timer.scheduleAtFixedRate(updateBannedTask, 10000, updateBannedMinutes.intValue()*60*1000);
195             gumsAdminLog.info("Automatic banned group update set: will refresh every " + updateBannedMinutes.intValue() + " minutes starting in 10 seconds.");
196             
197             // sparse email logger
198         	Integer emailWarningHours = Integer.parseInt(properties.getProperty("emailWarningHours", "48"));     	
199             gums.timer.scheduleAtFixedRate(emailWarningTask, 5*60*1000, emailWarningHours.intValue()*60*60*1000);
200             gumsAdminLog.info("Automatic email warning set: will refresh every " + emailWarningHours.intValue() + " hours starting in 5 minutes.");
201             
202 	        // auto merge
203         	Integer autoMergeHours = Integer.parseInt(properties.getProperty("autoMergeHours", "24"));    	
204             gums.timer.scheduleAtFixedRate(autoMergeTask, 0, autoMergeHours.intValue()*60*60*1000);
205             gumsAdminLog.info("Automatic merging set: will refresh every " + autoMergeHours.intValue() + " hours starting now.");
206             
207             // http proxy host
208 			String httpProxyHost = properties.getProperty("http.proxyHost");
209 			if (httpProxyHost!=null && httpProxyHost.length()>0)
210 				System.setProperty("http.proxyHost", httpProxyHost);
211             
212             // http proxy port
213 			String httpProxyPort = properties.getProperty("http.proxyPort");
214 			if (httpProxyPort!=null && httpProxyPort.length()>0)
215 				System.setProperty("http.proxyPort", httpProxyPort);
216             
217             // https proxy host
218 			String httpsProxyHost = properties.getProperty("https.proxyHost");
219 			if (httpsProxyHost!=null && httpsProxyHost.length()>0)
220 				System.setProperty("https.proxyHost", httpsProxyHost);
221             
222             // https proxy port
223 			String httpsProxyPort = properties.getProperty("https.proxyPort");
224 			if (httpsProxyPort!=null && httpsProxyPort.length()>0)
225 				System.setProperty("https.proxyPort", httpsProxyPort);
226         }
227     }
228     
229     protected Timer timer;
230     protected PersistenceEngine persEngine;
231     protected CoreLogic coreLogic = new CoreLogic();
232     protected Properties properties = null;
233     protected static GUMS gums = null;
234     
235     public GUMS() throws FileNotFoundException, IOException, IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException {
236     	properties = new Properties();
237     	properties.load(new FileInputStream(CertCache.getConfigDir() + "/gums.properties"));
238     	
239     	if (properties.get("persistenceEngineClass") != null) {
240     		persEngine = (PersistenceEngine)Class.forName(properties.get("persistenceEngineClass").toString()).getConstructor().newInstance();
241     	}
242     	else
243     		persEngine = new HibernatePersistenceEngine(properties);
244         
245         startWorkerThread(this);
246     }
247     
248     public GUMS(Properties properties) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException {
249     	this.properties = properties;
250     	
251     	if (properties!=null && properties.get("gums.persistenceEngineClass") != null)
252 			persEngine = (PersistenceEngine)Class.forName(properties.get("gums.persistenceEngineClass").toString()).getConstructor(Properties.class).newInstance(properties);
253     	else
254     		persEngine = new HibernatePersistenceEngine(properties);
255         
256         startWorkerThread(this);
257     }
258     
259     public Configuration getConfiguration() {
260     	Configuration conf = persEngine.retrieveCurrentConfiguration();
261 		
262 		return conf;
263     }
264     
265     /**
266      * Retrieve the Core Logic to perform actions on the business logic.
267      * 
268      * @return the resource manager.
269      */
270     public CoreLogic getCoreLogic() {
271         return coreLogic;
272     }
273     
274     static public GUMS getSingletonGums() {
275     	try {
276 			if (gums == null)
277 				gums = new GUMS();
278 		} catch (Exception e) {
279 			gumsAdminLog.fatal(e.getMessage());
280 			throw new RuntimeException(e);
281 		}
282     	return gums;
283     }
284         
285     public Properties getProperties() {
286 		return properties;
287 	}
288     
289     public void removeBackupConfiguration(String name) {
290     	persEngine.removeBackupConfiguration(name);
291     }
292     
293     public Configuration restoreConfiguration(String name) throws Exception {
294     	Configuration conf = (Configuration)persEngine.restoreConfiguration(name);
295     	gums.timer.schedule(updateTask, 5000);
296     	return conf;
297     }
298 
299 	public void setConfiguration(Configuration conf) {
300 		if (conf.isBackup())
301 			conf.clearCachedItems();
302 		persEngine.setConfiguration(conf);
303     }
304 
305 	public Collection<String> getBackupConfigurationNames() {
306 		return persEngine.retrieveBackupConfigurationNames();
307 	}
308 	
309 	public void commit() {
310 		persEngine.commit();
311 	}
312 	
313 	public void beginTransaction() {
314 		persEngine.beginTransaction();
315 	}
316    
317 	public void rollback() {
318 		persEngine.rollback();
319 	}
320 	
321 }