1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache license, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * 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 package org.apache.logging.log4j.core.appender.rolling.action;
18
19 import java.io.IOException;
20
21 import org.apache.logging.log4j.Logger;
22 import org.apache.logging.log4j.status.StatusLogger;
23
24
25 /**
26 * Abstract base class for implementations of Action.
27 */
28 public abstract class AbstractAction implements Action {
29
30 /**
31 * Allows subclasses access to the status logger without creating another instance.
32 */
33 protected static final Logger LOGGER = StatusLogger.getLogger();
34 /**
35 * Is action complete.
36 */
37 private boolean complete = false;
38
39 /**
40 * Is action interrupted.
41 */
42 private boolean interrupted = false;
43
44 /**
45 * Constructor.
46 */
47 protected AbstractAction() {
48 }
49
50 /**
51 * Performs action.
52 *
53 * @return true if successful.
54 * @throws IOException if IO error.
55 */
56 @Override
57 public abstract boolean execute() throws IOException;
58
59 /**
60 * {@inheritDoc}
61 */
62 @Override
63 public synchronized void run() {
64 if (!interrupted) {
65 try {
66 execute();
67 } catch (final RuntimeException | IOException ex) {
68 reportException(ex);
69 } catch (final Error e) {
70 // reportException takes Exception, widening to Throwable would break custom implementations
71 // so we wrap Errors in RuntimeException for handling.
72 reportException(new RuntimeException(e));
73 }
74
75 complete = true;
76 interrupted = true;
77 }
78 }
79
80 /**
81 * {@inheritDoc}
82 */
83 @Override
84 public synchronized void close() {
85 interrupted = true;
86 }
87
88 /**
89 * Tests if the action is complete.
90 *
91 * @return true if action is complete.
92 */
93 @Override
94 public boolean isComplete() {
95 return complete;
96 }
97
98 public boolean isInterrupted() {
99 return interrupted;
100 }
101
102 /**
103 * Captures exception.
104 *
105 * @param ex exception.
106 */
107 protected void reportException(final Exception ex) {
108 LOGGER.warn("Exception reported by action '{}'", getClass(), ex);
109 }
110
111 }