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