Adding individual statistics to statistics export

import java.io.IOException;

import model.SystemValues.Games;
import model.SystemValues.Players;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

import view.GUI;

public privileged aspect StatisticsExport {

	declare precedence: StatisticsExport, GraphExport, PdfExport;
	private GUI gui;

	/**
	 * catch constructor call, so that we have the correct gui, to refer to
	 * everywhere
	 */
	after() returning(GUI gui): call(GUI.new(*)) {
		this.gui = gui;
	}

	/**
	 * Catch the call on {@link PDFReportListener.drawTable(PDDocument)} to get
	 * the pdf creator object.
	 *
	 * @param document
	 * @throws IOException
	 */
	after(PDDocument document) returning() throws IOException
    : call(* PDFReportListener.drawTable(PDDocument))
    && args(document) {
		PDPage page = new PDPage();
		document.addPage(page);
		PDPageContentStream contentStream = new PDPageContentStream(document,
				page);

		contentStream.beginText();
		contentStream.setFont(PDType1Font.HELVETICA_BOLD, 15);
		contentStream.moveTextPositionByAmount(100, 680);
		contentStream.drawString("Statistik ueber das gesamte Spiel");
		contentStream.endText();

		contentStream.beginText();
		contentStream.setFont(PDType1Font.HELVETICA_BOLD, 10);
		createOverallContent(contentStream);
		contentStream.endText();
		contentStream.close();

		page = new PDPage();
		document.addPage(page);
		contentStream = new PDPageContentStream(document, page);

		contentStream.beginText();
		contentStream.setFont(PDType1Font.HELVETICA_BOLD, 15);
		contentStream.moveTextPositionByAmount(100, 680);
		contentStream.drawString("Statistik fuer jeden einzelnen Spieler");
		contentStream.endText();

		for (int i = 0; i < Players.values().length; ++i) {
			contentStream.beginText();
			contentStream.setFont(PDType1Font.HELVETICA_BOLD, 10);
			createIndividualContent(contentStream, Players.values()[i]);
			contentStream.endText();
			contentStream.close();
			if (i < Players.values().length - 1) {
				page = new PDPage();
				document.addPage(page);
				contentStream = new PDPageContentStream(document, page);
			}
		}
	}

	/**
	 * Write statistics to given contentStream of a pdf page.
	 *
	 * @param contentStream
	 *            The contentStream of the pdf page to write on.
	 * @throws IOException
	 */
	private void createOverallContent(PDPageContentStream contentStream)
			throws IOException {
		OverallStatistics data = gui.model.gameDB.getOverallStatistics();

		contentStream.moveTextPositionByAmount(50, 650);
		contentStream.drawString("#Spiele (ohne weiter): "
				+ data.getAnzahlSpieleGesamt() + " (gewonnen: "
				+ String.format("%.2f", data.getGesamtWinPerc()) + "%)");

		contentStream.moveTextPositionByAmount(0, -16);
		contentStream.drawString("#Rufspiele: " + data.getAnzahlRufspiele()
				+ " (gewonnen: "
				+ String.format("%.2f", data.getRufspieleWinPerc()) + "%)");

		contentStream.moveTextPositionByAmount(50, -16);
		contentStream.drawString("-> teuerstes Rufspiel: "
				+ data.getTeuerstesRufspiel());

		contentStream.moveTextPositionByAmount(-50, -16);
		contentStream.drawString("#Soli gesamt: " + data.getAnzahlSoliGesamt()
				+ " (gewonnen: "
				+ String.format("%.2f", data.getSoliGesamtWinPerc()) + "%)");

		contentStream.moveTextPositionByAmount(0, -16);
		contentStream.drawString("#Soli normal: " + data.getAnzahlSoli()
				+ " (gewonnen: "
				+ String.format("%.2f", data.getSoliNormalWinPerc()) + "%)");

		contentStream.moveTextPositionByAmount(50, -16);
		contentStream.drawString("-> teuerstes Solo: "
				+ data.getTeuerstesSolo());

		contentStream.moveTextPositionByAmount(-50, -16);
		contentStream.drawString("#Solo Tout: " + data.getAnzahlSoliTout()
				+ " (gewonnen: "
				+ String.format("%.2f", data.getSoliToutWinPerc()) + "%)");

		contentStream.moveTextPositionByAmount(50, -16);
		contentStream.drawString("-> teuerstes Solo Tout: "
				+ data.getTeuerstesSoloTout());

		contentStream.moveTextPositionByAmount(-50, -16);
		contentStream.drawString("#Solo Sie: " + data.getAnzahlSoliSie());

		contentStream.moveTextPositionByAmount(50, -16);
		contentStream.drawString("-> teuerstes Solo Sie: "
				+ data.getTeuerstesSoloSie());

		contentStream.moveTextPositionByAmount(-50, -16);
		contentStream.drawString("#Weiter: " + data.getAnzahlWeiter());
	}

	private void createIndividualContent(PDPageContentStream contentStream,
			Players player) throws IOException {
		contentStream.moveTextPositionByAmount(50, 650);
		contentStream.drawString(player.toString());

		contentStream.moveTextPositionByAmount(0, -22);

		PlayerWiseStatistics data = gui.model.getGameData()
				.getPlayerWiseStatistics(player);

		contentStream.drawString("Gespielte Spiele:");
		contentStream.moveTextPositionByAmount(50, -16);
		contentStream.drawString("- Gesamt: " + data.getGamesPlayedTot()
				+ ", davon gewonnen: " + data.getGamesWonTot() + " ("
				+ String.format("%.2f", data.getGamesWonPerc()) + "%)");

		for (Games game : Games.values()) {
			if (game != Games.WEITER && game != Games.NONE) {
				int i = game.ordinal();
				contentStream.moveTextPositionByAmount(0, -16);
				contentStream.drawString("- "
						+ game.toString()
						+ ": "
						+ data.getGamesPlayedPerType()[i]
						+ ", davon gewonnen: "
						+ data.getGamesWonPerType()[i]
						+ " ("
						+ String.format("%.2f",
								data.getGamesWonPerTypePerc()[i]) + "%");
			}
		}

		contentStream.moveTextPositionByAmount(-50, -16);
		contentStream
				.drawString("Höchster Kontostand: " + data.getHighestAcc());

		contentStream.moveTextPositionByAmount(0, -16);
		contentStream.drawString("Niedrigster Kontostand: "
				+ data.getLowestAcc());

		contentStream.moveTextPositionByAmount(0, -16);
		contentStream.drawString("Größter Gewinn: " + data.getHighestWin());

		contentStream.moveTextPositionByAmount(0, -16);
		contentStream.drawString("Größter Verlust: " + data.getHighestLoss());

		contentStream.moveTextPositionByAmount(0, -32);
	}

}

import java.io.IOException;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

import view.GUI;

public privileged aspect StatisticsExport {

    declare precedence: StatisticsExport, GraphExport, PdfExport;
    private GUI gui;

    /**
     * catch constructor call, so that we have the correct gui, to refer to everywhere
     */
    after() returning(GUI gui): call(GUI.new(*)) {
        this.gui = gui;
    }

    /**
     * Catch the call on {@link PDFReportListener.drawTable(PDDocument)} to get the pdf
     * creator object.
     *
     * @param document
     * @throws IOException
     */
    after(PDDocument document) returning() throws IOException
    : call(* PDFReportListener.drawTable(PDDocument))
    && args(document) {
        PDPage page = new PDPage();
        document.addPage(page);
        PDPageContentStream contentStream = new PDPageContentStream(document,
                page);

        contentStream.beginText();
        contentStream.setFont(PDType1Font.HELVETICA_BOLD, 15);
        contentStream.moveTextPositionByAmount(100, 680);
        contentStream.drawString("Statistik ueber das gesamte Spiel");
        contentStream.endText();

        contentStream.beginText();
        contentStream.setFont(PDType1Font.HELVETICA_BOLD, 10);
        createOverallContent(contentStream);
        contentStream.endText();
        contentStream.close();
    }

	/**
	 * Write statistics to given contentStream of a pdf page.
	 *
	 * @param contentStream The contentStream of the pdf page to write on.
	 * @throws IOException
	 */
	private void createOverallContent(PDPageContentStream contentStream) throws IOException {
		OverallStatistics data = gui.model.gameDB.getOverallStatistics();

        contentStream.moveTextPositionByAmount(50, 650);
        contentStream.drawString("#Spiele (ohne weiter): " + data.getAnzahlSpieleGesamt()
        		+ " (gewonnen: "
        		+ String.format("%.2f", data.getGesamtWinPerc()) + "%)");

        contentStream.moveTextPositionByAmount(0, -16);
        contentStream.drawString("#Rufspiele: " + data.getAnzahlRufspiele() + " (gewonnen: "
        		+ String.format("%.2f", data.getRufspieleWinPerc()) + "%)");

        contentStream.moveTextPositionByAmount(50, -16);
        contentStream.drawString("-> teuerstes Rufspiel: "
        + data.getTeuerstesRufspiel());

        contentStream.moveTextPositionByAmount(-50, -16);
        contentStream.drawString("#Soli gesamt: "
        		+ data.getAnzahlSoliGesamt() + " (gewonnen: "
        		+ String.format("%.2f", data.getSoliGesamtWinPerc())
        		+ "%)");

        contentStream.moveTextPositionByAmount(0, -16);
        contentStream.drawString("#Soli normal: " + data.getAnzahlSoli()
        		+ " (gewonnen: "
        		+ String.format("%.2f", data.getSoliNormalWinPerc()) + "%)");

        contentStream.moveTextPositionByAmount(50, -16);
        contentStream.drawString("-> teuerstes Solo: " + data.getTeuerstesSolo());

        contentStream.moveTextPositionByAmount(-50, -16);
        contentStream.drawString("#Solo Tout: " + data.getAnzahlSoliTout()
        		+ " (gewonnen: "
        		+ String.format("%.2f", data.getSoliToutWinPerc()) + "%)");

        contentStream.moveTextPositionByAmount(50, -16);
        contentStream.drawString("-> teuerstes Solo Tout: "
        		+ data.getTeuerstesSoloTout());

        contentStream.moveTextPositionByAmount(-50, -16);
        contentStream.drawString("#Solo Sie: " + data.getAnzahlSoliSie());

        contentStream.moveTextPositionByAmount(50, -16);
        contentStream.drawString("-> teuerstes Solo Sie: " + data.getTeuerstesSoloSie());

        contentStream.moveTextPositionByAmount(-50, -16);
        contentStream.drawString("#Weiter: " + data.getAnzahlWeiter());
	}
}


