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