View Javadoc

1   /*
2    * Copyright 1999,2005 The Apache Software Foundation.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.apache.log4j.rolling.helper;
18  
19  import java.io.IOException;
20  
21  import java.util.List;
22  import org.apache.log4j.helpers.LogLog;
23  
24  
25  /***
26   * A group of Actions to be executed in sequence.
27   *
28   * @author Curt Arnold
29   *
30   */
31  public class CompositeAction extends ActionBase {
32    /***
33     * Actions to perform.
34     */
35    private final Action[] actions;
36  
37    /***
38     * Stop on error.
39     */
40    private final boolean stopOnError;
41  
42    /***
43     * Construct a new composite action.
44     * @param actions list of actions, may not be null.
45     * @param stopOnError if true, stop on the first false return value or exception.
46     */
47    public CompositeAction(final List actions, 
48                           final boolean stopOnError) {
49      this.actions = new Action[actions.size()];
50      actions.toArray(this.actions);
51      this.stopOnError = stopOnError;
52    }
53  
54    /***
55     * {@inheritDoc}
56     */
57    public void run() {
58      try {
59        execute();
60      } catch (IOException ex) {
61           LogLog.warn("Exception during file rollover.", ex);
62      }
63    }
64  
65    /***
66     * Execute sequence of actions.
67     * @return true if all actions were successful.
68     * @throws IOException on IO error.
69     */
70    public boolean execute() throws IOException {
71      if (stopOnError) {
72        for (int i = 0; i < actions.length; i++) {
73          if (!actions[i].execute()) {
74            return false;
75          }
76        }
77  
78        return true;
79      } else {
80        boolean status = true;
81        IOException exception = null;
82  
83        for (int i = 0; i < actions.length; i++) {
84          try {
85            status &= actions[i].execute();
86          } catch (IOException ex) {
87            status = false;
88  
89            if (exception == null) {
90              exception = ex;
91            }
92          }
93        }
94  
95        if (exception != null) {
96          throw exception;
97        }
98  
99        return status;
100     }
101   }
102 }