Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JCabi aspects @RetryOnFailure how to throw exception

Tags:

java

aop

jcabi

I want to manually call for a retry on a method by using JCabi. Aspect oriented programming should make this easy but I can't figure it out.

import com.jcabi.aspects.RetryOnFailure;

public class Example
{

    public int j;

    @RetryOnFailure(attempts = 4, delay = 100, verbose = true)
    public void retryFun() throws Exception
    {
        j++;
        if(j<3)
            throw new Exception();
        else
            return;
    }

    public static void main(String[] args) throws Exception
    {
        Example example = new Example();
        System.out.println(example.j);
        example.retryFun();
        System.out.println(example.j);
    }
}

The only example available from jcabi is this one below which doesn't show how to throw an exception to force retry call:

Annotate your methods with @RetryOnFailure annotation and in case of exception in the method its execution will be repeated a few times:

public class Resource {
  @RetryOnFailure(attempts = 2, delay = 10, verbose = false)
  public String load(URL url) {
    return url.openConnection().getContent();
  }
}

In an exception occurs the method will retry two times, with a 10 msec delay between attempts.

like image 463
dendini Avatar asked Sep 19 '13 13:09

dendini


2 Answers

For those of you out there still looking for an answer, Yegor's answer is now outdated. The jcabi-maven-plugin version 0.8 he posted wasn't working for me.

After some hours of digging I have found this which states that we should use the last version As of this time, July 2014 is 0.9.2.

That was my answer for why when running mvn jcabi:ajc I was getting errors from the link and also the weaving not working.

like image 180
Turbut Alin Avatar answered Nov 19 '22 11:11

Turbut Alin


Indeed, just using jcabi annotations is not enough. You should "weave" your source code or binaries. I would recommend to weave binaries, as explained here: http://aspects.jcabi.com/example-weaving.html. Add this plugin to your pom.xml and you're done:

<plugin>
    <groupId>com.jcabi</groupId>
    <artifactId>jcabi-maven-plugin</artifactId>
    <version>0.8</version>
    <executions>
      <execution>
        <goals>
          <goal>ajc</goal>
        </goals>
      </execution>
    </executions>
</plugin>
like image 2
yegor256 Avatar answered Nov 19 '22 10:11

yegor256