remove Games.None from playerstatistics (forgotten before)

import java.awt.GridLayout;
import java.util.Iterator;

import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;

import view.GUI;
import view.UIUpdater;
import model.db.GameData;
import model.SystemValues.Games;
import model.SystemValues.Players;
import model.SystemValues.WIN;
import model.db.DataObject;

public privileged aspect StatPlayerWiseTxt {
    declare precedence : StatPlayerWiseTxt, StatOverallGraph, StatOverallTxt;

    private static GUI gui;
    private static JPanel panel = new JPanel();
    private static JTextArea statText = new JTextArea();

    after() returning(GUI gui): call(GUI.new(*)) {
        StatPlayerWiseTxt.gui = gui;
    }

    after(JTabbedPane tabbedPane):
                        execution(public static void StatisticsHelper.StatisticsPaneCreated(JTabbedPane))
                        && args(tabbedPane) {
        statText.setEditable(false);
        panel.setLayout(new GridLayout(0, 1));
        panel.add(statText);
        ((JTabbedPane) tabbedPane).addTab("PlayerWiseText", panel);
    }

    after() : execution(* UIUpdater.run()) {
        statText.setText(gui.model.getGameData()
                .getPlayerWiseStatisticsString());
    }

    public String GameData.getPlayerWiseStatisticsString() {
        StringBuilder result = new StringBuilder();

        for (Players player : Players.values()) {
            result.append(player);
            result.append(":" + System.lineSeparator() + System.lineSeparator());

            int gamesPlayedTot = 0;
            int gamesWonTot = 0;
            int highestAcc = 0;
            int lowestAcc = 0;
            int highestWin = 0;
            int highestLoss = 0;

            int[] gamesPlayedPerType = new int[Games.values().length];
            int[] gamesWonPerType = new int[Games.values().length];

            Iterator<DataObject> it = data.iterator();
            DataObject lastObj = it.next();

            while (it.hasNext()) {
                DataObject dataObj = it.next();

                if (dataObj.getPlayer().equals(player.toString())) {
                    gamesPlayedTot++;
                    gamesPlayedPerType[dataObj.getGameKind().ordinal()]++;
                    if (dataObj.getGameWon() == WIN.PLAYER) {
                        gamesWonTot++;
                        gamesWonPerType[dataObj.getGameKind().ordinal()]++;
                    }
                }
                int gameVal = dataObj.getPlayerVal(player) - lastObj.getPlayerVal(player);
                if (gameVal > highestWin) {
                    highestWin = gameVal;
                } else if (gameVal < highestLoss) {
                    highestLoss = gameVal;
                }

                int accVal = dataObj.getPlayerVal(player);
                if (accVal > highestAcc) {
                    highestAcc = accVal;
                } else if (accVal < lowestAcc) {
                    lowestAcc = accVal;
                }

                lastObj = dataObj;
            }

            double gamesWonPerc = ((gamesPlayedTot + gamesWonTot) > 0 ? (double) gamesWonTot
                    / gamesPlayedTot
                    : 0.0) * 100;

            double gamesWonPerTypePerc[] = new double[Games.values().length];
            for (Games game : Games.values()) {
                int i = game.ordinal();
                gamesWonPerTypePerc[i] = ((gamesPlayedPerType[i] + gamesWonPerType[i]) > 0 ? (double) gamesWonPerType[i]
                        / gamesPlayedPerType[i]
                        : 0.0) * 100;
            }

            result.append(
                    "Gespielte Spiele:" + System.lineSeparator() + "\t"
                            + "- Gesamt: " + gamesPlayedTot)
                    .append(", davon gewonnen: " + gamesWonTot)
                    .append(" (" + String.format("%.2f", gamesWonPerc) + "%)"
                            + System.lineSeparator());

            for (Games game : Games.values()) {
                if (game != Games.WEITER && game != Games.NONE) {
                    int i = game.ordinal();
                    result.append(
                            "\t- " + game.toString() + ": "
                                    + gamesPlayedPerType[i])
                            .append(", davon gewonnen: " + gamesWonPerType[i])
                            .append(" ("
                                    + String.format("%.2f",
                                            gamesWonPerTypePerc[i]) + "%)"
                                    + System.lineSeparator());
                }
            }

            result.append("Höchster Kontostand: " + highestAcc
                    + System.lineSeparator() + "Niedrigster Kontostand: "
                    + lowestAcc + System.lineSeparator());

            result.append("Größter Gewinn: " + highestWin
                    + System.lineSeparator());
            result.append("Größter Verlust: " + highestLoss
                    + System.lineSeparator());

            result.append(System.lineSeparator());
        }
        return result.toString();
    }
}

import java.awt.GridLayout;
import java.util.Iterator;

import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;

import view.GUI;
import view.UIUpdater;
import model.db.GameData;
import model.SystemValues.Games;
import model.SystemValues.Players;
import model.SystemValues.WIN;
import model.db.DataObject;

public privileged aspect StatPlayerWiseTxt {
    declare precedence : StatPlayerWiseTxt, StatOverallGraph, StatOverallTxt;

    private static GUI gui;
    private static JPanel panel = new JPanel();
    private static JTextArea statText = new JTextArea();

    after() returning(GUI gui): call(GUI.new(*)) {
        StatPlayerWiseTxt.gui = gui;
    }

    after(JTabbedPane tabbedPane):
                        execution(public static void StatisticsHelper.StatisticsPaneCreated(JTabbedPane))
                        && args(tabbedPane) {
        statText.setEditable(false);
        panel.setLayout(new GridLayout(0, 1));
        panel.add(statText);
        ((JTabbedPane) tabbedPane).addTab("PlayerWiseText", panel);
    }

    after() : execution(* UIUpdater.run()) {
        statText.setText(gui.model.getGameData()
                .getPlayerWiseStatisticsString());
    }

    public String GameData.getPlayerWiseStatisticsString() {
        StringBuilder result = new StringBuilder();

        for (Players player : Players.values()) {
            result.append(player);
            result.append(":" + System.lineSeparator() + System.lineSeparator());

            int gamesPlayedTot = 0;
            int gamesWonTot = 0;
            int highestAcc = 0;
            int lowestAcc = 0;
            int highestWin = 0;
            int highestLoss = 0;

            int[] gamesPlayedPerType = new int[Games.values().length];
            int[] gamesWonPerType = new int[Games.values().length];

            Iterator<DataObject> it = data.iterator();
            DataObject lastObj = it.next();

            while (it.hasNext()) {
                DataObject dataObj = it.next();

                if (dataObj.getPlayer().equals(player.toString())) {
                    gamesPlayedTot++;
                    gamesPlayedPerType[dataObj.getGameKind().ordinal()]++;
                    if (dataObj.getGameWon() == WIN.PLAYER) {
                        gamesWonTot++;
                        gamesWonPerType[dataObj.getGameKind().ordinal()]++;
                    }
                }
                int gameVal = dataObj.getPlayerVal(player) - lastObj.getPlayerVal(player);
                if (gameVal > highestWin) {
                    highestWin = gameVal;
                } else if (gameVal < highestLoss) {
                    highestLoss = gameVal;
                }

                int accVal = dataObj.getPlayerVal(player);
                if (accVal > highestAcc) {
                    highestAcc = accVal;
                } else if (accVal < lowestAcc) {
                    lowestAcc = accVal;
                }

                lastObj = dataObj;
            }

            double gamesWonPerc = ((gamesPlayedTot + gamesWonTot) > 0 ? (double) gamesWonTot
                    / gamesPlayedTot
                    : 0.0) * 100;

            double gamesWonPerTypePerc[] = new double[Games.values().length];
            for (Games game : Games.values()) {
                int i = game.ordinal();
                gamesWonPerTypePerc[i] = ((gamesPlayedPerType[i] + gamesWonPerType[i]) > 0 ? (double) gamesWonPerType[i]
                        / gamesPlayedPerType[i]
                        : 0.0) * 100;
            }

            result.append(
                    "Gespielte Spiele:" + System.lineSeparator() + "\t"
                            + "- Gesamt: " + gamesPlayedTot)
                    .append(", davon gewonnen: " + gamesWonTot)
                    .append(" (" + String.format("%.2f", gamesWonPerc) + "%)"
                            + System.lineSeparator());

            for (Games game : Games.values()) {
                if (game != Games.WEITER) {
                    int i = game.ordinal();
                    result.append(
                            "\t- " + game.toString() + ": "
                                    + gamesPlayedPerType[i])
                            .append(", davon gewonnen: " + gamesWonPerType[i])
                            .append(" ("
                                    + String.format("%.2f",
                                            gamesWonPerTypePerc[i]) + "%)"
                                    + System.lineSeparator());
                }
            }

            result.append("Höchster Kontostand: " + highestAcc
                    + System.lineSeparator() + "Niedrigster Kontostand: "
                    + lowestAcc + System.lineSeparator());

            result.append("Größter Gewinn: " + highestWin
                    + System.lineSeparator());
            result.append("Größter Verlust: " + highestLoss
                    + System.lineSeparator());

            result.append(System.lineSeparator());
        }
        return result.toString();
    }
}


Corrected pointcut and factored out recursive call.

git-svn-id: f4ecfe233223879a4a16cd7937f11b5152963d8e@18953 5e8d7ff9-d8ef-0310-90f0-a4852d11357a

/*
 * Copyright 2005-2009 LAMP/EPFL
 */
// $Id$

package scala.tools.eclipse.contribution.weaving.jdt.hierarchy;

import java.util.ArrayList;

import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.core.hierarchy.ChangeCollector;

import scala.tools.eclipse.contribution.weaving.jdt.IScalaElement;

