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