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