@SuppressWarnings("restriction")
public privileged aspect HierarchyAspect {

  pointcut getAllTypesFromElement(ChangeCollector cc, IJavaElement element, ArrayList allTypes) :
    execution(void ChangeCollector.getAllTypesFromElement(IJavaElement, ArrayList)) &&
    args(element, allTypes) &&
    target(cc);

  void around(ChangeCollector cc, IJavaElement element, ArrayList allTypes) throws JavaModelException :
    getAllTypesFromElement(cc, element, allTypes) {
    getAllTypesFromElement0(cc, element, allTypes);
  }

  public void getAllTypesFromElement0(ChangeCollector cc, IJavaElement element, ArrayList allTypes) throws JavaModelException {
    switch (element.getElementType()) {
      case IJavaElement.COMPILATION_UNIT:
        IType[] types = ((ICompilationUnit)element).getTypes();
        for (int i = 0, length = types.length; i < length; i++) {
          IType type = types[i];
          allTypes.add(type);
          getAllTypesFromElement0(cc, type, allTypes);
        }
        break;
      case IJavaElement.TYPE:
        types = ((IType)element).getTypes();
        for (int i = 0, length = types.length; i < length; i++) {
          IType type = types[i];
          allTypes.add(type);
          getAllTypesFromElement0(cc, type, allTypes);
        }
        break;
      case IJavaElement.INITIALIZER:
      case IJavaElement.FIELD:
      case IJavaElement.METHOD:
        IJavaElement[] children = ((IMember)element).getChildren();
        for (int i = 0, length = children.length; i < length; i++) {
          IJavaElement child = children[i];
          if (child instanceof IType) {
            IType type = (IType)child;
            allTypes.add(type);
            getAllTypesFromElement0(cc, type, allTypes);
          } else if(child instanceof IScalaElement) {
            getAllTypesFromElement0(cc, child, allTypes);
          }
        }
        break;
    }
  }
}

/*
 * Copyright 2005-2009 LAMP/EPFL
 */
// $Id$

package scala.tools.eclipse.contribution.weaving.jdt.hierarchy;

import java.util.ArrayList;

import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.core.JavaElement;
import org.eclipse.jdt.internal.core.hierarchy.ChangeCollector;

import scala.tools.eclipse.contribution.weaving.jdt.IScalaElement;

@SuppressWarnings("restriction")
public privileged aspect HierarchyAspect {

  pointcut getAllTypesFromElement(ChangeCollector cc, JavaElement element, ArrayList allTypes) :
    execution(void ChangeCollector.getAllTypesFromElement(JavaElement, ArrayList)) &&
    args(element, allTypes) &&
    target(cc);

  void around(ChangeCollector cc, JavaElement element, ArrayList allTypes) throws JavaModelException :
    getAllTypesFromElement(cc, element, allTypes) {
    switch (element.getElementType()) {
      case IJavaElement.COMPILATION_UNIT:
        IType[] types = ((ICompilationUnit)element).getTypes();
        for (int i = 0, length = types.length; i < length; i++) {
          IType type = types[i];
          allTypes.add(type);
          cc.getAllTypesFromElement(type, allTypes);
        }
        break;
      case IJavaElement.TYPE:
        types = ((IType)element).getTypes();
        for (int i = 0, length = types.length; i < length; i++) {
          IType type = types[i];
          allTypes.add(type);
          cc.getAllTypesFromElement(type, allTypes);
        }
        break;
      case IJavaElement.INITIALIZER:
      case IJavaElement.FIELD:
      case IJavaElement.METHOD:
        IJavaElement[] children = ((IMember)element).getChildren();
        for (int i = 0, length = children.length; i < length; i++) {
          IJavaElement child = children[i];
          if (child instanceof IType) {
            IType type = (IType)child;
            allTypes.add(type);
            cc.getAllTypesFromElement(type, allTypes);
          } else if(child instanceof IScalaElement) {
            cc.getAllTypesFromElement(child, allTypes);
          }
        }
        break;
    }
  }
}


Ignore all getters from security checkers

package net.etalia.crepuscolo.check;

import java.lang.reflect.Method;
import java.util.Stack;

import javax.persistence.Entity;
import javax.persistence.MappedSuperclass;

import net.etalia.crepuscolo.domain.Authenticable;
import net.etalia.crepuscolo.services.AuthService;
import net.etalia.crepuscolo.services.AuthService.Verification;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Configurable
public aspect CheckAspect {

	pointcut checkMethod() :
		(
		execution(@(@CheckerAnnotation *) * *.*(..))
		||
		execution(* *.*(@(@CheckerAnnotation *) (*),..))
		||
		execution(* *.*(*, @(@CheckerAnnotation *) (*),..))
		||
		execution(* *.*(*, *, @(@CheckerAnnotation *) (*),..))
		||
		execution(* *.*(*, *, *, @(@CheckerAnnotation *) (*),..))
		||
		execution(@CheckerAnnotation * *.*(..))
		)
		&& !execution(* *.get*())
		&& !execution(* *.is*());

	@Autowired(required=true)
	private AuthService authService;

	private CheckerFactory checkerFactory;

	public void setAuthService(AuthService authService) {
		this.authService = authService;
	}

	public void setCheckerFactory(CheckerFactory cf) {
		this.checkerFactory = cf;
	}

	private ThreadLocal<Boolean> probing = new ThreadLocal<Boolean>();
	private ThreadLocal<Boolean> skip = new ThreadLocal<Boolean>();
	private ThreadLocal<Boolean> nullAuth = new ThreadLocal<Boolean>();
	private ThreadLocal<Stack<String>> mode = new ThreadLocal<Stack<String>>();

	public class JoinPointCheckPoint implements CheckPoint {

		private JoinPoint jp;

		public JoinPointCheckPoint(JoinPoint jp) {
			this.jp = jp;
		}

		@Override
		@Transactional(propagation=Propagation.REQUIRES_NEW)
		public String getAuthenticableId(Verification level) {
			if (nullAuth.get() == Boolean.TRUE) return null;
			return authService.getPrincipalUserId(level);
		}

		@Override
		@Transactional(propagation=Propagation.REQUIRES_NEW)
		public Authenticable getAuthenticable(Verification level) {
			if (nullAuth.get() == Boolean.TRUE) return null;
			return authService.getPrincipalUser(level);
		}

		@Override
		public Object getInstance() {
			return jp.getThis();
		}

		@Override
		public Method getMethod() {
			return ((MethodSignature)jp.getSignature()).getMethod();
		}

		@Override
		public Object[] getParameters() {
			return jp.getArgs();
		}

		@Override
		public boolean isInMode(String testMode) {
			return CheckAspect.this.isInMode(testMode);
		}

	}

	before() :
		checkMethod()
		&& !cflowbelow(checkMethod())
	{
		if (checkerFactory == null) return;
		if (skip.get() == Boolean.TRUE) return;

		Checker checker = checkerFactory.getFor(((MethodSignature)thisJoinPointStaticPart.getSignature()).getMethod());

		int code = checker.check(new JoinPointCheckPoint(thisJoinPoint));
		if (code != 0) {
			throw new AuthException().statusCode(code);
		}
		if (this.probing.get() == Boolean.TRUE) {
			throw new AuthException().statusCode(100);
		}
	}

	public void probing(boolean set) {
		if (set) {
			this.probing.set(true);
		} else {
			this.probing.remove();
		}
	}

	public void nullAuth(boolean set) {
		if (set) {
			this.nullAuth.set(true);
		} else {
			this.nullAuth.remove();
		}
	}

	public void skip(boolean set) {
		if (set) {
			this.skip.set(true);
		} else {
			this.skip.remove();
		}
	}

	public boolean isSkipping() {
		return this.skip.get() == Boolean.TRUE;
	}
	public boolean isProbing() {
		return this.probing.get() == Boolean.TRUE;
	}
	public boolean isNullAuth() {
		return this.nullAuth.get() == Boolean.TRUE;
	}

	public void enterMode(String pmode) {
		Stack<String> stack = mode.get();
		if (stack == null) {
			stack = new Stack<String>();
			mode.set(stack);
		}
		stack.add(pmode);
	}

	public void exitMode() {
		Stack<String> stack = mode.get();
		if (stack == null) return;
		stack.pop();
	}

	public boolean isInMode(String testMode) {
		Stack<String> stack = mode.get();
		if (stack == null || stack.size() == 0) return testMode == null;
		return stack.contains(testMode);
	}

	Object around() :
		execution (@CheckNoAuth * *.*(..))
	{
		boolean prenullauth = this.nullAuth.get() == Boolean.TRUE;
		try {
			nullAuth(true);
			return proceed();
		} finally {
			nullAuth(prenullauth);
		}
	}

	Object around() :
		execution (@CheckNoChecks * *.*(..))
	{
		boolean preskip = this.skip.get() == Boolean.TRUE;
		try {
			skip(true);
			return proceed();
		} finally {
			skip(preskip);
		}
	}

	before(String setMode) :
		execution (@CheckMode * (@Controller *).*(..))
		&& @annotation(CheckMode(setMode))
	{
		enterMode(setMode);
	}

	Object around(String setMode) :
		execution (@CheckMode * *.*(..))
		&& @annotation(CheckMode(setMode))
	{
		enterMode(setMode);
		try {
			return proceed(setMode);
		} finally {
			exitMode();
		}
	}

	public void clear() {
		this.mode.remove();
		this.nullAuth.remove();
		this.probing.remove();
		this.skip.remove();
	}
}

package net.etalia.crepuscolo.check;

import java.lang.reflect.Method;
import java.util.Stack;

import javax.persistence.Entity;
import javax.persistence.MappedSuperclass;

