01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: *
17: */
18: package org.apache.tools.ant.util;
19:
20: import java.io.IOException;
21:
22: import org.apache.tools.ant.Project;
23: import org.apache.tools.ant.Task;
24:
25: /**
26: * A simple utility class to take a piece of code (that implements
27: * <code>Retryable</code> interface) and executes that with possibility to
28: * retry the execution in case of IOException.
29: */
30: public class RetryHandler {
31:
32: private int retriesAllowed = 0;
33: private Task task;
34:
35: /**
36: * Create a new RetryingHandler.
37: *
38: * @param retriesAllowed how many times to retry
39: * @param task the Ant task that is is executed from, used for logging only
40: */
41: public RetryHandler(int retriesAllowed, Task task) {
42: this .retriesAllowed = retriesAllowed;
43: this .task = task;
44: }
45:
46: /**
47: * Execute the <code>Retryable</code> code with specified number of retries.
48: *
49: * @param exe the code to execute
50: * @param desc some descriptive text for this piece of code, used for logging
51: * @throws IOException if the number of retries has exceeded the allowed limit
52: */
53: public void execute(Retryable exe, String desc) throws IOException {
54: int retries = 0;
55: while (true) {
56: try {
57: exe.execute();
58: break;
59: } catch (IOException e) {
60: retries++;
61: if (retries > this .retriesAllowed
62: && this .retriesAllowed > -1) {
63: task.log("try #" + retries + ": IO error (" + desc
64: + "), number of maximum retries reached ("
65: + this .retriesAllowed + "), giving up",
66: Project.MSG_WARN);
67: throw e;
68: } else {
69: task.log("try #" + retries + ": IO error (" + desc
70: + "), retrying", Project.MSG_WARN);
71: }
72: }
73: }
74: }
75:
76: }
|