001 package de.mospace.lang;
002
003 /* Mp3dings - manage mp3 meta-information
004 * Copyright (C) 2006 Moritz Ringler
005 * $Id: RunnableQueue.java 69 2007-10-24 21:57:43Z ringler $
006 *
007 * This program is free software; you can redistribute it and/or
008 * modify it under the terms of the GNU General Public License
009 * as published by the Free Software Foundation; either version 2
010 * of the License, or (at your option) any later version.
011 *
012 * This program is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
015 * GNU General Public License for more details.
016 *
017 * You should have received a copy of the GNU General Public License
018 * along with this program; if not, write to the Free Software
019 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
020 */
021 import java.awt.EventQueue;
022 import java.io.IOException;
023 import java.io.InputStream;
024 import java.io.OutputStream;
025 import java.io.PipedInputStream;
026 import java.io.PipedOutputStream;
027 import java.lang.reflect.InvocationTargetException;
028 import java.util.Collections;
029 import java.util.Iterator;
030 import java.util.List;
031 import java.util.Vector;
032 import java.util.logging.Logger;
033 import javax.swing.SwingUtilities;
034 import javax.swing.event.ChangeEvent;
035 import javax.swing.event.ChangeListener;
036 import javax.swing.event.EventListenerList;
037
038 /** A queue for Runnables that adhere to the {@link Job} interface,
039 * enqueued jobs are run one after the other in the order in which they have
040 * been enqueued.
041 * @see java.lang.Runnable
042 **/
043 public class RunnableQueue implements Runnable{
044 private static final Logger logger = Logger.getLogger(RunnableQueue.class.getPackage().getName());
045 /** A Runnable that can be enqueued to a RunnableQueue. */
046 public static interface Job extends Runnable{
047 /** Returns the exit status of this job. Should be zero by default and
048 * before the job has run.
049 * @return the exit status of this job
050 */
051 public int getExitStatus();
052
053 /** Requests that this job stops executing if it is currently running.
054 * This method will usually be called on another thread than
055 * <code>run()</code>. Implementations may choose to ignore this.
056 */
057 public void stop();
058
059 /** Returns whether this job currently has a non-null input.
060 * Jobs that don't require any input should always return
061 * <code>true</code>.
062 * @return whether this job has a non-null input
063 * @see #readInputFrom(InputStream)
064 */
065 public boolean hasInput();
066
067 /** Requests that this job reads any input it needs
068 * from the specified stream. Jobs that don't require any input may
069 * ignore this.
070 * @param stream the stream to read input from
071 */
072 public void readInputFrom(InputStream stream);
073
074 /** Registers an exception handler to deal with exceptions
075 * thrown within the <code>run()</code> method. By default any exceptions
076 * thrown within run should be re-thrown as RuntimeExceptions.
077 * @param eh an exception handler
078 */
079 public void registerExceptionHandler(ExceptionHandler eh);
080 }
081
082 private ExceptionHandler eh = new ExceptionHandler(){
083 public void handleException(Throwable e){
084 //does nothing.
085 }
086 };
087 private List jobs;
088 private Job job;
089 private OutputStream inputSink;
090 private boolean goon = true;
091 private int lastExitStatus;
092 private final Runnable fireStateChange = new Runnable(){
093 public void run(){
094 fireStateChanged();
095 }
096 };
097 private final ThreadGroup tg = new ThreadGroup(
098 "RunnableQueueThreadGroup"+
099 this.toString()
100 ){
101 public void uncaughtException(Thread t, Throwable e){
102 eh.handleException(e);
103 }
104 };
105
106 /** Executes this queue. Jobs will be run one after the other in the
107 * order in which they have been enqueued.
108 * @throws IllegalStateException when this queue is already running
109 */
110 public void run(){
111 if(isRunning()){
112 throw new
113 IllegalStateException("Runnable queue is already running");
114 }
115 goon = true;
116 job = getNextRunnable();
117 /* fire events on the event dispatching thread */
118 if (EventQueue.isDispatchThread()) {
119 fireStateChanged();
120 } else {
121 try{
122 SwingUtilities.invokeAndWait(fireStateChange);
123 } catch (InterruptedException ex){
124 throw new Error(ex);
125 } catch (InvocationTargetException ex){
126 throw new Error(ex);
127 }
128 }
129 while(goon && job != null){
130 jobs.remove(0);
131 if(job.hasInput()){
132 inputSink = null;
133 job.run();
134 } else {
135 PipedOutputStream pipeo = null;
136 PipedInputStream pipei = null;
137 try{
138 pipeo = new PipedOutputStream();
139 try{
140 pipei = new PipedInputStream(pipeo);
141 try {
142 job.readInputFrom(pipei);
143 inputSink = pipeo;
144 job.run();
145 } finally {
146 inputSink = null;
147 pipei.close();
148 }
149 } finally {
150 pipeo.close();
151 }
152 } catch (IOException ex){
153 logger.severe(ex.toString());
154 }
155 }
156 lastExitStatus = job.getExitStatus();
157 job = getNextRunnable();
158 }
159 goon = false;
160 job = null;
161 jobs.clear();
162 /* fire events on the event dispatching thread */
163 if (EventQueue.isDispatchThread()) {
164 fireStateChanged();
165 } else {
166 try{
167 SwingUtilities.invokeAndWait(fireStateChange);
168 } catch (InterruptedException ex){
169 //ignore
170 logger.warning(ex.toString());
171 } catch (InvocationTargetException ex){
172 //cannot happen
173 throw new Error(ex);
174 }
175 }
176 }
177
178 private Thread createThread(){
179 return new Thread(
180 tg,
181 "RunnableQueueThread:"+this.toString()
182 ){
183 public void run(){
184 RunnableQueue.this.run();
185 }
186 };
187 }
188
189 /** Creates a new RunnableQueue with the specified jobs.
190 * @param commands an array of non-null jobs to initialize the queue with
191 */
192 public RunnableQueue(Job[] commands){
193 if (commands != null){
194 for(int i=0; i<commands.length; i++){
195 enqueueImpl(commands[i]);
196 }
197 }
198 }
199
200 /** Creates a new RunnableQueue with no jobs. */
201 public RunnableQueue(){
202 this(null);
203 }
204
205 /** Registers an exception handler for all jobs in this queue
206 * and for all threads started with this queue's {@link #start}
207 * method.
208 * @param xh an exception handler
209 * @see Job#registerExceptionHandler
210 */
211 public void registerExceptionHandler(ExceptionHandler xh){
212 eh = xh;
213 if(jobs != null){
214 synchronized(jobs) {
215 Iterator i = jobs.iterator(); // Must be in synchronized block
216 while (i.hasNext()){
217 ((Job) i.next()).registerExceptionHandler(xh);
218 }
219 }
220 }
221 }
222
223 /** Returns the job that will next start executing.
224 * @return the job that will next start executing
225 * or <code>null</code> if no job is awaiting execution in the queue
226 */
227 public Job getNextRunnable(){
228 if(jobs == null || jobs.isEmpty()){
229 return null;
230 } else {
231 return (Job) jobs.get(0);
232 }
233 }
234
235 /** Returns the currently running job.
236 * @return the currently running job from this queue or <code>null</code>
237 * if no job is running. **/
238 public Job getRunningRunnable(){
239 return job;
240 }
241
242 /** Adds a new job to the end of this queue. If this queue is currently
243 * running then this job will be executed once the currently running job
244 * and the jobs enqueued before it have terminated. If this queue is not
245 * running then this job will not be executed unless {@link #run} or
246 * {@link #start} is called.
247 * @param p the job to add to the queue
248 */
249 public void enqueue(Job p){
250 enqueueImpl(p);
251 }
252
253 private void enqueueImpl(Job p){
254 if(jobs == null){
255 jobs = Collections.synchronizedList(new Vector());
256 }
257 p.registerExceptionHandler(eh);
258 jobs.add(p);
259 }
260
261 /** Removes the first occurrence in this queue of the
262 * specified job. If this queue does not contain the element,
263 * it is unchanged.
264 * @param p the job to dequeue
265 * @see java.util.List#remove(Object)
266 * @return true if the job was in the queue, false otherwise
267 **/
268 public boolean dequeue(Job p){
269 return jobs.remove(p);
270 }
271
272 /** Returns whether this queue is currently running.
273 * @return whether this queue is currently running
274 */
275 public boolean isRunning(){
276 return (job != null);
277 }
278
279 /** Starts to execute this queue in a new thread.
280 * @throws IllegalStateException when this queue is already running
281 */
282 public void start(){
283 createThread().start();
284 }
285
286 /** Stops the currently running job in this queue. If there are further
287 * jobs in the queue then these will be executed.
288 * @see Job#stop
289 */
290 public void stop(){
291 if (isRunning()){
292 job.stop();
293 }
294 }
295
296 /** Stops execution of this queue. The currently running job will be
297 * stopped and further jobs in the queue will not be executed and
298 * remain queued.
299 * @see Job#stop
300 */
301 public void interrupt(){
302 if (isRunning()){
303 job.stop();
304 goon = false;
305 }
306 }
307
308 /** Removes all jobs from the queue. Does not stop a currently running job.
309 */
310 public void clear(){
311 jobs.clear();
312 }
313
314 /** Forwards text input to the currently running job if it does not have
315 * another source of input.
316 * @param input text input for the currently running job
317 * @see Job#hasInput
318 */
319 public void handleInput(String input) throws IOException{
320 if (inputSink != null){
321 inputSink.write(input.getBytes());
322 inputSink.flush();
323 }
324 }
325
326 /* Event generation and listener management */
327 EventListenerList listenerList = new EventListenerList();
328 ChangeEvent changeEvent = null;
329
330 /** Registers a listener that will be notified whenever this runnable
331 * queue starts or stops executing. A listener can differentiate the two cases
332 * by calling <code>event.getSource().isRunning()</code>, this will return
333 * true iff the queue has started.
334 * @param l a change listener to be notified of future changes in this
335 * queue's state
336 */
337 public void addChangeListener(ChangeListener l) {
338 listenerList.add(ChangeListener.class, l);
339 }
340
341 /** Requests that the specified listener no longer be notified when this
342 * runnable queue starts or stops executing.
343 * @param l the change listener to remove
344 */
345 public void removeChangeListener(ChangeListener l) {
346 listenerList.remove(ChangeListener.class, l);
347 }
348
349 /** Notifies all registered listeners that this runnable
350 * queue has started or stopped executing.
351 * A listener can differentiate the two cases
352 * by calling <code>event.getSource().isRunning()</code>, this will return
353 * true iff the queue has started.
354 */
355 protected void fireStateChanged() {
356 // Guaranteed to return a non-null array
357 Object[] listeners = listenerList.getListenerList();
358 // Process the listeners last to first, notifying
359 // those that are interested in this event
360 for (int i = listeners.length-2; i>=0; i-=2) {
361 if (listeners[i] == ChangeListener.class) {
362 // Lazily create the event:
363 if (changeEvent == null){
364 changeEvent = new ChangeEvent(this);
365 }
366 ((ChangeListener)listeners[i+1]).stateChanged(changeEvent);
367 }
368 }
369 }
370 }