import net.etalia.crepuscolo.domain.Authenticable;
import net.etalia.crepuscolo.services.AuthService;
import net.etalia.crepuscolo.services.AuthService.Verification;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Configurable
public aspect CheckAspect {

	pointcut checkMethod() :
		(
		execution(@(@CheckerAnnotation *) * *.*(..))
		||
		execution(* *.*(@(@CheckerAnnotation *) (*),..))
		||
		execution(* *.*(*, @(@CheckerAnnotation *) (*),..))
		||
		execution(* *.*(*, *, @(@CheckerAnnotation *) (*),..))
		||
		execution(* *.*(*, *, *, @(@CheckerAnnotation *) (*),..))
		||
		execution(@CheckerAnnotation * *.*(..))
		)
		&& !execution(* (@(Entity || MappedSuperclass) *).get*())
		&& !execution(* (@(Entity || MappedSuperclass) *).is*());

	@Autowired(required=true)
	private AuthService authService;

	private CheckerFactory checkerFactory;

	public void setAuthService(AuthService authService) {
		this.authService = authService;
	}

	public void setCheckerFactory(CheckerFactory cf) {
		this.checkerFactory = cf;
	}

	private ThreadLocal<Boolean> probing = new ThreadLocal<Boolean>();
	private ThreadLocal<Boolean> skip = new ThreadLocal<Boolean>();
	private ThreadLocal<Boolean> nullAuth = new ThreadLocal<Boolean>();
	private ThreadLocal<Stack<String>> mode = new ThreadLocal<Stack<String>>();

	public class JoinPointCheckPoint implements CheckPoint {

		private JoinPoint jp;

		public JoinPointCheckPoint(JoinPoint jp) {
			this.jp = jp;
		}

		@Override
		@Transactional(propagation=Propagation.REQUIRES_NEW)
		public String getAuthenticableId(Verification level) {
			if (nullAuth.get() == Boolean.TRUE) return null;
			return authService.getPrincipalUserId(level);
		}

		@Override
		@Transactional(propagation=Propagation.REQUIRES_NEW)
		public Authenticable getAuthenticable(Verification level) {
			if (nullAuth.get() == Boolean.TRUE) return null;
			return authService.getPrincipalUser(level);
		}

		@Override
		public Object getInstance() {
			return jp.getThis();
		}

		@Override
		public Method getMethod() {
			return ((MethodSignature)jp.getSignature()).getMethod();
		}

		@Override
		public Object[] getParameters() {
			return jp.getArgs();
		}

		@Override
		public boolean isInMode(String testMode) {
			return CheckAspect.this.isInMode(testMode);
		}

	}

	before() :
		checkMethod()
		&& !cflowbelow(checkMethod())
	{
		if (checkerFactory == null) return;
		if (skip.get() == Boolean.TRUE) return;

		Checker checker = checkerFactory.getFor(((MethodSignature)thisJoinPointStaticPart.getSignature()).getMethod());

		int code = checker.check(new JoinPointCheckPoint(thisJoinPoint));
		if (code != 0) {
			throw new AuthException().statusCode(code);
		}
		if (this.probing.get() == Boolean.TRUE) {
			throw new AuthException().statusCode(100);
		}
	}

	public void probing(boolean set) {
		if (set) {
			this.probing.set(true);
		} else {
			this.probing.remove();
		}
	}

	public void nullAuth(boolean set) {
		if (set) {
			this.nullAuth.set(true);
		} else {
			this.nullAuth.remove();
		}
	}

	public void skip(boolean set) {
		if (set) {
			this.skip.set(true);
		} else {
			this.skip.remove();
		}
	}

	public boolean isSkipping() {
		return this.skip.get() == Boolean.TRUE;
	}
	public boolean isProbing() {
		return this.probing.get() == Boolean.TRUE;
	}
	public boolean isNullAuth() {
		return this.nullAuth.get() == Boolean.TRUE;
	}

	public void enterMode(String pmode) {
		Stack<String> stack = mode.get();
		if (stack == null) {
			stack = new Stack<String>();
			mode.set(stack);
		}
		stack.add(pmode);
	}

	public void exitMode() {
		Stack<String> stack = mode.get();
		if (stack == null) return;
		stack.pop();
	}

	public boolean isInMode(String testMode) {
		Stack<String> stack = mode.get();
		if (stack == null || stack.size() == 0) return testMode == null;
		return stack.contains(testMode);
	}

	Object around() :
		execution (@CheckNoAuth * *.*(..))
	{
		boolean prenullauth = this.nullAuth.get() == Boolean.TRUE;
		try {
			nullAuth(true);
			return proceed();
		} finally {
			nullAuth(prenullauth);
		}
	}

	Object around() :
		execution (@CheckNoChecks * *.*(..))
	{
		boolean preskip = this.skip.get() == Boolean.TRUE;
		try {
			skip(true);
			return proceed();
		} finally {
			skip(preskip);
		}
	}

	before(String setMode) :
		execution (@CheckMode * (@Controller *).*(..))
		&& @annotation(CheckMode(setMode))
	{
		enterMode(setMode);
	}

	Object around(String setMode) :
		execution (@CheckMode * *.*(..))
		&& @annotation(CheckMode(setMode))
	{
		enterMode(setMode);
		try {
			return proceed(setMode);
		} finally {
			exitMode();
		}
	}

	public void clear() {
		this.mode.remove();
		this.nullAuth.remove();
		this.probing.remove();
		this.skip.remove();
	}
}


Removes aspectj files which are no longer used

/*
 * Package package net.sf.jabref.aspects.violations;
 * Created on Nov 6, 2004
 * Author mspiegel
 *
 */
package net.sf.jabref.aspects.violations;

import java.awt.Component;
import java.awt.EventQueue;

public aspect DetectSwingSingleThreadRuleViolations {

	pointcut guiUpdates(Component component)
		:	call(* java..Component+.*(..)) &&
		    !call(* net..jabref+.*(..)) && target(component);

	pointcut safeGuiCalls()
		: call (* javax..JComponent.repaint(..))
			|| call(* javax..JComponent.revalidate(..))
		    || call(* javax..JComponent.invalidate(..))
		    || call(* javax..*.add*Listener(..))
		    || call(* javax..*.remove*Listener(..));

	pointcut unsafeGuiCalls(Component component)
		: guiUpdates(component) && !safeGuiCalls();

    before(Component component) : unsafeGuiCalls(component)
    	&& if (!EventQueue.isDispatchThread() && (component != null) &&
    	        	component.isDisplayable() && !Thread.currentThread().getName().equals("main")) {
            System.err.println(
                    "Violation: Swing component method called from nonAWT thread"
                    + "\nCalled method: " + thisJoinPointStaticPart.getSignature()
                    + "\nCaller:" + thisEnclosingJoinPointStaticPart.getSignature()
                    + "\nSource Location:" + thisJoinPointStaticPart.getSourceLocation()
                    + "\nThread:" + Thread.currentThread()
                    + "\nChange code to use EventQueue.invokeLater() or EventQueue.invokeAndWait()"
                    + "\n");
    	}

}


Allow to specify more than one Program to use the same ExecutorService

/*
 *     ParallelJ, framework for parallel computing
 *
 *     Copyright (C) 2010, 2011, 2012 Atos Worldline or third-party contributors as
 *     indicated by the @author tags or express copyright attribution
 *     statements applied by the authors.
 *
 *     This library is free software; you can redistribute it and/or
 *     modify it under the terms of the GNU Lesser General Public
 *     License as published by the Free Software Foundation; either
 *     version 2.1 of the License.
 *
 *     This library is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *     Lesser General Public License for more details.
 *
 *     You should have received a copy of the GNU Lesser General Public
 *     License along with this library; if not, write to the Free Software
 *     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */
package org.parallelj.launching.internal;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;

import org.parallelj.Programs;
import org.parallelj.internal.conf.ConfigurationService;
import org.parallelj.internal.conf.ParalleljConfigurationManager;
import org.parallelj.internal.conf.pojos.CExecutor;
import org.parallelj.internal.conf.pojos.CExecutors;
import org.parallelj.internal.conf.pojos.ParalleljConfiguration;
import org.parallelj.internal.kernel.KProcessor;
import org.parallelj.internal.kernel.procedure.CallableProcedure.CallableCall.CallableCallRunnable;
import org.parallelj.internal.kernel.procedure.RunnableProcedure.RunnableCall.RunnableCallRunnable;
import org.parallelj.internal.kernel.procedure.SubProcessProcedure.SubProcessCall.SubProcessRunnable;
import org.parallelj.internal.reflect.ProcessHelperImpl;
import org.parallelj.internal.reflect.ProgramAdapter.Adapter;
import org.parallelj.launching.Launch;
import org.parallelj.launching.LaunchException;
import org.parallelj.launching.LaunchingMessageKind;
import org.parallelj.launching.ProgramReturnCodes;
import org.parallelj.mirror.ExecutorServiceKind;
import org.parallelj.mirror.ParallelJThreadFactory;

/**
 * Implements the synchLaunch(..) and aSynchLaunch(..) methods of Launch.
 *
 *
 */
