summaryrefslogtreecommitdiffstats
path: root/src/main/java/net/sf/antcontrib/process/Limit.java
blob: b9cd7df2d71198c3dbb88f83e86a95a4484b7218 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402

/*
* Copyright (c) 2001-2004 Ant-Contrib project.  All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.antcontrib.process;


import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;


import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.TaskContainer;
import org.apache.tools.ant.types.EnumeratedAttribute;


/**
 * Limits the amount of time that a task or set of tasks can run. This is useful
 * for tasks that may "hang" or otherwise not complete in a timely fashion. This
 * task is done when either the maxwait time has expired or all nested tasks are
 * complete, whichever is first.
 *
 * <p>Developed for use with Antelope, migrated to ant-contrib Oct 2003.
 *
 * @author    Dale Anson
 * @author    Robert D. Rice
 * @version   $Revision: 1.6 $
 * @since Ant 1.5
 */
public class Limit extends Task implements TaskContainer {


   // storage for nested tasks
   private Vector tasks = new Vector();


   // time units, default value is 3 minutes.
   private long maxwait = 180;
   protected TimeUnit unit = TimeUnit.SECOND_UNIT;

   // property to set if time limit is reached
   private String timeoutProperty = null;
   private String timeoutValue = "true";


   // storage for task currently executing
   private Task currentTask = null;


   // used to control thread stoppage
   private Thread taskRunner = null;


   // should the build fail if the time limit has expired? Default is no.
   private boolean failOnError = false;


   private Exception exception = null;




   /**
    * Add a task to wait on.
    *
    * @param task                A task to execute
    * @exception BuildException  won't happen
    */
   public void addTask( Task task ) throws BuildException {
      tasks.addElement( task );
   }




   /**
    * How long to wait for all nested tasks to complete, in units. 
    * Default is to wait 3 minutes.
    *
    * @param wait  time to wait, set to 0 to wait forever.
    */
   public void setMaxwait( int wait ) {
      maxwait = wait;
   }

   /**
    * Sets the unit for the max wait. Default is minutes.

    * @param unit valid values are "millisecond", "second", "minute", "hour", "day", and "week".

    */
   public void setUnit( String unit ) {
      if ( unit == null )
         return ;
      if ( unit.equals( TimeUnit.SECOND ) ) {
         setMaxWaitUnit( TimeUnit.SECOND_UNIT );
         return ;
      }
      if ( unit.equals( TimeUnit.MILLISECOND ) ) {
         setMaxWaitUnit( TimeUnit.MILLISECOND_UNIT );
         return ;
      }
      if ( unit.equals( TimeUnit.MINUTE ) ) {
         setMaxWaitUnit( TimeUnit.MINUTE_UNIT );
         return ;
      }
      if ( unit.equals( TimeUnit.HOUR ) ) {
         setMaxWaitUnit( TimeUnit.HOUR_UNIT );
         return ;
      }
      if ( unit.equals( TimeUnit.DAY ) ) {
         setMaxWaitUnit( TimeUnit.DAY_UNIT );
         return ;
      }
      if ( unit.equals( TimeUnit.WEEK ) ) {
         setMaxWaitUnit( TimeUnit.WEEK_UNIT );
         return ;
      }

   }

   /**
    * Set a millisecond wait value.
    * @param value the number of milliseconds to wait.
    */
   public void setMilliseconds( int value ) {
      setMaxwait( value );
      setMaxWaitUnit( TimeUnit.MILLISECOND_UNIT );
   }

   /**
    * Set a second wait value.
    * @param value the number of seconds to wait.
    */
   public void setSeconds( int value ) {
      setMaxwait( value );
      setMaxWaitUnit( TimeUnit.SECOND_UNIT );
   }

   /**
    * Set a minute wait value.
    * @param value the number of milliseconds to wait.
    */
   public void setMinutes( int value ) {
      setMaxwait( value );
      setMaxWaitUnit( TimeUnit.MINUTE_UNIT );
   }

   /**
    * Set an hours wait value.
    * @param value the number of hours to wait.
    */
   public void setHours( int value ) {
      setMaxwait( value );
      setMaxWaitUnit( TimeUnit.HOUR_UNIT );
   }

   /**
    * Set a day wait value.
    * @param value the number of days to wait.
    */
   public void setDays( int value ) {
      setMaxwait( value );
      setMaxWaitUnit( TimeUnit.DAY_UNIT );
   }

   /**
    * Set a week wait value.
    * @param value the number of weeks to wait.
    */
   public void setWeeks( int value ) {
      setMaxwait( value );
      setMaxWaitUnit( TimeUnit.WEEK_UNIT );
   }

   /**
    * Set the max wait time unit, default is minutes.
    */
   public void setMaxWaitUnit( TimeUnit unit ) {
      this.unit = unit;
   }


   /**
    * Determines whether the build should fail if the time limit has
    * expired on this task.
    * Default is no.
    *
    * @param fail  if true, fail the build if the time limit has been reached.
    */
   public void setFailonerror( boolean fail ) {
      failOnError = fail;
   }


   /**
    * Name the property to set after a timeout.
    *
    * @param p of property to set if the time limit has been reached.
    */
   public void setProperty( String p ) {
      timeoutProperty = p;
   }


