Debian Codegraph @

src/main/java/com/jcabi/aspects/aj/Repeater.java

raw
1 /**
2 * Copyright (c) 2012-2017, jcabi.com
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met: 1) Redistributions of source code must retain the above
8 * copyright notice, this list of conditions and the following
9 * disclaimer. 2) Redistributions in binary form must reproduce the above
10 * copyright notice, this list of conditions and the following
11 * disclaimer in the documentation and/or other materials provided
12 * with the distribution. 3) Neither the name of the jcabi.com nor
13 * the names of its contributors may be used to endorse or promote
14 * products derived from this software without specific prior written
15 * permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
19 * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
20 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
21 * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
22 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
28 * OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30 package com.jcabi.aspects.aj;
31
32 import com.jcabi.aspects.Immutable;
33 import com.jcabi.aspects.RetryOnFailure;
34 import com.jcabi.aspects.Tv;
35 import com.jcabi.log.Logger;
36 import java.lang.reflect.Method;
37 import java.security.SecureRandom;
38 import java.util.Random;
39 import org.aspectj.lang.ProceedingJoinPoint;
40 import org.aspectj.lang.annotation.Around;
41 import org.aspectj.lang.annotation.Aspect;
42 import org.aspectj.lang.reflect.MethodSignature;
43
44 /**
45 * Repeat execution in case of exception.
46 *
47 * @author Yegor Bugayenko ([email protected])
48 * @version $Id: fe039fc8ea2889715377bc94b2d8bbddcb1579c2 $
49 * @since 0.1.10
50 * @see com.jcabi.aspects.RetryOnFailure
51 */
52 @Aspect
53 @Immutable
54 public final class Repeater {
55
56 /**
57 * Pseudo random number generator.
58 */
59 private static final Random RAND = new SecureRandom();
60
61 /**
62 * Catch exception and re-call the method.
63 * @param point Joint point
64 * @return The result of call
65 * @throws Throwable If something goes wrong inside
66 * @checkstyle IllegalThrows (6 lines)
67 * @checkstyle LineLength (4 lines)
68 * @checkstyle ExecutableStatementCountCheck (100 lines)
69 */
70 @Around("execution(* * (..)) && @annotation(com.jcabi.aspects.RetryOnFailure)")
71 @SuppressWarnings("PMD.AvoidCatchingThrowable")
72 public Object wrap(final ProceedingJoinPoint point) throws Throwable {
73 final Method method = MethodSignature.class
74 .cast(point.getSignature())
75 .getMethod();
76 final RetryOnFailure rof = method.getAnnotation(RetryOnFailure.class);
77 int attempt = 0;
78 final long begin = System.nanoTime();
79 final Class<? extends Throwable>[] types = rof.types();
80 final ImprovedJoinPoint joinpoint = new ImprovedJoinPoint(point);
81 while (true) {
82 final long start = System.nanoTime();
83 try {
84 return point.proceed();
85 } catch (final InterruptedException ex) {
86 Thread.currentThread().interrupt();
87 throw ex;
88 // @checkstyle IllegalCatch (1 line)
89 } catch (final Throwable ex) {
90 if (Repeater.matches(ex.getClass(), rof.ignore())) {
91 throw ex;
92 }
93 if (!Repeater.matches(ex.getClass(), types)) {
94 throw ex;
95 }
96 ++attempt;
97 if (rof.verbose()) {
98 Logger.warn(
99 joinpoint.targetize(),
100 // @checkstyle LineLength (1 line)
101 "#%s(): attempt #%d of %d failed in %[nano]s (%[nano]s waiting already) with %[exception]s",
102 method.getName(),
103 attempt, rof.attempts(), System.nanoTime() - start,
104 System.nanoTime() - begin, ex
105 );
106 } else {
107 Logger.warn(
108 joinpoint.targetize(),
109 // @checkstyle LineLength (1 line)
110 "#%s(): attempt #%d/%d failed with %[type]s in %[nano]s (%[nano]s in total): %s",
111 method.getName(),
112 attempt, rof.attempts(), ex, System.nanoTime() - start,
113 System.nanoTime() - begin,
114 Repeater.message(ex)
115 );
116 }
117 if (attempt >= rof.attempts()) {
118 throw ex;
119 }
120 if (rof.delay() > 0L) {
121 this.delay(rof, attempt);
122 }
123 }
124 }
125 }
126
127 /**
128 * Waits certain time before returning.
129 * @param rof RetryOnFailure parameters.
130 * @param attempt Attempt number.
131 * @throws InterruptedException If wait has been interrupted.
132 */
133 private void delay(final RetryOnFailure rof, final int attempt) throws
134 InterruptedException {
135 final long delay;
136 if (rof.randomize()) {
137 delay = Repeater.RAND.nextInt(2 << attempt) * rof.delay();
138 } else {
139 delay = rof.delay() * attempt;
140 }
141 rof.unit().sleep(delay);
142 }
143
144 /**
145 * Get a message out of a potentially chained exception (recursively
146 * calls itself in order to reproduce a chain of messages).
147 * @param exp The exception
148 * @return The message
149 */
150 private static String message(final Throwable exp) {
151 final StringBuilder text = new StringBuilder();
152 text.append(exp.getMessage());
153 if (exp.getCause() != null) {
154 text.append("; ").append(Repeater.message(exp.getCause()));
155 }
156 String msg = text.toString();
157 if (msg.length() > Tv.HUNDRED) {
158 msg = String.format("%s...", msg.substring(0, Tv.HUNDRED));
159 }
160 return msg;
161 }
162
163 /**
164 * Checks if the exception thrown matches the list.
165 * @param thrown The thrown exception class
166 * @param types The exceptions to match
167 * @return TRUE if matches
168 */
169 private static boolean matches(
170 final Class<? extends Throwable> thrown,
171 final Class<? extends Throwable>... types
172 ) {
173 boolean matches = false;
174 for (final Class<? extends Throwable> type : types) {
175 if (type.isAssignableFrom(thrown)) {
176 matches = true;
177 break;
178 }
179 }
180 return matches;
181 }
182
183 }