privileged aspect LaunchManagement {

	private static Map<KProcessor, LaunchImpl> phl = new ConcurrentHashMap<>();

	static privileged public aspect LaunchAdapter percflow(launchInstance() ) {

		declare precedence :
			org.parallelj.internal.kernel.Identifiers,
			org.parallelj.internal.reflect.ProgramAdapter,
			org.parallelj.internal.util.sm.impl.KStateMachines,
			org.parallelj.internal.util.sm.impl.KStateMachines.PerMachine,
			org.parallelj.Executables$PerExecutable,
			org.parallelj.internal.reflect.ProgramAdapter.PerProgram,
			org.parallelj.internal.log.Logs;

		pointcut launchInstance() : execution(* Launch+.*(..));

		interface IKProcessorLaunch {}
		LaunchImpl IKProcessorLaunch.launch;
		declare parents: KProcessor implements IKProcessorLaunch;

		interface ILaunchExecutors {}
		Map<String, ExecutorService> ILaunchExecutors.executors = new ConcurrentHashMap<>();
		ExecutorService ILaunchExecutors.defaultExecutor = null;
		declare parents: LaunchImpl implements ILaunchExecutors;

		private LaunchingObservable observable = new LaunchingObservable();

		boolean stopExecutorServiceAfterExecution = false;

		private static class AsyncThread implements Runnable {

			private LaunchAdapter launchAdapter;
			private LaunchImpl<?> launch;

			public AsyncThread(LaunchImpl<?> launch, LaunchAdapter launchAdapter) {
				this.launch = launch;
				this.launchAdapter = launchAdapter;
			}

			@Override
			public void run() {
				this.launchAdapter.internalSyncLaunch(this.launch);
			}
		}

		@SuppressWarnings({ "rawtypes", "unchecked" })
		Launch around(LaunchImpl launch) throws LaunchException:
					execution(public Launch Launch+.synchLaunch(..) throws LaunchException)
						&& this(launch) {
			proceed(launch);
			launch.processHelper = Programs.as(launch.jobInstance);
			launch.getLaunchResult().setStatusCode(ProgramReturnCodes.RUNNING);
			this.observable.prepareLaunching(launch);

			return internalSyncLaunch(launch);
		}

		@SuppressWarnings({ "rawtypes", "unchecked" })
		Launch around(LaunchImpl launch) throws LaunchException:
					execution(public Launch Launch+.aSynchLaunch() throws LaunchException)
						&& this(launch) {
			proceed(launch);
			launch.processHelper = Programs.as(launch.jobInstance);
			launch.getLaunchResult().setStatusCode(ProgramReturnCodes.RUNNING);
			this.observable.prepareLaunching(launch);
			if (launch.getExecutorService()!=null) {
				launch.getExecutorService().execute(new AsyncThread(launch, this));
			} else {
				ParallelJThreadFactory.getInstance().newThread(new AsyncThread(launch, this)).start();
	 		}
			return launch;
		}

		@SuppressWarnings("rawtypes")
		private Launch<?> internalSyncLaunch(LaunchImpl<?> launch) {
			LaunchingMessageKind.ILAUNCH0002.format(launch.getJobInstance()
					.getClass().getCanonicalName(), launch.getLaunchId());
			initializeExecutors(launch);
			ProcessHelperImpl processHelper = (ProcessHelperImpl)launch.getProcessHelper();
			KProcessor processor = processHelper.processor;
			if (processor == null) {
				if ( ((ILaunchExecutors)launch).defaultExecutor!=null) {
					processor = new KProcessor(((ILaunchExecutors)launch).defaultExecutor);
				} else {
					processor = new KProcessor(launch.getExecutorService());
				}
				((IKProcessorLaunch)processor).launch = launch;
				phl.put(processor, launch);
			}
			processor.execute(processHelper.process);
			launch.getProcessHelper().join();
			this.observable.finalizeLaunching(launch);
			launch.complete();
			cleanExecutors(launch);
			phl.remove(processor);

			if (launch.getLaunchResult().getStatusCode()!=ProgramReturnCodes.FAILURE
					&&launch.getLaunchResult().getStatusCode()!=ProgramReturnCodes.ABORTED) {
				launch.getLaunchResult().setStatusCode(ProgramReturnCodes.SUCCESS);
			}
			LaunchingMessageKind.ILAUNCH0003.format(launch.getJobInstance()
					.getClass().getCanonicalName(), launch.getLaunchId(), launch
					.getLaunchResult().getStatusCode(), launch.getLaunchResult()
					.getReturnCode());
			return launch;
		}

		private void initializeExecutors(LaunchImpl<?> launch) {
			ParalleljConfiguration configuration = (ParalleljConfiguration) ConfigurationService
					.getConfigurationService().getConfigurationManager()
					.get(ParalleljConfigurationManager.class)
					.getConfiguration();
			Map<String, ExecutorService> executors = ((ILaunchExecutors) launch).executors;
			CExecutors cExecutors = configuration != null ? configuration
					.getExecutorServices() : null;
			if (cExecutors != null) {
				if (cExecutors.getDefaultServiceType() != null
						|| cExecutors.getDefaultPoolSize() != null
						|| cExecutors.getDefaultServiceClass() != null) {
					try {
						ExecutorService defaultService = ExecutorServiceKind
								.valueOf(
										cExecutors.getDefaultServiceType()
												.value()).create(
										cExecutors.getDefaultPoolSize()
												.intValue(),
										cExecutors.getDefaultServiceClass());
						((ILaunchExecutors) launch).defaultExecutor = defaultService;
					} catch (InstantiationException | IllegalAccessException
							| ClassNotFoundException e) {
						// Do nothing..
					} catch (Exception e) {
						LaunchingMessageKind.ELAUNCH0011.format(e);
					}
				}
				if (cExecutors.getExecutorService() != null) {
					for (CExecutor cExecutor : cExecutors.getExecutorService()) {
						String[] names = cExecutor.getProgramName().split(",");
						boolean instanciate = false;
						for (String name : names) {
							if (name.length() > 0 && name.trim().length() > 0) {
								instanciate = true;
							}
						}
						if (instanciate) {
							ExecutorService executor = null;
							if (cExecutor.getServiceType() != null) {
								String type = cExecutor.getServiceType()
										.value();
								try {
									int size = cExecutor.getPoolSize() != null ? cExecutor
											.getPoolSize().intValue() : 0;
									executor = ExecutorServiceKind
											.valueOf(type)
											.create(size,
													cExecutor.getServiceClass());
									boolean foundProgram = false;
									for (String name : names) {
										if (name.length() > 0 && name.trim().length() > 0) {
											executors.put(
													name,
													executor);
											foundProgram = true;
										}
									}
									if (!foundProgram) {
										executor.shutdown();
									}
								} catch (InstantiationException
										| IllegalAccessException
										| ClassNotFoundException e) {
									// Do Nothing..
								} catch (Exception e) {
									LaunchingMessageKind.ELAUNCH0012.format(e);
								}
							}
						}
					}
				}
			}
		}

		private void cleanExecutors(LaunchImpl<?> launch) {
			Map<String, ExecutorService> executors = ((ILaunchExecutors)launch).executors;
			for (String key : executors.keySet()) {
				executors.get(key).shutdown();
				executors.remove(key);
			}
			if (((ILaunchExecutors)launch).defaultExecutor!=null) {
				((ILaunchExecutors)launch).defaultExecutor.shutdown();
			}
		}
	}

	@SuppressWarnings("rawtypes")
	void around(KProcessor kProcessor, SubProcessRunnable runnable):execution(public void submit(..))
		&& args(runnable)
		&&this(kProcessor){

		Adapter context = (Adapter)runnable.getSubProcessCall().getProcess().getContext();
		LaunchImpl launch = phl.get(kProcessor);
		if (launch!=null) {
			ExecutorService service = launch.executors.get(context.getClass().getCanonicalName());
			if (service!=null) {
				kProcessor.submit(runnable, service);
			} else {
				proceed(kProcessor, runnable);
			}
		} else {
			proceed(kProcessor, runnable);
		}
}

	@SuppressWarnings("rawtypes")
	void around(KProcessor kProcessor, CallableCallRunnable runnable):execution(public void submit(..))
		&& args(runnable)
		&&this(kProcessor){

		Adapter context = (Adapter)runnable.getCallableCall().getProcess().getContext();
		LaunchImpl launch = phl.get(kProcessor);
		if (launch!=null) {
			ExecutorService service = launch.executors.get(context.getClass().getCanonicalName());
			if (service!=null) {
				kProcessor.submit(runnable, service);
			} else {
				proceed(kProcessor, runnable);
			}
		} else {
			proceed(kProcessor, runnable);
		}
	}

	@SuppressWarnings("rawtypes")
	void around(KProcessor kProcessor, RunnableCallRunnable runnable):execution(public void submit(..))
		&& args(runnable)
		&&this(kProcessor) {

		Adapter context = (Adapter)runnable.getRunnableCall().getProcess().getContext();
		LaunchImpl launch = phl.get(kProcessor);
		if (launch!=null) {
			ExecutorService service = launch.executors.get(context.getClass().getCanonicalName());
			if (service!=null) {
				kProcessor.submit(runnable, service);
			} else {
				proceed(kProcessor, runnable);
			}
		} else {
			proceed(kProcessor, runnable);
		}
	}
}

/*
 *     ParallelJ, framework for parallel computing
 *
 *     Copyright (C) 2010, 2011, 2012 Atos Worldline or third-party contributors as
 *     indicated by the @author tags or express copyright attribution
 *     statements applied by the authors.
 *
 *     This library is free software; you can redistribute it and/or
 *     modify it under the terms of the GNU Lesser General Public
 *     License as published by the Free Software Foundation; either
 *     version 2.1 of the License.
 *
 *     This library is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *     Lesser General Public License for more details.
 *
 *     You should have received a copy of the GNU Lesser General Public
 *     License along with this library; if not, write to the Free Software
 *     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */
package org.parallelj.launching.internal;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;

import org.parallelj.Programs;
import org.parallelj.internal.conf.ConfigurationService;
import org.parallelj.internal.conf.ParalleljConfigurationManager;
import org.parallelj.internal.conf.pojos.CExecutor;
import org.parallelj.internal.conf.pojos.CExecutors;
import org.parallelj.internal.conf.pojos.ParalleljConfiguration;
import org.parallelj.internal.kernel.KProcessor;
import org.parallelj.internal.kernel.procedure.CallableProcedure.CallableCall.CallableCallRunnable;
import org.parallelj.internal.kernel.procedure.RunnableProcedure.RunnableCall.RunnableCallRunnable;
import org.parallelj.internal.kernel.procedure.SubProcessProcedure.SubProcessCall.SubProcessRunnable;
import org.parallelj.internal.reflect.ProcessHelperImpl;
import org.parallelj.internal.reflect.ProgramAdapter.Adapter;
import org.parallelj.launching.Launch;
import org.parallelj.launching.LaunchException;
import org.parallelj.launching.LaunchingMessageKind;
import org.parallelj.launching.ProgramReturnCodes;
import org.parallelj.mirror.ExecutorServiceKind;
import org.parallelj.mirror.ParallelJThreadFactory;

/**
 * Implements the synchLaunch(..) and aSynchLaunch(..) methods of Launch.
 *
 *
 */
