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