code cleaning, new config
[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 the com.oreilly.servlet library, any library
22  * licensed under the Apache Software License, The Sun (tm) Java Advanced
23  * Imaging library (JAI), The Sun JIMI library (or with modified versions of
24  * the above that use the same license as the above), and distribute linked
25  * combinations including the two.  You must obey the GNU General Public
26  * License in all respects for all of the code used other than the above
27  * mentioned libraries.  If you modify this file, you may extend this exception
28  * to your version of the file, but you are not obligated to do so.  If you do
29  * not wish to do so, delete this exception statement from your version.
30  */
31
32 package mircoders.global;
33
34 import java.io.PrintWriter;
35 import java.util.HashMap;
36 import java.util.Iterator;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.Vector;
40
41 import mir.log.LoggerToWriterAdapter;
42 import mir.log.LoggerWrapper;
43 import mir.producer.Producer;
44 import mir.producer.ProducerFactory;
45 import mir.util.DateToMapAdapter;
46 import mir.util.StringRoutines;
47 import multex.Exc;
48 import multex.Failure;
49
50 public class ProducerEngine {
51 //  private Map producers;
52   private JobQueue producerJobQueue;
53   private Thread queueThread;
54   private LoggerWrapper logger;
55
56
57   protected ProducerEngine() {
58     producerJobQueue = new JobQueue();
59     logger = new LoggerWrapper("Producer");
60
61     queueThread = new Thread(new ProducerJobQueueThread());
62     queueThread.start();
63   }
64
65   public void addJob(String aProducerFactory, String aVerb) {
66     producerJobQueue.appendJob(new ProducerJob(aProducerFactory, aVerb));
67   }
68
69   public void addTask(ProducerTask aTask) {
70     addJob(aTask.getProducer(), aTask.getVerb());
71   }
72
73   public void addTasks(List aTasks) {
74     Iterator i = aTasks.iterator();
75
76     while (i.hasNext()) {
77       addTask((ProducerTask) i.next());
78     }
79   }
80
81   private String convertStatus(JobQueue.Job aJob) {
82     if (aJob.hasBeenProcessed())
83       return "processed";
84     if (aJob.isProcessing())
85       return "processing";
86     if (aJob.isPending())
87       return "pending";
88     if (aJob.isCancelled())
89       return "cancelled";
90     if (aJob.hasBeenAborted())
91       return "aborted";
92
93     return "unknown";
94   }
95
96   private Map convertJob(JobQueue.Job aJob) {
97     Map result = new HashMap();
98     ProducerJob producerJob = (ProducerJob) aJob.getData();
99
100     result.put("identifier", aJob.getIdentifier());
101     result.put("factory", producerJob.getFactoryName());
102     result.put("verb", producerJob.getVerb());
103     result.put("priority", new Integer(aJob.getPriority()));
104     result.put("status", convertStatus(aJob));
105     result.put("lastchange", new DateToMapAdapter(aJob.getLastChange()));
106
107     return result;
108   }
109
110   private void convertJobList(List aSourceJobList, List aDestination) {
111     Iterator i = aSourceJobList.iterator();
112
113     while (i.hasNext())
114       aDestination.add(convertJob((JobQueue.Job) i.next()));
115   }
116
117   public List getQueueStatus() {
118     List result = new Vector();
119     List pendingJobs = new Vector();
120     List finishedJobs = new Vector();
121
122     producerJobQueue.makeJobListSnapshots(pendingJobs, finishedJobs);
123
124     convertJobList(pendingJobs, result);
125     convertJobList(finishedJobs, result);
126
127     return result;
128   }
129
130 private class ProducerJob {
131     private String factoryName;
132     private String verb;
133     private Producer producer;
134
135     public ProducerJob(String aFactory, String aVerb) {
136       factoryName = aFactory;
137       verb = aVerb;
138       producer=null;
139     }
140
141     public String getFactoryName() {
142       return factoryName;
143     }
144
145     public String getVerb() {
146       return verb;
147     }
148
149     public void abort() {
150       if (producer!=null) {
151         producer.abort();
152       }
153     }
154
155     public void execute() {
156       ProducerFactory factory;
157       long startTime;
158       long endTime;
159       Map startingMap = new HashMap();
160
161       startTime = System.currentTimeMillis();
162       logger.info("Producing job: "+factoryName+"."+verb);
163
164       try {
165         factory = MirGlobal.localizer().producers().getFactoryForName( factoryName );
166
167         if (factory!=null) {
168           MirGlobal.localizer().producerAssistant().initializeGenerationValueSet(startingMap);
169
170           synchronized(factory) {
171             producer = factory.makeProducer(verb, startingMap);
172           }
173           if (producer!=null) {
174             producer.produce(logger);
175           }
176         }
177       }
178       catch (Throwable t) {
179         logger.error("Exception occurred while producing " + factoryName + "." + verb + t.getMessage());
180         t.printStackTrace(new PrintWriter(new LoggerToWriterAdapter(logger, LoggerWrapper.ERROR_MESSAGE)));
181       }
182       endTime = System.currentTimeMillis();
183       logger.info("Done producing job: " + factoryName + "." + verb + ", time elapsed:" + (endTime-startTime) + " ms");
184     }
185
186     boolean isAborted() {
187       return false;
188     }
189   }
190
191   private class ProducerJobQueueThread implements Runnable {
192     public void run() {
193       logger.debug("starting ProducerJobQueueThread");
194
195       while (true) {
196         ProducerJob job = (ProducerJob) producerJobQueue.acquirePendingJob();
197         if (job!=null) {
198           job.execute();
199           if (job.isAborted())
200             producerJobQueue.jobAborted(job);
201           else
202             producerJobQueue.jobProcessed(job);
203         }
204         else
205         {
206           try {
207             Thread.sleep(1500);
208           }
209           catch (InterruptedException e) {
210           }
211         }
212       }
213     }
214   }
215
216   public static class ProducerEngineExc extends Exc {
217     public ProducerEngineExc(String aMessage) {
218       super(aMessage);
219     }
220   }
221
222   public static class ProducerEngineRuntimeExc extends Failure {
223     public ProducerEngineRuntimeExc(String msg, Exception cause){
224       super(msg,cause);
225     }
226   }
227
228   public static class ProducerTask {
229     private String producer;
230     private String verb;
231
232     public ProducerTask(String aProducer, String aVerb) {
233       producer = aProducer;
234       verb = aVerb;
235     }
236
237     public String getVerb() {
238       return verb;
239     }
240
241     public String getProducer() {
242       return producer;
243     }
244
245     public static List parseProducerTaskList(String aList) throws ProducerEngineExc {
246       Iterator i;
247       List result = new Vector();
248
249       i = StringRoutines.splitString(aList, ";").iterator();
250       while (i.hasNext()) {
251         String taskExpression = (String) i.next();
252         List parts = StringRoutines.splitString(taskExpression, ".");
253
254         if (parts.size()!=2)
255           throw new ProducerEngineExc("Invalid producer expression: '" + taskExpression + "'");
256         else
257           result.add(new ProducerEngine.ProducerTask((String) parts.get(0), (String) parts.get(1)));
258       }
259
260       return result;
261     }
262   }
263 }