privileged aspect LaunchManagement {

	private static Map<KProcessor, LaunchImpl> phl = new ConcurrentHashMap<>();

	static privileged public aspect LaunchAdapter percflow(launchInstance() ) {

		declare precedence :
			org.parallelj.internal.kernel.Identifiers,
			org.parallelj.internal.reflect.ProgramAdapter,
			org.parallelj.internal.util.sm.impl.KStateMachines,
			org.parallelj.internal.util.sm.impl.KStateMachines.PerMachine,
			org.parallelj.Executables$PerExecutable,
			org.parallelj.internal.reflect.ProgramAdapter.PerProgram,
			org.parallelj.internal.log.Logs;

		pointcut launchInstance() : execution(* Launch+.*(..));

		interface IKProcessorLaunch {}
		LaunchImpl IKProcessorLaunch.launch;
		declare parents: KProcessor implements IKProcessorLaunch;

		interface ILaunchExecutors {}
		Map<String, ExecutorService> ILaunchExecutors.executors = new ConcurrentHashMap<>();
		ExecutorService ILaunchExecutors.defaultExecutor = null;
		declare parents: LaunchImpl implements ILaunchExecutors;

		private LaunchingObservable observable = new LaunchingObservable();

		boolean stopExecutorServiceAfterExecution = false;

		private static class AsyncThread implements Runnable {

			private LaunchAdapter launchAdapter;
			private LaunchImpl<?> launch;

			public AsyncThread(LaunchImpl<?> launch, LaunchAdapter launchAdapter) {
				this.launch = launch;
				this.launchAdapter = launchAdapter;
			}

			@Override
			public void run() {
				this.launchAdapter.internalSyncLaunch(this.launch);
			}
		}

		@SuppressWarnings({ "rawtypes", "unchecked" })
		Launch around(LaunchImpl launch) throws LaunchException:
					execution(public Launch Launch+.synchLaunch(..) throws LaunchException)
						&& this(launch) {
			proceed(launch);
			launch.processHelper = Programs.as(launch.jobInstance);
			launch.getLaunchResult().setStatusCode(ProgramReturnCodes.RUNNING);
			this.observable.prepareLaunching(launch);

			return internalSyncLaunch(launch);
		}

		@SuppressWarnings({ "rawtypes", "unchecked" })
		Launch around(LaunchImpl launch) throws LaunchException:
					execution(public Launch Launch+.aSynchLaunch() throws LaunchException)
						&& this(launch) {
			proceed(launch);
			launch.processHelper = Programs.as(launch.jobInstance);
			launch.getLaunchResult().setStatusCode(ProgramReturnCodes.RUNNING);
			this.observable.prepareLaunching(launch);
			if (launch.getExecutorService()!=null) {
				launch.getExecutorService().execute(new AsyncThread(launch, this));
			} else {
				ParallelJThreadFactory.getInstance().newThread(new AsyncThread(launch, this)).start();
	 		}
			return launch;
		}

		@SuppressWarnings("rawtypes")
		private Launch<?> internalSyncLaunch(LaunchImpl<?> launch) {
			LaunchingMessageKind.ILAUNCH0002.format(launch.getJobInstance()
					.getClass().getCanonicalName(), launch.getLaunchId());
			initializeExecutors(launch);
			ProcessHelperImpl processHelper = (ProcessHelperImpl)launch.getProcessHelper();
			KProcessor processor = processHelper.processor;
			if (processor == null) {
				if ( ((ILaunchExecutors)launch).defaultExecutor!=null) {
					processor = new KProcessor(((ILaunchExecutors)launch).defaultExecutor);
				} else {
					processor = new KProcessor(launch.getExecutorService());
				}
				((IKProcessorLaunch)processor).launch = launch;
				phl.put(processor, launch);
			}
			processor.execute(processHelper.process);
			launch.getProcessHelper().join();
			this.observable.finalizeLaunching(launch);
			launch.complete();
			cleanExecutors(launch);
			phl.remove(processor);

			if (launch.getLaunchResult().getStatusCode()!=ProgramReturnCodes.FAILURE
					&&launch.getLaunchResult().getStatusCode()!=ProgramReturnCodes.ABORTED) {
				launch.getLaunchResult().setStatusCode(ProgramReturnCodes.SUCCESS);
			}
			LaunchingMessageKind.ILAUNCH0003.format(launch.getJobInstance()
					.getClass().getCanonicalName(), launch.getLaunchId(), launch
					.getLaunchResult().getStatusCode(), launch.getLaunchResult()
					.getReturnCode());
			return launch;
		}

		private void initializeExecutors(LaunchImpl<?> launch) {
			ParalleljConfiguration configuration = (ParalleljConfiguration) ConfigurationService
					.getConfigurationService().getConfigurationManager()
					.get(ParalleljConfigurationManager.class).getConfiguration();
			Map<String, ExecutorService> executors = ((ILaunchExecutors)launch).executors;
			CExecutors cExecutors = configuration!=null?configuration.getExecutorServices():null;
			if (cExecutors != null) {
				if(cExecutors.getDefaultServiceType()!=null || cExecutors.getDefaultPoolSize()!=null||cExecutors.getDefaultServiceClass()!=null) {
					try {
						ExecutorService defaultService = ExecutorServiceKind.valueOf(cExecutors.getDefaultServiceType().value()).create(cExecutors.getDefaultPoolSize().intValue(), cExecutors.getDefaultServiceClass());
						((ILaunchExecutors)launch).defaultExecutor=defaultService;
					} catch (InstantiationException | IllegalAccessException
							| ClassNotFoundException e) {
						// Do nothing..
					} catch (Exception e) {
						LaunchingMessageKind.ELAUNCH0011.format(e);
					}
				}
				if(cExecutors.getExecutorService() != null) {
					for(CExecutor cExecutor:cExecutors.getExecutorService()) {
						if (executors.get(cExecutor.getProgramName()) == null) {
							String type = cExecutor.getServiceType().value();
							try {
								int size = cExecutor.getPoolSize()!=null?cExecutor.getPoolSize().intValue():0;
								ExecutorService executor = ExecutorServiceKind.valueOf(type).create(size, cExecutor.getServiceClass());
								executors.put(cExecutor.getProgramName(), executor);
							} catch (InstantiationException | IllegalAccessException
									| ClassNotFoundException e) {
								// Do Nothing..
							} catch (Exception e) {
								LaunchingMessageKind.ELAUNCH0012.format(e);
							}
						}
					}
				}
			}
		}

		private void cleanExecutors(LaunchImpl<?> launch) {
			Map<String, ExecutorService> executors = ((ILaunchExecutors)launch).executors;
			for (String key : executors.keySet()) {
				executors.get(key).shutdown();
				executors.remove(key);
			}
			if (((ILaunchExecutors)launch).defaultExecutor!=null) {
				((ILaunchExecutors)launch).defaultExecutor.shutdown();
			}
		}
	}

	@SuppressWarnings("rawtypes")
	void around(KProcessor kProcessor, SubProcessRunnable runnable):execution(public void submit(..))
		&& args(runnable)
		&&this(kProcessor){

		Adapter context = (Adapter)runnable.getSubProcessCall().getProcess().getContext();
		LaunchImpl launch = phl.get(kProcessor);
		if (launch!=null) {
			ExecutorService service = launch.executors.get(context.getClass().getCanonicalName());
			if (service!=null) {
				kProcessor.submit(runnable, service);
			} else {
				proceed(kProcessor, runnable);
			}
		} else {
			proceed(kProcessor, runnable);
		}
}

	@SuppressWarnings("rawtypes")
	void around(KProcessor kProcessor, CallableCallRunnable runnable):execution(public void submit(..))
		&& args(runnable)
		&&this(kProcessor){

		Adapter context = (Adapter)runnable.getCallableCall().getProcess().getContext();
		LaunchImpl launch = phl.get(kProcessor);
		if (launch!=null) {
			ExecutorService service = launch.executors.get(context.getClass().getCanonicalName());
			if (service!=null) {
				kProcessor.submit(runnable, service);
			} else {
				proceed(kProcessor, runnable);
			}
		} else {
			proceed(kProcessor, runnable);
		}
	}

	@SuppressWarnings("rawtypes")
	void around(KProcessor kProcessor, RunnableCallRunnable runnable):execution(public void submit(..))
		&& args(runnable)
		&&this(kProcessor) {

		Adapter context = (Adapter)runnable.getRunnableCall().getProcess().getContext();
		LaunchImpl launch = phl.get(kProcessor);
		if (launch!=null) {
			ExecutorService service = launch.executors.get(context.getClass().getCanonicalName());
			if (service!=null) {
				kProcessor.submit(runnable, service);
			} else {
				proceed(kProcessor, runnable);
			}
		} else {
			proceed(kProcessor, runnable);
		}
	}
}


Refinement of previous commit r696.

Refinement of previous commit r696.

/*
 * Copyright (C) 2011 Archie L. Cobbs and other authors. All rights reserved.
 *
 * $Id$
 */

package org.dellroad.stuff.spring;

import java.lang.reflect.Method;
import java.util.Random;

import org.aspectj.lang.reflect.MethodSignature;
import org.dellroad.stuff.java.ThreadLocalHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.TransientDataAccessException;
import org.springframework.dao.UncategorizedDataAccessException;
import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAttribute;
import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 * An aspect that automatically retries failed but "retryable" transactions.
 *
 * @see RetryTransaction
 */
