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