cleanup / abuse system fix / prepping for a release
[mir.git] / source / mircoders / global / ProducerEngine.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 package mircoders.global;
31
32 import java.io.PrintWriter;
33 import java.util.ArrayList;
34 import java.util.HashMap;
35 import java.util.Iterator;
36 import java.util.List;
37 import java.util.Map;
38
39 import mir.config.MirPropertiesConfiguration;
40 import mir.log.LoggerToWriterAdapter;
41 import mir.log.LoggerWrapper;
42 import mir.producer.Producer;
43 import mir.producer.ProducerFactory;
44 import mir.producer.ProductionContext;
45 import mir.util.GeneratorFormatAdapters;
46 import mir.util.StringRoutines;
47
48 public class ProducerEngine {
49   private JobQueue producerJobQueue;
50   private LoggerWrapper logger;
51   private Map nameToFactory;
52   private List factories;
53
54   protected ProducerEngine() {
55     logger = new LoggerWrapper("Producer");
56     producerJobQueue = new JobQueue(new LoggerWrapper("Producer.Queue"));
57
58     factories = new ArrayList();
59     nameToFactory = new HashMap();
60
61     try {
62       reloadConfiguration();
63     }
64     catch (Throwable t) {
65     }
66   }
67
68   /**
69    * Reloads the producer configuration
70    */
71   public void reloadConfiguration()  throws MirGlobalExc, MirGlobalFailure {
72     try {
73       factories = MirGlobal.localizer().producers().loadFactories();
74
75       synchronized (nameToFactory) {
76         nameToFactory.clear();
77
78         Iterator i = factories.iterator();
79         while (i.hasNext()) {
80           ProducerFactory factory = (ProducerFactory) i.next();
81           nameToFactory.put(factory.getName(), factory);
82         }
83       }
84     }
85     catch (Throwable t) {
86       throw new MirGlobalFailure(t);
87     }
88   }
89
90   /**
91    * Looks up a producer factory by name
92    */
93   private ProducerFactory getFactoryForName(String aName) {
94     synchronized (nameToFactory) {
95       return (ProducerFactory) nameToFactory.get(aName);
96     }
97   }
98
99   /**
100    * Returns all factories
101    */
102   public List getFactories() {
103     return factories;
104   }
105   /**
106    * Adds a producer job to the queue
107    */
108   public void addJob(String aProducerFactory, String aVerb) throws MirGlobalExc, MirGlobalFailure {
109     ProducerFactory factory;
110
111     factory = getFactoryForName( aProducerFactory );
112
113     if (factory==null)
114       throw new MirGlobalExc("Unknown producer: " + aProducerFactory);
115
116     if (!factory.allowVerb(aVerb))
117       throw new MirGlobalExc("illegal producer/verb combination: " + aProducerFactory+"::"+aVerb);
118
119     producerJobQueue.appendJob(
120         new ProducerJob(aProducerFactory, aVerb), aProducerFactory+"."+aVerb);
121   }
122
123   /**
124    * Cancels a list of jobs by job identifier
125    */
126   public void cancelJobs(List aJobs) {
127     producerJobQueue.cancelJobs(aJobs);
128   }
129
130   /**
131    * Cancels all jobs in the queue
132    */
133   public void cancelAllJobs() {
134     producerJobQueue.cancelAllJobs();
135   }
136
137   public void addTask(ProducerTask aTask) throws MirGlobalExc, MirGlobalFailure {
138     addJob(aTask.getProducer(), aTask.getVerb());
139   }
140
141   private String convertStatus(JobQueue.JobInfo aJob) {
142     switch (aJob.getStatus()) {
143       case JobQueue.STATUS_ABORTED:
144         return "aborted";
145       case JobQueue.STATUS_CANCELLED:
146         return "cancelled";
147       case JobQueue.STATUS_CREATED:
148         return "created";
149       case JobQueue.STATUS_PENDING:
150         return "pending";
151       case JobQueue.STATUS_PROCESSED:
152         return "processed";
153       case JobQueue.STATUS_PROCESSING:
154         return "processing";
155     }
156     return "unknown";
157   }
158
159   private Map convertJob(JobQueue.JobInfo aJob) {
160     try {
161       Map result = new HashMap();
162       result.put("identifier", aJob.getIdentifier());
163       result.put("description", aJob.getDescription());
164       result.put("priority", new Integer(aJob.getPriority()));
165       result.put("runningtime", new Double( (double) aJob.getRunningTime() / 1000));
166       result.put("status", convertStatus(aJob));
167       result.put("lastchange", new GeneratorFormatAdapters.DateFormatAdapter(aJob.getLastChange(), MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone")));
168       result.put("finished", new Boolean(
169           aJob.getStatus() == JobQueue.STATUS_PROCESSED ||
170           aJob.getStatus() == JobQueue.STATUS_CANCELLED ||
171           aJob.getStatus() == JobQueue.STATUS_ABORTED));
172
173       return result;
174     }
175     catch (Throwable t) {
176       throw new RuntimeException(t.toString());
177     }
178   }
179
180   private List convertJobInfoList(List aJobInfoList) {
181     List result = new ArrayList();
182
183     Iterator i = aJobInfoList.iterator();
184
185     while (i.hasNext())
186       result.add(convertJob((JobQueue.JobInfo) i.next()));
187
188     return result;
189   }
190
191   public List getQueueStatus() {
192     return convertJobInfoList(producerJobQueue.getJobsInfo());
193   }
194
195   private class ProducerJob implements JobQueue.Job {
196     private String factoryName;
197     private String verb;
198     private Producer producer;
199     private ProductionContext productionContext;
200
201     public ProducerJob(String aFactory, String aVerb) {
202       factoryName = aFactory;
203       verb = aVerb;
204       producer=null;
205     }
206
207     public String getFactoryName() {
208       return factoryName;
209     }
210
211     public String getVerb() {
212       return verb;
213     }
214
215     public void abort() {
216       if (producer!=null && productionContext!=null) {
217         producer.abort(productionContext);
218       }
219     }
220
221     public boolean run() {
222       final ProducerFactory factory;
223       long startTime;
224       long endTime;
225       boolean result = false;
226       final Map startingMap = new HashMap();
227       Map mirMap = new HashMap();
228       mirMap.put("producer", factoryName);
229       mirMap.put("verb", verb);
230
231       startingMap.put("Mir", mirMap);
232
233       startTime = System.currentTimeMillis();
234       logger.info("Producing job: "+factoryName+"."+verb);
235
236       try {
237         factory = getFactoryForName(factoryName);
238
239         if (factory!=null) {
240           MirGlobal.localizer().producerAssistant().initializeGenerationValueSet(startingMap);
241
242           synchronized(factory) {
243             producer = factory.makeProducer(verb, startingMap);
244           }
245
246           if (producer!=null) {
247             try {
248               MirGlobal.localizer().producers().beforeProducerTask(factoryName, verb);
249             }
250             catch (Throwable t) {
251               logger.warn("Misbehaving beforeProducerTask",t );
252             }
253
254             productionContext = new ProductionContext() {
255               public ProducerFactory getFactory() {
256                 return factory;
257               }
258
259               public Producer getProducer() {
260                 return producer;
261               }
262
263               public String getVerb() {
264                 return verb;
265               }
266
267               public LoggerWrapper getLogger() {
268                 return logger;
269               }
270
271               public Map getValueSet() {
272                 return startingMap;
273               }
274             };
275             result = producer.execute(productionContext);
276             try {
277               MirGlobal.localizer().producers().afterProducerTask(factoryName, verb);
278             }
279             catch (Throwable t) {
280               logger.warn("Misbehaving afterProducerTask", t);
281             }
282           }
283         }
284       }
285       catch (Throwable t) {
286         logger.error("Exception occurred while producing " + factoryName + "." + verb + t.getMessage());
287         t.printStackTrace(new PrintWriter(new LoggerToWriterAdapter(logger, LoggerWrapper.ERROR_MESSAGE)));
288       }
289       endTime = System.currentTimeMillis();
290       logger.info("Done producing job: " + factoryName + "." + verb + ", time elapsed:" + (endTime-startTime) + " ms");
291
292       return result;
293     }
294
295     boolean isAborted() {
296       return false;
297     }
298   }
299
300   public static class ProducerTask {
301     private String producer;
302     private String verb;
303
304     public ProducerTask(String aProducer, String aVerb) {
305       producer = aProducer;
306       verb = aVerb;
307     }
308
309     public String getVerb() {
310       return verb;
311     }
312
313     public String getProducer() {
314       return producer;
315     }
316
317     public static List parseProducerTaskList(String aList) throws MirGlobalExc {
318       Iterator i;
319       List result = new ArrayList();
320
321       i = StringRoutines.splitString(aList, ";").iterator();
322       while (i.hasNext()) {
323         String taskExpression = ((String) i.next()).trim();
324
325         if (taskExpression.length()>0) {
326           List parts = StringRoutines.splitString(taskExpression, ".");
327
328           if (parts.size() != 2)
329             throw new MirGlobalExc("Invalid producer expression: '" + taskExpression + "'");
330           result.add(new ProducerEngine.ProducerTask( (String) parts.get(0), (String) parts.get(1)));
331         }
332       }
333
334       return result;
335     }
336   }
337 }