public aspect RetryTransactionAspect implements RetryTransactionProvider, InitializingBean {

    private final Logger log = LoggerFactory.getLogger(this.getClass());
    private final ThreadLocalHolder<Integer> attemptHolder = new ThreadLocalHolder<Integer>();
    private final Random random = new Random();

    // Default values for retry settings
    private int maxRetriesDefault = RetryTransaction.DEFAULT_MAX_RETRIES;
    private long initialDelayDefault = RetryTransaction.DEFAULT_INITIAL_DELAY;
    private long maximumDelayDefault = RetryTransaction.DEFAULT_MAXIMUM_DELAY;

    // This knows how to read information from @Transactional annotation
    private final AnnotationTransactionAttributeSource transactionAttributeSource = new AnnotationTransactionAttributeSource(false);

    // Tells us what is a "transient" exception; must be explicitly configured
    private PersistenceExceptionTranslator persistenceExceptionTranslator;

// Property accessors and RetryTransactionProvider implementation

    @Override
    public PersistenceExceptionTranslator getPersistenceExceptionTranslator() {
        return this.persistenceExceptionTranslator;
    }
    public void setPersistenceExceptionTranslator(PersistenceExceptionTranslator persistenceExceptionTranslator) {
        this.persistenceExceptionTranslator = persistenceExceptionTranslator;
    }

    @Override
    public int getMaxRetriesDefault() {
        return this.maxRetriesDefault;
    }
    public void setMaxRetriesDefault(int maxRetriesDefault) {
        this.maxRetriesDefault = maxRetriesDefault;
    }

    @Override
    public long getInitialDelayDefault() {
        return this.initialDelayDefault;
    }
    public void setInitialDelayDefault(long initialDelayDefault) {
        this.initialDelayDefault = initialDelayDefault;
    }

    @Override
    public long getMaximumDelayDefault() {
        return this.maximumDelayDefault;
    }
    public void setMaximumDelayDefault(long maximumDelayDefault) {
        this.maximumDelayDefault = maximumDelayDefault;
    }

    @Override
    public int getAttemptNumber() {
        final Integer attempt = this.attemptHolder.get();
        return attempt != null ? attempt : 0;
    }

// InitializingBean

    @Override
    public void afterPropertiesSet() throws Exception {
        if (this.persistenceExceptionTranslator == null)
            throw new IllegalArgumentException("no PersistenceExceptionTranslator configured");
    }

// Aspect

    // Ensure that this aspect is woven outside of the AnnotationTransactionAspect
    declare precedence : RetryTransactionAspect, org.springframework.transaction.aspectj.*;

    /**
     * Attempt to execute a transactional method. If the method throws any exception which is translated
     * to a subclass of TransientDataAccessException, the method will be executed again, with a delay
     * between attempts.
     */
    Object around(final Object txObject) : retryTransactionalMethodExecution(txObject) {

        // Get method info
        final MethodSignature methodSignature = (MethodSignature)thisJoinPoint.getSignature();
        final Method method = methodSignature.getMethod();

        // Get transaction attribute from @Transactional annotation
        final TransactionAttribute transactionAttribute = this.transactionAttributeSource
          .getTransactionAttribute(method, txObject.getClass());
        if (transactionAttribute == null) {
            throw new RuntimeException("no @Transactional annotation found for method "
              + method + "; required for @RetryTransaction");
        }

        // Do nothing unless this method is about to create a new transaction
        switch (transactionAttribute.getPropagationBehavior()) {
        case TransactionDefinition.PROPAGATION_REQUIRES_NEW:
            break;
        case TransactionDefinition.PROPAGATION_REQUIRED:
            if (TransactionSynchronizationManager.isActualTransactionActive()) {
                if (this.log.isTraceEnabled())
                    this.log.trace("skipping retry logic; transaction already open in @Transactional method {}", method);
                return proceed(txObject);
            }
            break;
        default:
            return proceed(txObject);
        }

        // Get @RetryTransaction annotation
        final RetryTransaction retryTransaction = AnnotationUtils.getAnnotation(method, RetryTransaction.class);
        if (retryTransaction == null)
            throw new RuntimeException("internal error: no @RetryTransaction annotation found for method " + method);

        // Get retry parameters, applying defaults if necessary
        final int maxRetries = retryTransaction.maxRetries() != -1 ?
          retryTransaction.maxRetries() : this.maxRetriesDefault;
        final long initialDelay = retryTransaction.initialDelay() != -1 ?
          retryTransaction.initialDelay() : this.initialDelayDefault;
        final long maximumDelay = retryTransaction.maximumDelay() != -1 ?
          retryTransaction.maximumDelay() : this.maximumDelayDefault;

        // Sanity check we are configured
        if (this.persistenceExceptionTranslator == null)
            throw new RuntimeException("@RetryTransaction aspect must be configured before use");

        // Perform attempts
        TransientDataAccessException transientException;
        int attempt = 1;
        do {

            // If this is not the first attempt, sleep for a while
            if (attempt > 1) {
                final long delay = this.calculateDelay(attempt, initialDelay, maximumDelay);
                if (this.log.isDebugEnabled())
                    this.log.debug("pausing {}ms before retrying @Transactional method {}", delay, method);
                this.pause(delay);
                if (this.log.isDebugEnabled())
                    this.log.debug("retrying @Transactional method {} (attempt #{})", method, attempt);
            }

            // Make attempt
            try {

                // Make next attempt
                if (this.log.isTraceEnabled())
                    this.log.trace("starting @Transactional method {} (attempt #{})", method, attempt);
                final Object[] result = new Object[1];
                this.attemptHolder.invoke(attempt, new Runnable() {
                    @Override
                    public void run() {
                        result[0] = proceed(txObject);
                    }
                });
                if (attempt > 1) {
                    if (this.log.isDebugEnabled())
                        this.log.debug("successfully completed @Transactional method {} on re-try attempt #{}", method, attempt);
                } else {
                    if (this.log.isTraceEnabled())
                        this.log.trace("successfully completed @Transactional method {} on first attempt", method);
                }

                // We're done
                return result[0];
            } catch (RuntimeException e) {

                // Handle case that Spring has already wrapped and hidden the real exception without recognizing it
                DataAccessException translatedException = null;
                if (e instanceof UncategorizedDataAccessException) {
                    for (Throwable t = e.getCause(); translatedException == null && t != null; t = t.getCause()) {
                        if (t instanceof RuntimeException)
                            translatedException = this.persistenceExceptionTranslator.translateExceptionIfPossible((RuntimeException)t);
                    }
                }

                // Translate the exception, if not already translated above
                if (translatedException == null) {
                    translatedException = e instanceof DataAccessException ?
                      (DataAccessException)e : this.persistenceExceptionTranslator.translateExceptionIfPossible(e);
                }

                // Log result
                if (this.log.isDebugEnabled()) {
                    this.log.debug("exception from @Transactional method {} on attempt #{}: {} (translates to {})",
                      method, attempt, e, translatedException != null ? translatedException.getClass().getSimpleName() : null);
                }

                // If it's not a transient exception, re-throw the original exception
                if (!(translatedException instanceof TransientDataAccessException))
                    throw e;

                // Re-throw the transient exception when we've run out of attempts
                transientException = (TransientDataAccessException)translatedException;
            }
        }
        while (attempt++ <= maxRetries);

        // All attempts failed
        this.log.error("@Transactional method {} failed after {} attempts, giving up!", method, maxRetries);
        throw transientException;
    }

// Static methods

    /**
     * Get the current transaction attempt number.
     *
     * @return transaction attempt number, or zero if this aspect is not active in the current thread
     * @deprecated Use {@link RetryTransactionProvider#getAttemptNumber} instead
     */
    public static int getAttempt() {
        final Integer attempt = RetryTransactionAspect.aspectOf().attemptHolder.get();
        return attempt != null ? attempt : 0;
    }

// Helper methods

    /**
     * Calculate how long to sleep.
     *
     * @param attempt attempt number (one-based)
     * @param initialDelay initial delay
     * @param maximumDelay maximum delay
     */
    protected long calculateDelay(int attempt, long initialDelay, long maximumDelay) {

        // Enforce sanity
        initialDelay = Math.max(initialDelay, 1);
        maximumDelay = Math.max(maximumDelay, 1);
        initialDelay = Math.min(initialDelay, maximumDelay);

        // Calculate nominal delay for this attempt, using exponential back-off; be careful to avoid overflow
        long delay = initialDelay;
        while (attempt-- > 1) {
            delay <<= 1;
            if (delay >= maximumDelay) {
                delay = maximumDelay;
                break;
            }
        }

        // Add in +/- 12.5% randomness
        final int randomRange = Math.max(1, (int)(delay >> 3));
        synchronized (this.random) {
            delay += this.random.nextInt(randomRange) - randomRange / 2;
        }

        // Enforce upper bound again
        delay = Math.min(delay, maximumDelay);

        // Done
        return delay;
    }

    /**
     * Sleep for the specified period.
     *
     * @param delay delay in milliseconds
     */
    protected void pause(long delay) {
        try {
            Thread.sleep(delay);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    /*
     * Matches the execution of any public method in a type with the @Transactional annotation, or any subtype of a type with the
     * @Transactional annotation.
     */
    private pointcut executionOfPublicMethodInTransactionalType() : execution(public * ((@Transactional *)+).*(..));

    /*
     * Matches the execution of any public method in a type with the @RetryTransaction annotation, or any subtype of a type with the
     * @RetryTransaction annotation.
     */
    private pointcut executionOfPublicMethodInRetryTransactionType() : execution(public * ((@RetryTransaction *)+).*(..));

    /*
     * Matches the execution of any method with the @Transactional annotation.
     */
    private pointcut executionOfTransactionalMethod() : execution(@Transactional * *(..));

    /*
     * Matches the execution of any method with the @RetryTransaction annotation.
     */
    private pointcut executionOfRetryTransactionMethod() : execution(@RetryTransaction * *(..));

    /*
     * Main pointcut - matched join points have both @Transactional and @RetryTransaction on method and/or type
     */
    private pointcut retryTransactionalMethodExecution(Object txObject) : this(txObject)
        && (executionOfPublicMethodInTransactionalType() || executionOfTransactionalMethod())
        && (executionOfPublicMethodInRetryTransactionType() || executionOfRetryTransactionMethod());
}

/*
 * Copyright (C) 2011 Archie L. Cobbs and other authors. All rights reserved.
 *
 * $Id$
 */

package org.dellroad.stuff.spring;

import java.lang.reflect.Method;
import java.util.Random;

import org.aspectj.lang.reflect.MethodSignature;
import org.dellroad.stuff.java.ThreadLocalHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.TransientDataAccessException;
import org.springframework.dao.UncategorizedDataAccessException;
import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAttribute;
import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 * An aspect that automatically retries failed but "retryable" transactions.
 *
 * @see RetryTransaction
 */
public aspect RetryTransactionAspect implements RetryTransactionProvider, InitializingBean {

    private final Logger log = LoggerFactory.getLogger(this.getClass());
    private final ThreadLocalHolder<Integer> attemptHolder = new ThreadLocalHolder<Integer>();
    private final Random random = new Random();

    // Default values for retry settings
    private int maxRetriesDefault = RetryTransaction.DEFAULT_MAX_RETRIES;
    private long initialDelayDefault = RetryTransaction.DEFAULT_INITIAL_DELAY;
    private long maximumDelayDefault = RetryTransaction.DEFAULT_MAXIMUM_DELAY;

    // This knows how to read information from @Transactional annotation
    private final AnnotationTransactionAttributeSource transactionAttributeSource = new AnnotationTransactionAttributeSource(false);

    // Tells us what is a "transient" exception; must be explicitly configured
    private PersistenceExceptionTranslator persistenceExceptionTranslator;

// Property accessors and RetryTransactionProvider implementation

    @Override
    public PersistenceExceptionTranslator getPersistenceExceptionTranslator() {
        return this.persistenceExceptionTranslator;
    }
    public void setPersistenceExceptionTranslator(PersistenceExceptionTranslator persistenceExceptionTranslator) {
        this.persistenceExceptionTranslator = persistenceExceptionTranslator;
    }

    @Override
    public int getMaxRetriesDefault() {
        return this.maxRetriesDefault;
    }
    public void setMaxRetriesDefault(int maxRetriesDefault) {
        this.maxRetriesDefault = maxRetriesDefault;
    }

    @Override
    public long getInitialDelayDefault() {
        return this.initialDelayDefault;
    }
    public void setInitialDelayDefault(long initialDelayDefault) {
        this.initialDelayDefault = initialDelayDefault;
    }

    @Override
    public long getMaximumDelayDefault() {
        return this.maximumDelayDefault;
    }
    public void setMaximumDelayDefault(long maximumDelayDefault) {
        this.maximumDelayDefault = maximumDelayDefault;
    }

    @Override
    public int getAttemptNumber() {
        final Integer attempt = this.attemptHolder.get();
        return attempt != null ? attempt : 0;
    }

// InitializingBean

    @Override
    public void afterPropertiesSet() throws Exception {
        if (this.persistenceExceptionTranslator == null)
            throw new IllegalArgumentException("no PersistenceExceptionTranslator configured");
    }

// Aspect

    // Ensure that this aspect is woven outside of the AnnotationTransactionAspect
    declare precedence : RetryTransactionAspect, org.springframework.transaction.aspectj.*;

    /**
     * Attempt to execute a transactional method. If the method throws any exception which is translated
     * to a subclass of TransientDataAccessException, the method will be executed again, with a delay
     * between attempts.
     */
    Object around(final Object txObject) : retryTransactionalMethodExecution(txObject) {

        // Get method info
        final MethodSignature methodSignature = (MethodSignature)thisJoinPoint.getSignature();
        final Method method = methodSignature.getMethod();

        // Get transaction attribute from @Transactional annotation
        final TransactionAttribute transactionAttribute = this.transactionAttributeSource
          .getTransactionAttribute(method, txObject.getClass());
        if (transactionAttribute == null) {
            throw new RuntimeException("no @Transactional annotation found for method "
              + method + "; required for @RetryTransaction");
        }

        // Do nothing unless this method is about to create a new transaction
        switch (transactionAttribute.getPropagationBehavior()) {
        case TransactionDefinition.PROPAGATION_REQUIRES_NEW:
            break;
        case TransactionDefinition.PROPAGATION_REQUIRED:
            if (TransactionSynchronizationManager.isActualTransactionActive()) {
                if (this.log.isTraceEnabled())
                    this.log.trace("skipping retry logic; transaction already open in @Transactional method {}", method);
                return proceed(txObject);
            }
            break;
        default:
            return proceed(txObject);
        }

        // Get @RetryTransaction annotation
        final RetryTransaction retryTransaction = AnnotationUtils.getAnnotation(method, RetryTransaction.class);
        if (retryTransaction == null)
            throw new RuntimeException("internal error: no @RetryTransaction annotation found for method " + method);

        // Get retry parameters, applying defaults if necessary
        final int maxRetries = retryTransaction.maxRetries() != -1 ?
          retryTransaction.maxRetries() : this.maxRetriesDefault;
        final long initialDelay = retryTransaction.initialDelay() != -1 ?
          retryTransaction.initialDelay() : this.initialDelayDefault;
        final long maximumDelay = retryTransaction.maximumDelay() != -1 ?
          retryTransaction.maximumDelay() : this.maximumDelayDefault;

        // Sanity check we are configured
        if (this.persistenceExceptionTranslator == null)
            throw new RuntimeException("@RetryTransaction aspect must be configured before use");

        // Perform attempts
        TransientDataAccessException transientException;
        int attempt = 1;
        do {

            // If this is not the first attempt, sleep for a while
            if (attempt > 1) {
                final long delay = this.calculateDelay(attempt, initialDelay, maximumDelay);
                if (this.log.isDebugEnabled())
                    this.log.debug("pausing {}ms before retrying @Transactional method {}", delay, method);
                this.pause(delay);
                if (this.log.isDebugEnabled())
                    this.log.debug("retrying @Transactional method {} (attempt #{})", method, attempt);
            }

            // Make attempt
            try {

                // Make next attempt
                if (this.log.isTraceEnabled())
                    this.log.trace("starting @Transactional method {} (attempt #{})", method, attempt);
                final Object[] result = new Object[1];
                this.attemptHolder.invoke(attempt, new Runnable() {
                    @Override
                    public void run() {
                        result[0] = proceed(txObject);
                    }
                });
                if (attempt > 1) {
                    if (this.log.isDebugEnabled())
                        this.log.debug("successfully completed @Transactional method {} on re-try attempt #{}", method, attempt);
                } else {
                    if (this.log.isTraceEnabled())
                        this.log.trace("successfully completed @Transactional method {} on first attempt", method);
                }

                // We're done
                return result[0];
            } catch (RuntimeException e) {

                // Handle case that Spring has already wrapped and hidden the real exception without recognizing it
                DataAccessException translatedException = null;
                if (e instanceof UncategorizedDataAccessException) {
                    final Throwable cause = ((UncategorizedDataAccessException)e).getCause();
                    if (cause instanceof RuntimeException) {
                        translatedException = this.persistenceExceptionTranslator.translateExceptionIfPossible(
                          (RuntimeException)cause);
                    }
                }

                // Translate the exception, if not already translated above
                if (translatedException == null) {
                    translatedException = e instanceof DataAccessException ?
                      (DataAccessException)e : this.persistenceExceptionTranslator.translateExceptionIfPossible(e);
                }

                // Log result
                if (this.log.isDebugEnabled()) {
                    this.log.debug("exception from @Transactional method {} on attempt #{}: {} (translates to {})",
                      method, attempt, e, translatedException != null ? translatedException.getClass().getSimpleName() : null);
                }

                // If it's not a transient exception, re-throw the original exception
                if (!(translatedException instanceof TransientDataAccessException))
                    throw e;

                // Re-throw the transient exception when we've run out of attempts
                transientException = (TransientDataAccessException)translatedException;
            }
        }
        while (attempt++ <= maxRetries);

        // All attempts failed
        this.log.error("@Transactional method {} failed after {} attempts, giving up!", method, maxRetries);
        throw transientException;
    }

// Static methods

    /**
     * Get the current transaction attempt number.
     *
     * @return transaction attempt number, or zero if this aspect is not active in the current thread
     * @deprecated Use {@link RetryTransactionProvider#getAttemptNumber} instead
     */
    public static int getAttempt() {
        final Integer attempt = RetryTransactionAspect.aspectOf().attemptHolder.get();
        return attempt != null ? attempt : 0;
    }

// Helper methods

    /**
     * Calculate how long to sleep.
     *
     * @param attempt attempt number (one-based)
     * @param initialDelay initial delay
     * @param maximumDelay maximum delay
     */
    protected long calculateDelay(int attempt, long initialDelay, long maximumDelay) {

        // Enforce sanity
        initialDelay = Math.max(initialDelay, 1);
        maximumDelay = Math.max(maximumDelay, 1);
        initialDelay = Math.min(initialDelay, maximumDelay);

        // Calculate nominal delay for this attempt, using exponential back-off; be careful to avoid overflow
        long delay = initialDelay;
        while (attempt-- > 1) {
            delay <<= 1;
            if (delay >= maximumDelay) {
                delay = maximumDelay;
                break;
            }
        }

        // Add in +/- 12.5% randomness
        final int randomRange = Math.max(1, (int)(delay >> 3));
        synchronized (this.random) {
            delay += this.random.nextInt(randomRange) - randomRange / 2;
        }

        // Enforce upper bound again
        delay = Math.min(delay, maximumDelay);

        // Done
        return delay;
    }

    /**
     * Sleep for the specified period.
     *
     * @param delay delay in milliseconds
     */
    protected void pause(long delay) {
        try {
            Thread.sleep(delay);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    /*
     * Matches the execution of any public method in a type with the @Transactional annotation, or any subtype of a type with the
     * @Transactional annotation.
     */
    private pointcut executionOfPublicMethodInTransactionalType() : execution(public * ((@Transactional *)+).*(..));

    /*
     * Matches the execution of any public method in a type with the @RetryTransaction annotation, or any subtype of a type with the
     * @RetryTransaction annotation.
     */
    private pointcut executionOfPublicMethodInRetryTransactionType() : execution(public * ((@RetryTransaction *)+).*(..));

    /*
     * Matches the execution of any method with the @Transactional annotation.
     */
    private pointcut executionOfTransactionalMethod() : execution(@Transactional * *(..));

    /*
     * Matches the execution of any method with the @RetryTransaction annotation.
     */
    private pointcut executionOfRetryTransactionMethod() : execution(@RetryTransaction * *(..));

    /*
     * Main pointcut - matched join points have both @Transactional and @RetryTransaction on method and/or type
     */
    private pointcut retryTransactionalMethodExecution(Object txObject) : this(txObject)
        && (executionOfPublicMethodInTransactionalType() || executionOfTransactionalMethod())
        && (executionOfPublicMethodInRetryTransactionType() || executionOfRetryTransactionMethod());
}