   /**
    * The value for the property to set after a timeout, defaults to true.
    *
    * @param v for the property to set if the time limit has been reached.
    */
   public void setValue( String v ) {
      timeoutValue = v;
   }


   /**
    * Execute all nested tasks, but stopping execution of nested tasks after
    * maxwait or when all tasks are done, whichever is first.
    *
    * @exception BuildException  Description of the Exception
    */
   public void execute() throws BuildException {
      try {
         // start executing nested tasks
         final Thread runner =
            new Thread() {
               public void run() {
                  Enumeration e = tasks.elements();
                  while ( e.hasMoreElements() ) {
                     if ( taskRunner != this ) {
                        break;
                     }
                     currentTask = ( Task ) e.nextElement();
                     try {
                        currentTask.perform();
                     }
                     catch ( Exception ex ) {
                        if ( failOnError ) {
                           exception = ex;
                           return ;
                        }
                        else {
                           exception = ex;
                        }
                     }
                  }
               }
            };
         taskRunner = runner;
         runner.start();
         runner.join( unit.toMillis( maxwait ) );


         // stop executing the nested tasks
         if ( runner.isAlive() ) {
            taskRunner = null;
            runner.interrupt();
            int index = tasks.indexOf( currentTask );
            StringBuffer not_ran = new StringBuffer();
            for ( int i = index + 1; i < tasks.size(); i++ ) {
               not_ran.append( '<' ).append( ( ( Task ) tasks.get( i ) ).getTaskName() ).append( '>' );
               if ( i < tasks.size() - 1 ) {
                  not_ran.append( ", " );
               }
            }


            // maybe set timeout property
            if ( timeoutProperty != null ) {
               getProject().setNewProperty( timeoutProperty, timeoutValue );
            }


            // create output message
            StringBuffer msg = new StringBuffer();
            msg.append( "Interrupted task <" )
            .append( currentTask.getTaskName() )
            .append( ">. Waited " )
            .append( ( maxwait ) ).append( " " ).append( unit.getValue() )
            .append( ", but this task did not complete." )
            .append( ( not_ran.length() > 0 ?
                  " The following tasks did not execute: " + not_ran.toString() + "." :
                  "" ) );


            // deal with it
            if ( failOnError ) {
               throw new BuildException( msg.toString() );
            }
            else {
               log( msg.toString() );
            }
         }
         else if ( failOnError && exception != null ) {
            throw new BuildException( exception );
         }
      }
      catch ( Exception e ) {
         throw new BuildException( e );
      }
   }


   /**
    * The enumeration of units:
    * millisecond, second, minute, hour, day, week
    * Todo: we use timestamps in many places, why not factor this out
    */
   public static class TimeUnit extends EnumeratedAttribute {

      public static final String MILLISECOND = "millisecond";
      public static final String SECOND = "second";
      public static final String MINUTE = "minute";
      public static final String HOUR = "hour";
      public static final String DAY = "day";
      public static final String WEEK = "week";

      /** static unit objects, for use as sensible defaults */
      public static final TimeUnit MILLISECOND_UNIT =
         new TimeUnit( MILLISECOND );
      public static final TimeUnit SECOND_UNIT =
         new TimeUnit( SECOND );
      public static final TimeUnit MINUTE_UNIT =
         new TimeUnit( MINUTE );
      public static final TimeUnit HOUR_UNIT =
         new TimeUnit( HOUR );
      public static final TimeUnit DAY_UNIT =
         new TimeUnit( DAY );
      public static final TimeUnit WEEK_UNIT =
         new TimeUnit( WEEK );


      private static final String[] units = {
               MILLISECOND, SECOND, MINUTE, HOUR, DAY, WEEK
            };

      private Hashtable timeTable = new Hashtable();

      public TimeUnit() {
         timeTable.put( MILLISECOND, new Long( 1L ) );
         timeTable.put( SECOND, new Long( 1000L ) );
         timeTable.put( MINUTE, new Long( 1000L * 60L ) );
         timeTable.put( HOUR, new Long( 1000L * 60L * 60L ) );
         timeTable.put( DAY, new Long( 1000L * 60L * 60L * 24L ) );
         timeTable.put( WEEK, new Long( 1000L * 60L * 60L * 24L * 7L ) );
      }

      /**
       * private constructor
       * used for static construction of TimeUnit objects.
       * @param value String representing the value.
       */
      private TimeUnit( String value ) {
         this( );
         setValueProgrammatically( value );
      }

      /**
       * set the inner value programmatically.
       * @param value to set
       */
      protected void setValueProgrammatically( String value ) {
         this.value = value;
      }

      public long getMultiplier() {
         String key = getValue().toLowerCase();
         Long l = ( Long ) timeTable.get( key );
         return l.longValue();
      }

      public String[] getValues() {
         return units;
      }

      /**
       * convert the time in the current unit, to millis
       * @param numberOfUnits long expressed in the current objects units
       * @return long representing the value in millis
       */
      public long toMillis( long numberOfUnits ) {
         return numberOfUnits * getMultiplier( );
      }
   }
}