added:
[mir.git] / source / mircoders / global / MirGlobal.java
1 /*
2  * Copyright (C) 2001, 2002 The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
6  * Mir is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * Mir is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Mir; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * In addition, as a special exception, The Mir-coders gives permission to link
21  * the code of this program with  any library licensed under the Apache Software License,
22  * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
23  * (or with modified versions of the above that use the same license as the above),
24  * and distribute linked combinations including the two.  You must obey the
25  * GNU General Public License in all respects for all of the code used other than
26  * the above mentioned libraries.  If you modify this file, you may extend this
27  * exception to your version of the file, but you are not obligated to do so.
28  * If you do not wish to do so, delete this exception statement from your version.
29  */
30
31 package mircoders.global;
32
33 import mir.bundle.BasicBundleFactory;
34 import mir.bundle.BundleFactory;
35 import mir.bundle.CascadingBundleFactory;
36 import mir.bundle.PropertiesFileBundleLoader;
37 import mir.config.MirPropertiesConfiguration;
38 import mir.entity.adapter.EntityAdapter;
39 import mir.log.LoggerEngine;
40 import mir.log.LoggerWrapper;
41 import mircoders.accesscontrol.AccessControl;
42 import mircoders.entity.EntityComment;
43 import mircoders.entity.EntityContent;
44 import mircoders.entity.EntityUsers;
45 import mircoders.localizer.MirAdminInterfaceLocalizer;
46 import mircoders.localizer.LocalizerCache;
47 import mircoders.localizer.MirLocalizer;
48 import mircoders.localizer.MirLocalizerExc;
49 import mircoders.localizer.MirLocalizerFailure;
50
51 import java.util.ArrayList;
52 import java.util.HashMap;
53 import java.util.Iterator;
54 import java.util.List;
55 import java.util.Map;
56
57 public class MirGlobal {
58   static private MirLocalizer localizer;
59   static private ProducerEngine producerEngine;
60   static private Abuse abuse;
61   static private MRUCache mruCache;
62   static private AccessControl accessControl;
63   static private Map articleOperations;
64   static private Map commentOperations;
65   static private final Map loggedInUsers = new HashMap();
66   static private final Map loggedInUserIds = new HashMap();
67   static private LoggerWrapper logger = new LoggerWrapper("Global");
68   static private LoggerWrapper adminUsageLogger = new LoggerWrapper("AdminUsage");
69
70   static private ChangeEngine changeEngine = new ChangeEngine();
71
72   static private DatabaseEngine databaseEngine;
73
74   static private BundleFactory bundleFactory =
75       new CascadingBundleFactory(
76         new BasicBundleFactory(
77             new PropertiesFileBundleLoader(
78                 config().getHome())));
79
80   private MirGlobal() {
81   }
82
83   public synchronized static MirLocalizer localizer() {
84     String localizerClassName;
85     Class localizerClass;
86
87     if (localizer == null ) {
88       localizerClassName = config().getString("Mir.Localizer", "mirlocal.localizer.basic.MirBasicLocalizer");
89
90       try {
91         localizerClass = Class.forName(localizerClassName);
92       }
93       catch (Throwable t) {
94         throw new MirLocalizerFailure("localizer class '" +
95             localizerClassName + "' not found: ", t);
96       }
97
98       if (!MirLocalizer.class.isAssignableFrom(localizerClass)) {
99         throw new MirLocalizerFailure("localizer class '" +
100             localizerClassName + "' is not assignable from MirLocalizer");
101       }
102
103       try {
104         localizer = new LocalizerCache((MirLocalizer) localizerClass.newInstance());
105       }
106       catch (Throwable t) {
107         throw new MirLocalizerFailure("localizer class '" +
108             localizerClassName + "' cannot be instantiated: " + t.getMessage(), t);
109       }
110     }
111
112     return localizer;
113   }
114
115   /**
116    * Returns a string that provides some global status information
117    */
118   public static String getStatus() {
119     StringBuffer result = new StringBuffer();
120
121     result.append((Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory())/(1024*1024));
122     result.append("M in use, ");
123     result.append(Thread.activeCount()).append(" threads, ");
124     result.append(getDatabaseEngine().getStatus());
125
126     return result.toString();
127   }
128
129   synchronized public static Abuse abuse() {
130     if (abuse==null) {
131       try {
132         abuse = new Abuse(localizer().dataModel().adapterModel());
133       }
134       catch (MirLocalizerExc e) {
135         throw new RuntimeException(e.getMessage());
136       }
137     }
138
139     return abuse;
140   }
141
142   /**
143    * returns the global change engine (used to track changed files)
144    */
145   public static ChangeEngine getChangeEngine() {
146     return changeEngine;
147   }
148
149   public static MirPropertiesConfiguration config() {
150     return MirPropertiesConfiguration.instance();
151   }
152
153   synchronized public static DatabaseEngine getDatabaseEngine() {
154     if (databaseEngine==null) {
155       databaseEngine = new DatabaseEngine();
156     }
157
158     return databaseEngine;
159   }
160
161   public static ProducerEngine getProducerEngine() {
162     if (producerEngine == null) {
163       producerEngine = new ProducerEngine();
164     }
165
166     return producerEngine;
167   }
168
169   public static MRUCache mruCache() {
170     synchronized(MirGlobal.class) {
171       if (mruCache == null) {
172         mruCache = new MRUCache();
173       }
174       return mruCache;
175     }
176   }
177
178   synchronized public static AccessControl accessControl() {
179     if (accessControl == null) {
180       accessControl=new AccessControl();
181     }
182
183     return accessControl;
184   }
185
186   public static void performArticleOperation(EntityUsers aUser, EntityContent  anArticle, String anOperation) {
187     MirAdminInterfaceLocalizer.EntityOperation operation = getArticleOperationForName(anOperation);
188
189     try {
190       EntityAdapter user = null;
191       if (aUser!=null) {
192           user = localizer().dataModel().adapterModel().makeEntityAdapter("user", aUser);
193       }
194
195       if (operation!=null) {
196         operation.perform(
197             user,
198             localizer().dataModel().adapterModel().makeEntityAdapter("content", anArticle));
199       }
200     }
201     catch (Throwable t) {
202       throw new MirGlobalFailure(t.getMessage(), t);
203     }
204   }
205
206   public static void performCommentOperation(EntityUsers aUser, EntityComment  aComment, String anOperation) {
207     MirAdminInterfaceLocalizer.EntityOperation operation = getCommentOperationForName(anOperation);
208
209     try {
210       EntityAdapter user = null;
211       if (aUser!=null) {
212           user = localizer().dataModel().adapterModel().makeEntityAdapter("user", aUser);
213       }
214
215       if (operation!=null) {
216         operation.perform(
217             user,
218             localizer().dataModel().adapterModel().makeEntityAdapter("comment", aComment));
219       }
220     }
221     catch (Throwable t) {
222       throw new MirGlobalFailure(t.getMessage(), t);
223     }
224   }
225
226   private synchronized static MirAdminInterfaceLocalizer.EntityOperation
227       getArticleOperationForName(String aName) {
228     try {
229       if (articleOperations == null) {
230         articleOperations = new HashMap();
231         Iterator i = localizer().adminInterface().simpleArticleOperations().iterator();
232         while (i.hasNext()) {
233           MirAdminInterfaceLocalizer.EntityOperation operation =
234               (MirAdminInterfaceLocalizer.EntityOperation) i.next();
235           articleOperations.put(operation.getName(), operation);
236         }
237       }
238
239       return (MirAdminInterfaceLocalizer.EntityOperation) articleOperations.get(aName);
240     }
241     catch (Throwable t) {
242       throw new MirGlobalFailure(t.getMessage(), t);
243     }
244   }
245
246   private synchronized static MirAdminInterfaceLocalizer.EntityOperation
247       getCommentOperationForName(String aName) {
248     try {
249       if (commentOperations == null) {
250         commentOperations = new HashMap();
251         Iterator i = localizer().adminInterface().simpleCommentOperations().iterator();
252         while (i.hasNext()) {
253           MirAdminInterfaceLocalizer.EntityOperation operation =
254               (MirAdminInterfaceLocalizer.EntityOperation) i.next();
255           commentOperations.put(operation.getName(), operation);
256         }
257       }
258
259       return (MirAdminInterfaceLocalizer.EntityOperation) commentOperations.get(aName);
260     }
261     catch (Throwable t) {
262       throw new MirGlobalFailure(t.getMessage(), t);
263     }
264   }
265
266   public static boolean isUserLoggedIn(String anId) {
267     synchronized (loggedInUserIds) {
268       return loggedInUserIds.containsKey(anId);
269     }
270   }
271
272   public static List getLoggedInUsers() {
273     List result = new ArrayList();
274
275     synchronized (loggedInUsers) {
276       Iterator i = loggedInUsers.entrySet().iterator();
277
278       while (i.hasNext()) {
279         Map.Entry entry = (Map.Entry) i.next();
280
281         Map item = new HashMap();
282         item.put("name", entry.getKey());
283         item.put("count", entry.getValue());
284         result.add(item);
285       }
286     }
287
288     return result;
289   }
290
291   public static BundleFactory getBundleFactory() {
292     return bundleFactory;
293   }
294
295   public static void registerLogin(String aName, String anId) {
296     modifyLoggedInCount(aName, anId, 1);
297   }
298
299   public static void registerLogout(String aName, String anId) {
300     modifyLoggedInCount(aName, anId, -1);
301   }
302
303   private static void modifyLoggedInCount(String aName, String anId, int aModifier) {
304     synchronized (loggedInUsers) {
305       Integer count = (Integer) loggedInUsers.get(aName);
306       if (count==null)
307         count = new Integer(0);
308
309       if (count.intValue()+aModifier<=0) {
310         loggedInUsers.remove(aName);
311       }
312       else {
313         loggedInUsers.put(aName, new Integer(count.intValue() + aModifier));
314       }
315     }
316
317     synchronized (loggedInUserIds) {
318       Integer count = (Integer) loggedInUserIds.get(anId);
319       if (count==null)
320         count = new Integer(0);
321
322       if (count.intValue()+aModifier<=0) {
323         loggedInUserIds.remove(anId);
324       }
325       else {
326         loggedInUserIds.put(anId, new Integer(count.intValue() + aModifier));
327       }
328     }
329   }
330
331   /**
332    * Called whenever a modifying admin action occurs. Used to log
333    * the action, if admin activity logging is turned on,
334    */
335   public static void logAdminUsage(EntityUsers aUser, String anObject, String aDescription) {
336     try {
337       if (config().getString("Mir.Admin.LogAdminActivity", "0").equals("1")) {
338         String user = "unknown (" + aUser.toString() + ")";
339         if (aUser != null)
340           user = aUser.getFieldValue("login");
341         adminUsageLogger.info(user + " | " + anObject + " | " + aDescription);
342       }
343     }
344     catch (Throwable t) {
345       logger.error("Error while logging admin usage ("+
346           aUser.toString()+", "+aDescription+"): " +t.toString());
347     }
348   }
349
350   /**
351    * Reloads all reloadable configurations, such as the producer subsystem.
352    */
353   public static void reloadConfigurations() throws MirGlobalExc, MirGlobalFailure {
354     getProducerEngine().reloadConfiguration();
355     try {
356       LoggerEngine.reload();
357     }
358     catch (Throwable e) {
359       throw new MirGlobalFailure(e);
360     }
361     getBundleFactory().reload();
362   }
363 }
364
365