Changing pdf statistics export to new version.

This changes the export in pdf statistics to the new version,
Julian created.

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 {

	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
     */
	void around(PDDocument document) throws IOException
		: execution (* PDFReportListener.drawTable(PDDocument))
		&& args(document) {
		PDPage page = new PDPage();
		document.addPage(page);
		PDPageContentStream contentStream = new PDPageContentStream(document, page);
		contentStream.setFont(PDType1Font.HELVETICA_BOLD, 10);
		contentStream.beginText();
		createContent(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 createContent(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, -20);
        contentStream.drawString("#Rufspiele: " + data.getAnzahlRufspiele() + " (gewonnen: "
        		+ String.format("%.2f", data.getRufspieleWinPerc()) + "%)");

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

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

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

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

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

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

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

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

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

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 {

	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
     */
	void around(PDDocument document) throws IOException
		: execution (* PDFReportListener.drawTable(PDDocument))
		&& args(document) {
		PDPage page = new PDPage();
		document.addPage(page);
		PDPageContentStream contentStream = new PDPageContentStream(document, page);
		contentStream.setFont(PDType1Font.HELVETICA_BOLD, 10);
		contentStream.beginText();
		createContent(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 createContent(PDPageContentStream contentStream) throws IOException {
		OverallStatistics data = gui.model.gameDB.getOverallStatistics();

		int anzahlSpieleGesamt = data.getAnzahlSpieleGesamt();
        int anzahlSpieleGesamtGewonnen = data.getAnzahlSpieleGesamtGewonnen();
        int teuerstesRufspiel = data.getTeuerstesRufspiel();
        int teuerstesSolo = data.getTeuerstesSolo();
        int teuerstesSoloTout = data.getTeuerstesSoloTout();
        int teuerstesSoloSie = data.getTeuerstesSoloSie();
        int anzahlRufspiele = data.getAnzahlRufspiele();
        int anzahlSoli = data.getAnzahlSoli();
        int anzahlSoliTout = data.getAnzahlSoliTout();
        int anzahlSoliSie = data.getAnzahlSoliSie();
        int anzahlSoliGesamt = data.getAnzahlSoliGesamt();
        int anzahlGewonneneSoliGesamt = data.getAnzahlGewonneneSoliGesamt();
        int anzahlGewonneneRufspiele = data.getAnzahlGewonneneRufspiele();
        int anzahlGewonneneSoli = data.getAnzahlGewonneneSoli();
        int anzahlGewonneneSoliTout = data.getAnzahlGewonneneSoliTout();
        int anzahlGewonneneSoliSie = data.getAnzahlGewonneneSoliSie();
        int anzahlWeiter = data.getAnzahlWeiter();

        double sologesamtwin = (anzahlSoliGesamt) > 0 ? ((double) (anzahlGewonneneSoliGesamt) / (anzahlSoliGesamt))
                : 0;

        contentStream.moveTextPositionByAmount(50, 650);
        contentStream.drawString("#Spiele (ohne weiter): "
                + anzahlSpieleGesamt
                + " (gewonnen: "
                + String.format("%.2f",
                        (anzahlSpieleGesamt > 0 ? anzahlSpieleGesamtGewonnen
                                / ((double) anzahlSpieleGesamt) : 0) * 100)
                + "%)");

        contentStream.moveTextPositionByAmount(0, -20);
        contentStream.drawString("#Rufspiele: "
                + anzahlRufspiele
                + " (gewonnen: "
                + String.format("%.2f",
                        (anzahlRufspiele > 0 ? anzahlGewonneneRufspiele
                                / ((double) anzahlRufspiele) : 0) * 100)
                + "%)");

        contentStream.moveTextPositionByAmount(0, -20);
        contentStream.drawString("          -> teuerstes Rufspiel: "
                + teuerstesRufspiel);

        contentStream.moveTextPositionByAmount(0, -20);
        contentStream.drawString("#Soli gesamt: "
                + (anzahlSoli + anzahlSoliTout + anzahlSoliSie)
                + " (gewonnen: "
                + String.format("%.2f", sologesamtwin * 100)
                + "%)");

        contentStream.moveTextPositionByAmount(0, -20);
        contentStream.drawString("#Soli normal: "
                + anzahlSoli
                + " (gewonnen: "
                + String.format("%.2f", (anzahlSoli > 0 ? anzahlGewonneneSoli
                        / ((double) anzahlSoli) : 0) * 100)
                + "%)");

        contentStream.moveTextPositionByAmount(0, -20);
        contentStream.drawString("            -> teuerstes Solo: "
                + teuerstesSolo);

        contentStream.moveTextPositionByAmount(0, -20);
        contentStream.drawString("#Solo Tout: "
                + anzahlSoliTout
                + " (gewonnen: "
                + String.format("%.2f",
                        (anzahlSoliTout > 0 ? anzahlGewonneneSoliTout
                                / ((double) anzahlSoliTout) : 0) * 100)
                + "%)");

        contentStream.moveTextPositionByAmount(0, -20);
        contentStream.drawString("          -> teuerstes Solo Tout: "
                + teuerstesSoloTout);

        contentStream.moveTextPositionByAmount(0, -20);
        contentStream.drawString("#Solo Sie: "
                + anzahlSoliSie
                + " (gewonnen: "
                + String.format("%.2f",
                        (anzahlSoliSie > 0 ? anzahlGewonneneSoliSie
                                / ((double) anzahlSoliSie) : 0) * 100) + "%)");

        contentStream.moveTextPositionByAmount(0, -20);
        contentStream.drawString("         -> teuerstes Solo Sie: " + teuerstesSoloSie);

        contentStream.moveTextPositionByAmount(0, -20);
        contentStream.drawString("#Weiter: " + anzahlWeiter);
	}
}


code to test for actor count

code to test for actor count

/*
 * Copyright (c) 2013 original authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.eigengo.monitor.agent.akka;

import akka.actor.*;

import java.util.ArrayList;
import java.util.List;

public aspect ActorCellMonitoringAspect extends AbstractMonitoringAspect {

    // decide whether to include this ActorCell in our measurements
    private boolean includeActorPath(ActorPath actorPath) {
        if (this.includeSystemActors) return true;

        String userOrSystem = actorPath.getElements().iterator().next();
        return "user".equals(userOrSystem);
    }

    // get the tags for the cell
    private String[] getTags(final ActorPath actorPath, final Actor actor) {
        List<String> tags = new ArrayList<String>();

        // TODO: Improve detection of routed actors. This relies only on the naming :(.
        String lastPathElement = actorPath.elements().last();
        if (lastPathElement.startsWith("$")) {
            // this is routed actor.
            tags.add(actorPath.parent().toString());
            if (this.includeRoutees) tags.add(actorPath.toString());
        } else {
            // there is no supervisor
            tags.add(actorPath.toString());
        }
        if (actor != null) {
            tags.add(String.format("akka:%s.%s", actor.context().system().name(), actor.getClass().getCanonicalName()));
        }

        return tags.toArray(new String[tags.size()]);
    }

    Object around(ActorCell actorCell, Object msg) : Pointcuts.receiveMessage(actorCell, msg) {
        final ActorPath actorPath = actorCell.self().path();
        if (!includeActorPath(actorPath)) return proceed(actorCell, msg);

        // we tag by actor name
        final String[] tags = getTags(actorPath, actorCell.actor());

        // record the queue size
        counterInterface.recordGaugeValue("akka.queue.size", actorCell.numberOfMessages(), tags);
        // record the message, general and specific
        counterInterface.incrementCounter("akka.actor.delivered", tags);
        counterInterface.incrementCounter("akka.actor.delivered." + msg.getClass().getSimpleName(), tags);

        // measure the time. we're using the ``nanoTime`` call to access the high-precision timer.
        // since we're not really interested in wall time, but just some increasing measure of
        // elapsed time
        Object result = null;
        final long start = System.nanoTime();
        // result will always be ``null``, because target returns ``Unit``
        result = proceed(actorCell, msg);
        // ns or µs is too fine. ms will do for now.
        final long duration = (System.nanoTime() - start) / 1000000;

        // record the actor duration
        counterInterface.recordExecutionTime("akka.actor.duration", (int)duration, tags);
        // add gauge value of 1 with actor ref as tag, to provide 'number of actors' metric
        counterInterface.gaugeValue("akka.actor.count", tag)

        // return null would do the trick, but we want to be _proper_.
        return result;
    }

    before(ActorCell actorCell, Throwable failure) : Pointcuts.handleInvokeFailure(actorCell, failure) {
        // record the error, general and specific
        String[] tags = getTags(actorCell.self().path(), actorCell.actor());
        counterInterface.incrementCounter("akka.actor.error", tags);
        counterInterface.incrementCounter(String.format("akka.actor.error.%s", failure.getMessage()), tags);
    }

    before(Object event) : Pointcuts.eventStreamPublish(event) {
        if (event instanceof UnhandledMessage) {
            UnhandledMessage unhandledMessage = (UnhandledMessage)event;
            String[] tags = getTags(unhandledMessage.recipient().path(), null);
            counterInterface.incrementCounter("akka.actor.undelivered", tags);
            counterInterface.incrementCounter("akka.actor.undelivered." + unhandledMessage.getMessage().getClass().getSimpleName(), tags);
        }
    }

//    after() returning (ActorRef actor): execution(* akka.actor.ActorSystem.actorOf(..)) {
//        if (!includeActorPath(actor.path())) return;
//
//        final String tag = actor.path().root().toString();
//        counterInterface.incrementCounter("akka.actor.count", tag);
//    }
//
//    after() returning (ActorRef actor): execution(* akka.actor.ActorCell.actorOf(..)) {
//        if (!includeActorPath(actor.path())) return;
//
//        final String tag = actor.path().root().toString();
//        counterInterface.incrementCounter("akka.actor.count", tag);
//    }
//
//    after(ActorRef actor) : execution(* akka.actor.ActorCell.stop(..)) && args(actor) {
//        if (!includeActorPath(actor.path())) return;
//
//        final String tag = actor.path().root().toString();
//        counterInterface.decrementCounter("akka.actor.count", tag);
//    }

}

/*
 * Copyright (c) 2013 original authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.eigengo.monitor.agent.akka;

import akka.actor.*;

import java.util.ArrayList;
import java.util.List;

public aspect ActorCellMonitoringAspect extends AbstractMonitoringAspect {

    // decide whether to include this ActorCell in our measurements
    private boolean includeActorPath(ActorPath actorPath) {
        if (this.includeSystemActors) return true;

        String userOrSystem = actorPath.getElements().iterator().next();
        return "user".equals(userOrSystem);
    }

    // get the tags for the cell
    private String[] getTags(final ActorPath actorPath, final Actor actor) {
        List<String> tags = new ArrayList<String>();

        // TODO: Improve detection of routed actors. This relies only on the naming :(.
        String lastPathElement = actorPath.elements().last();
        if (lastPathElement.startsWith("$")) {
            // this is routed actor.
            tags.add(actorPath.parent().toString());
            if (this.includeRoutees) tags.add(actorPath.toString());
        } else {
            // there is no supervisor
            tags.add(actorPath.toString());
        }
        if (actor != null) {
            tags.add(String.format("akka:%s.%s", actor.context().system().name(), actor.getClass().getCanonicalName()));
        }

        return tags.toArray(new String[tags.size()]);
    }

    Object around(ActorCell actorCell, Object msg) : Pointcuts.receiveMessage(actorCell, msg) {
        final ActorPath actorPath = actorCell.self().path();
        if (!includeActorPath(actorPath)) return proceed(actorCell, msg);

        // we tag by actor name
        final String[] tags = getTags(actorPath, actorCell.actor());

        // record the queue size
        counterInterface.recordGaugeValue("akka.queue.size", actorCell.numberOfMessages(), tags);
        // record the message, general and specific
        counterInterface.incrementCounter("akka.actor.delivered", tags);
        counterInterface.incrementCounter("akka.actor.delivered." + msg.getClass().getSimpleName(), tags);

        // measure the time. we're using the ``nanoTime`` call to access the high-precision timer.
        // since we're not really interested in wall time, but just some increasing measure of
        // elapsed time
        Object result = null;
        final long start = System.nanoTime();
        // result will always be ``null``, because target returns ``Unit``
        result = proceed(actorCell, msg);
        // ns or µs is too fine. ms will do for now.
        final long duration = (System.nanoTime() - start) / 1000000;

        // record the actor duration
        counterInterface.recordExecutionTime("akka.actor.duration", (int)duration, tags);

        // return null would do the trick, but we want to be _proper_.
        return result;
    }

    before(ActorCell actorCell, Throwable failure) : Pointcuts.handleInvokeFailure(actorCell, failure) {
        // record the error, general and specific
        String[] tags = getTags(actorCell.self().path(), actorCell.actor());
        counterInterface.incrementCounter("akka.actor.error", tags);
        counterInterface.incrementCounter(String.format("akka.actor.error.%s", failure.getMessage()), tags);
    }

    before(Object event) : Pointcuts.eventStreamPublish(event) {
        if (event instanceof UnhandledMessage) {
            UnhandledMessage unhandledMessage = (UnhandledMessage)event;
            String[] tags = getTags(unhandledMessage.recipient().path(), null);
            counterInterface.incrementCounter("akka.actor.undelivered", tags);
            counterInterface.incrementCounter("akka.actor.undelivered." + unhandledMessage.getMessage().getClass().getSimpleName(), tags);
        }
    }

    after() returning (ActorRef actor): execution(* akka.actor.ActorSystem.actorOf(..)) {
        if (!includeActorPath(actor.path())) return;

        final String tag = actor.path().root().toString();
        counterInterface.incrementCounter("akka.actor.count", tag);
    }

    after() returning (ActorRef actor): execution(* akka.actor.ActorCell.actorOf(..)) {
        if (!includeActorPath(actor.path())) return;

        final String tag = actor.path().root().toString();
        counterInterface.incrementCounter("akka.actor.count", tag);
    }

    after(ActorRef actor) : execution(* akka.actor.ActorCell.stop(..)) && args(actor) {
        if (!includeActorPath(actor.path())) return;

        final String tag = actor.path().root().toString();
        counterInterface.decrementCounter("akka.actor.count", tag);
    }

}


Dispatcher monitoring

Dispatcher monitoring

/*
 * Copyright (c) 2013 original authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.eigengo.monitor.agent.akka;

import akka.dispatch.MessageDispatcher;

import java.util.concurrent.ForkJoinPool;

privileged aspect DispatcherMonitoringAspect extends AbstractMonitoringAspect issingleton() {

    before(MessageDispatcher dispatcher) : execution(* akka.dispatch.MessageDispatcher.dispatch(..)) && target(dispatcher) {
        System.out.println("*****Dispatching a task");
    }

    before(ForkJoinPool pool) : execution(* scala.concurrent.forkjoin.ForkJoinPool.execute(..)) && target(pool) {
        System.out.println("*****Active threads>> " + pool.getActiveThreadCount());
        System.out.println("*****Queue size>> " + pool.getQueuedTaskCount());
        System.out.println("*****Running thread count>> " + pool.getRunningThreadCount());
    }

}

/*
 * Copyright (c) 2013 original authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.eigengo.monitor.agent.akka;

public aspect DispatcherMonitoringAspect extends AbstractMonitoringAspect {

}


finish StatOverallGraphical

finish StatOverallGraphical

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.LinearGradientPaint;

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

import model.SystemValues.WIN;
import model.db.DataObject;
import de.erichseifert.gral.data.DataTable;
import de.erichseifert.gral.plots.BarPlot;
import de.erichseifert.gral.plots.PiePlot;
import de.erichseifert.gral.ui.InteractivePanel;
import de.erichseifert.gral.plots.BarPlot.BarRenderer;
import de.erichseifert.gral.plots.PiePlot.PieSliceRenderer;
import de.erichseifert.gral.plots.points.PointRenderer;
import de.erichseifert.gral.util.GraphicsUtils;
import de.erichseifert.gral.util.Insets2D;
import de.erichseifert.gral.util.Location;
import view.GUI;
import view.UIUpdater;
import model.db.GameData;

public privileged aspect StatOverallGraphical {

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

	private static final Color COLOR1 = Color.GREEN;

	private static DataTable playedTypes = new DataTable(Integer.class,
			String.class);
	private static DataTable mostExpsvGame = new DataTable(Integer.class,
			Integer.class, String.class);
	private static DataTable wonGames = new DataTable(Integer.class,
			Double.class, String.class);

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

	after(JTabbedPane tabbedPane):
			execution(public static void StatisticsHelper.StatisticsPaneCreated(JTabbedPane))
			&& args(tabbedPane) {
		panel.setLayout(new GridLayout(2, 2));

		updateData();
		panel.add(new InteractivePanel(createExpGameBarPlot()));
		panel.add(new InteractivePanel(createWonGamesBarPlot()));
		panel.add(new InteractivePanel(createPlayedTypesPlot()));

		tabbedPane.addTab("OverallGrafik", panel);
	}

	after() : execution(* UIUpdater.run()) {
		updateData();
	}

	private static void updateData() {
		StatsData data = gui.model.getGameData().getOverallStatisticsData();

		while (playedTypes.getRowCount() > 0) {
			playedTypes.removeLast();
		}
		playedTypes.add(data.anzahlRufspiele, "Rufspiele");
		playedTypes.add(data.anzahlSolo, "Soli");
		playedTypes.add(data.anzahlSoloTout, "Soli Tout");
		playedTypes.add(data.anzahlSoloSie, "Soli Sie");
		playedTypes.add(data.anzahlWeiter, "Weiter");

		while (mostExpsvGame.getRowCount() > 0) {
			mostExpsvGame.removeLast();
		}
		mostExpsvGame.add(1, data.teuerstesRufspiel, "Rufspiel");
		mostExpsvGame.add(2, data.teuerstesSolo, "Solo");
		mostExpsvGame.add(3, data.teuerstesSoloTout, "Solo Tout");
		mostExpsvGame.add(4, data.teuerstesSoloSie, "Solo Sie");

		// percentage of won games by gametype
		double gesamt = (data.anzahlSpieleGesamt > 0 ? data.anzahlSpieleGesamtGewonnen
				/ ((double) data.anzahlSpieleGesamt)
				: 0) * 100;
		double rufspiele = (data.anzahlRufspiele > 0 ? data.anzahlGewonneneRufspiele
				/ ((double) data.anzahlRufspiele)
				: 0) * 100;
		double soli_gesamt = ((data.anzahlSolo + data.anzahlSoloSie + data.anzahlSoloTout) > 0 ? ((data.anzahlGewonneneSoli
				+ data.anzahlGewonneneSoliTout + data.anzahlSoloSie) / 1.0 / (data.anzahlSolo
				+ data.anzahlSoloSie + data.anzahlSoloTout))
				: 0) * 100;
		double soli_normal = (data.anzahlSolo > 0 ? data.anzahlGewonneneSoli
				/ ((double) data.anzahlSolo) : 0) * 100;
		double soli_tout = (data.anzahlSoloTout > 0 ? data.anzahlGewonneneSoliTout
				/ ((double) data.anzahlSoloTout)
				: 0) * 100;
		double soli_sie = (data.anzahlSoloSie > 0 ? data.anzahlSoloSie
				/ ((double) data.anzahlSoloSie) : 0) * 100;

		while (wonGames.getRowCount() > 0) {
			wonGames.removeLast();
		}
		wonGames.add(1, gesamt, "Gesamt");
		wonGames.add(2, rufspiele, "Rufspiele");
		wonGames.add(3, soli_gesamt, "Soli gesamt");
		wonGames.add(4, soli_normal, "Soli normal");
		wonGames.add(5, soli_tout, "Soli Tout");
		wonGames.add(6, soli_sie, "Soli Sie");
	}

	private static PiePlot createPlayedTypesPlot() {
		PiePlot plot = new PiePlot(playedTypes);

		PointRenderer pointRenderer = plot.getPointRenderer(playedTypes);
		pointRenderer.setValueVisible(true);
		pointRenderer.setValueColumn(1);

		// Format plot
		plot.getTitle().setText("Anzahl gespielter Spieltypen");
		// Change plot size
		plot.setRadius(0.9);
		// Display a legend
		plot.setLegendVisible(true);
		// Add some margin to the plot area
		plot.setInsets(new Insets2D.Double(20.0, 40.0, 40.0, 40.0));

		PieSliceRenderer pieSliceRenderer = (PieSliceRenderer) plot
				.getPointRenderer(playedTypes);

		// Change relative size of inner region
		pieSliceRenderer.setInnerRadius(0.4);
		// Change the width of gaps between segments
		pieSliceRenderer.setGap(0.2);
		// Show labels
		pieSliceRenderer.setValueVisible(true);
		pieSliceRenderer.setValueColor(Color.WHITE);
		pieSliceRenderer.setValueFont(Font.decode(null).deriveFont(Font.BOLD));

		return plot;
	}

	public BarPlot createExpGameBarPlot() {
		// Create new bar plot
		BarPlot plot = new BarPlot(mostExpsvGame);

		// Format plot
		plot.getTitle().setText("Teuerstes Spiel pro Spieltyp");
		plot.setInsets(new Insets2D.Double(40.0, 40.0, 40.0, 40.0));
		plot.setBarWidth(0.075);

		// Format bars
		PointRenderer pointRenderer = plot.getPointRenderer(mostExpsvGame);
		BarRenderer barRenderer = (BarRenderer) pointRenderer;

		barRenderer.setColor(new LinearGradientPaint(0f, 0f, 0f, 1f,
				new float[] { 0.0f, 1.0f }, new Color[] { COLOR1,
						GraphicsUtils.deriveBrighter(COLOR1) }));
		barRenderer.setBorderStroke(new BasicStroke(3f));
		barRenderer.setBorderColor(new LinearGradientPaint(0f, 0f, 0f, 1f,
				new float[] { 0.0f, 1.0f }, new Color[] {
						GraphicsUtils.deriveBrighter(COLOR1), COLOR1 }));

		pointRenderer.setValueVisible(true);
		pointRenderer.setValueColumn(2);

		pointRenderer.setValueLocation(Location.CENTER);
		pointRenderer.setValueColor(GraphicsUtils.deriveDarker(COLOR1));
		pointRenderer.setValueFont(Font.decode(null).deriveFont(Font.BOLD));

		return plot;
	}

	public BarPlot createWonGamesBarPlot() {
		// Create new bar plot
		BarPlot plot = new BarPlot(wonGames);

		// Format plot
		plot.getTitle().setText("Gewonnene Spiele pro Spieltyp (in %)");
		plot.setInsets(new Insets2D.Double(40.0, 40.0, 40.0, 40.0));
		plot.setBarWidth(0.075);

		// Format bars
		PointRenderer pointRenderer = plot.getPointRenderer(wonGames);
		BarRenderer barRenderer = (BarRenderer) pointRenderer;

		barRenderer.setColor(new LinearGradientPaint(0f, 0f, 0f, 1f,
				new float[] { 0.0f, 1.0f }, new Color[] { COLOR1,
						GraphicsUtils.deriveBrighter(COLOR1) }));
		barRenderer.setBorderStroke(new BasicStroke(3f));
		barRenderer.setBorderColor(new LinearGradientPaint(0f, 0f, 0f, 1f,
				new float[] { 0.0f, 1.0f }, new Color[] {
						GraphicsUtils.deriveBrighter(COLOR1), COLOR1 }));

		pointRenderer.setValueVisible(true);
		pointRenderer.setValueColumn(2);

		pointRenderer.setValueLocation(Location.CENTER);
		pointRenderer.setValueColor(GraphicsUtils.deriveDarker(COLOR1));
		pointRenderer.setValueFont(Font.decode(null).deriveFont(Font.BOLD));

		return plot;
	}

	public StatsData GameData.getOverallStatisticsData() {
		int anzahlSpieleGesamt = 0;
		int anzahlSpieleGesamtGewonnen = 0;
		int teuerstesRufspiel = 0;
		int teuerstesSolo = 0;
		int teuerstesSoloTout = 0;
		int teuerstesSoloSie = 0;
		int anzahlRufspiele = 0;
		int anzahlSolo = 0;
		int anzahlSoloTout = 0;
		int anzahlSoloSie = 0;
		int anzahlGewonneneRufspiele = 0;
		int anzahlGewonneneSoli = 0;
		int anzahlGewonneneSoliTout = 0;
		int anzahlWeiter = 0;

		for (DataObject obj : data) {
			switch (obj.getGameKind()) {
			case "Rufspiel":
				anzahlRufspiele++;
				anzahlSpieleGesamt++;
				if (obj.getGameWon() == WIN.PLAYER) {
					anzahlGewonneneRufspiele++;
					anzahlSpieleGesamtGewonnen++;
				}
				if (obj.getGameValue() > teuerstesRufspiel) {
					teuerstesRufspiel = obj.getGameValue();
				}
				break;
			case "Solo":
				anzahlSolo++;
				anzahlSpieleGesamt++;
				if (obj.getGameWon() == WIN.PLAYER) {
					anzahlGewonneneSoli++;
					anzahlSpieleGesamtGewonnen++;
				}
				if (obj.getGameValue() > teuerstesSolo) {
					teuerstesSolo = obj.getGameValue();
				}
				break;
			case "Solo Tout":
				anzahlSpieleGesamt++;
				if (obj.getGameWon() == WIN.PLAYER) {
					anzahlGewonneneSoliTout++;
					anzahlSpieleGesamtGewonnen++;
				}
				if (obj.getGameValue() > teuerstesSoloTout) {
					teuerstesSoloTout = obj.getGameValue();
				}
				anzahlSoloTout++;
				break;
			case "Solo Sie":
				anzahlSpieleGesamt++;
				anzahlSpieleGesamtGewonnen++;
				anzahlSoloSie++;
				if (obj.getGameValue() > teuerstesSoloSie) {
					teuerstesSoloSie = obj.getGameValue();
				}
				break;
			case "weiter":
				anzahlWeiter++;
				break;
			}
		}

		return new StatsData(anzahlSpieleGesamt, anzahlSpieleGesamtGewonnen,
				teuerstesRufspiel, teuerstesSolo, teuerstesSoloTout,
				teuerstesSoloSie, anzahlRufspiele, anzahlSolo, anzahlSoloTout,
				anzahlSoloSie, anzahlGewonneneRufspiele, anzahlGewonneneSoli,
				anzahlGewonneneSoliTout, anzahlWeiter);
	}

	private static class StatsData {
		protected int anzahlSpieleGesamt = 0;
		protected int anzahlSpieleGesamtGewonnen = 0;
		protected int teuerstesRufspiel = 0;
		protected int teuerstesSolo = 0;
		protected int teuerstesSoloTout = 0;
		protected int teuerstesSoloSie = 0;
		protected int anzahlRufspiele = 0;
		protected int anzahlSolo = 0;
		protected int anzahlSoloTout = 0;
		protected int anzahlSoloSie = 0;
		protected int anzahlGewonneneRufspiele = 0;
		protected int anzahlGewonneneSoli = 0;
		protected int anzahlGewonneneSoliTout = 0;
		protected int anzahlWeiter = 0;

		public StatsData(int anzahlSpieleGesamt,
				int anzahlSpieleGesamtGewonnen, int teuerstesRufspiel,
				int teuerstesSolo, int teuerstesSoloTout, int teuerstesSoloSie,
				int anzahlRufspiele, int anzahlSolo, int anzahlSoloTout,
				int anzahlSoloSie, int anzahlGewonneneRufspiele,
				int anzahlGewonneneSoli, int anzahlGewonneneSoliTout,
				int anzahlWeiter) {
			this.anzahlSpieleGesamt = anzahlSpieleGesamt;
			this.anzahlSpieleGesamtGewonnen = anzahlSpieleGesamtGewonnen;
			this.teuerstesRufspiel = teuerstesRufspiel;
			this.teuerstesSolo = teuerstesSolo;
			this.teuerstesSoloTout = teuerstesSoloTout;
			this.teuerstesSoloSie = teuerstesSoloSie;
			this.anzahlRufspiele = anzahlRufspiele;
			this.anzahlSolo = anzahlSolo;
			this.anzahlSoloTout = anzahlSoloTout;
			this.anzahlSoloSie = anzahlSoloSie;
			this.anzahlGewonneneRufspiele = anzahlGewonneneRufspiele;
			this.anzahlGewonneneSoli = anzahlGewonneneSoli;
			this.anzahlGewonneneSoliTout = anzahlGewonneneSoliTout;
			this.anzahlWeiter = anzahlWeiter;
		}
	}
}

import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;

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

import model.SystemValues.WIN;
import model.db.DataObject;
import de.erichseifert.gral.data.DataTable;
import de.erichseifert.gral.plots.PiePlot;
import de.erichseifert.gral.ui.InteractivePanel;
import de.erichseifert.gral.plots.PiePlot.PieSliceRenderer;
import de.erichseifert.gral.util.Insets2D;
import view.GUI;
import view.UIUpdater;
import model.db.GameData;

public privileged aspect StatOverallGraphical {

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

    @SuppressWarnings("unchecked")
    private static DataTable playedTypesTable = new DataTable(Integer.class);

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

    after(JTabbedPane tabbedPane):
        execution(public static void StatisticsHelper.StatisticsPaneCreated(JTabbedPane))
        && args(tabbedPane) {
        panel.setLayout(new GridLayout(1, 2));

        panel.add(new InteractivePanel(createPlayedTypesPlot()));

        tabbedPane.addTab("OverallGrafik", panel);
    }

    after() : execution(* UIUpdater.run()) {
        updateData();
    }

    private static void updateData() {
        StatsData data = gui.model.getGameData().getOverallStatisticsData();

        playedTypesTable.clear();
        playedTypesTable.add(data.anzahlRufspiele);
        playedTypesTable.add(data.anzahlSolo);
        playedTypesTable.add(data.anzahlSoloTout);
        playedTypesTable.add(data.anzahlSoloSie);
        playedTypesTable.add(data.anzahlWeiter);
    }

    private static PiePlot createPlayedTypesPlot() {
        updateData();
        PiePlot plot = new PiePlot(playedTypesTable);

        // Format plot
        plot.getTitle().setText("Anzahl gespielter Spieltypen");
        // Change plot size
        plot.setRadius(0.9);
        // Display a legend
        plot.setLegendVisible(true);
        // Add some margin to the plot area
        plot.setInsets(new Insets2D.Double(20.0, 40.0, 40.0, 40.0));

        PieSliceRenderer pointRenderer = (PieSliceRenderer) plot.getPointRenderer(playedTypesTable);
        // Change relative size of inner region
        pointRenderer.setInnerRadius(0.4);
        // Change the width of gaps between segments
        pointRenderer.setGap(0.2);
        // Show labels
        pointRenderer.setValueVisible(true);
        pointRenderer.setValueColor(Color.WHITE);
        pointRenderer.setValueFont(Font.decode(null).deriveFont(Font.BOLD));

        return plot;
    }

    public StatsData GameData.getOverallStatisticsData() {
        int anzahlSpieleGesamt = 0;
        int anzahlSpieleGesamtGewonnen = 0;
        int teuerstesRufspiel = 0;
        int teuerstesSolo = 0;
        int teuerstesSoloTout = 0;
        int teuerstesSoloSie = 0;
        int anzahlRufspiele = 0;
        int anzahlSolo = 0;
        int anzahlSoloTout = 0;
        int anzahlSoloSie = 0;
        int anzahlGewonneneRufspiele = 0;
        int anzahlGewonneneSoli = 0;
        int anzahlGewonneneSoliTout = 0;
        int anzahlWeiter = 0;

        for (DataObject obj : data) {
            switch (obj.getGameKind()) {
            case "Rufspiel":
                anzahlRufspiele++;
                anzahlSpieleGesamt++;
                if (obj.getGameWon() == WIN.PLAYER) {
                    anzahlGewonneneRufspiele++;
                    anzahlSpieleGesamtGewonnen++;
                }
                if (obj.getGameValue() > teuerstesRufspiel) {
                    teuerstesRufspiel = obj.getGameValue();
                }
                break;
            case "Solo":
                anzahlSolo++;
                anzahlSpieleGesamt++;
                if (obj.getGameWon() == WIN.PLAYER) {
                    anzahlGewonneneSoli++;
                    anzahlSpieleGesamtGewonnen++;
                }
                if (obj.getGameValue() > teuerstesSolo) {
                    teuerstesSolo = obj.getGameValue();
                }
                break;
            case "Solo Tout":
                anzahlSpieleGesamt++;
                if (obj.getGameWon() == WIN.PLAYER) {
                    anzahlGewonneneSoliTout++;
                    anzahlSpieleGesamtGewonnen++;
                }
                if (obj.getGameValue() > teuerstesSoloTout) {
                    teuerstesSoloTout = obj.getGameValue();
                }
                anzahlSoloTout++;
                break;
            case "Solo Sie":
                anzahlSpieleGesamt++;
                anzahlSpieleGesamtGewonnen++;
                anzahlSoloSie++;
                if (obj.getGameValue() > teuerstesSoloSie) {
                    teuerstesSoloSie = obj.getGameValue();
                }
                break;
            case "weiter":
                anzahlWeiter++;
                break;
            }
        }

        double sologesamtwin = (anzahlSolo + anzahlSoloSie + anzahlSoloTout) > 0 ? ((anzahlGewonneneSoli
                + anzahlGewonneneSoliTout + anzahlSoloSie) / 1.0 / (anzahlSolo
                + anzahlSoloSie + anzahlSoloTout))
                : 0;

        return new StatsData(anzahlSpieleGesamt, anzahlSpieleGesamtGewonnen,
                teuerstesRufspiel, teuerstesSolo, teuerstesSoloTout,
                teuerstesSoloSie, anzahlRufspiele, anzahlSolo, anzahlSoloTout,
                anzahlSoloSie, anzahlGewonneneRufspiele, anzahlGewonneneSoli,
                anzahlGewonneneSoliTout, anzahlWeiter);
    }

    private static class StatsData {
        protected int anzahlSpieleGesamt = 0;
        protected int anzahlSpieleGesamtGewonnen = 0;
        protected int teuerstesRufspiel = 0;
        protected int teuerstesSolo = 0;
        protected int teuerstesSoloTout = 0;
        protected int teuerstesSoloSie = 0;
        protected int anzahlRufspiele = 0;
        protected int anzahlSolo = 0;
        protected int anzahlSoloTout = 0;
        protected int anzahlSoloSie = 0;
        protected int anzahlGewonneneRufspiele = 0;
        protected int anzahlGewonneneSoli = 0;
        protected int anzahlGewonneneSoliTout = 0;
        protected int anzahlWeiter = 0;

        public StatsData(int anzahlSpieleGesamt,
                int anzahlSpieleGesamtGewonnen, int teuerstesRufspiel,
                int teuerstesSolo, int teuerstesSoloTout, int teuerstesSoloSie,
                int anzahlRufspiele, int anzahlSolo, int anzahlSoloTout,
                int anzahlSoloSie, int anzahlGewonneneRufspiele,
                int anzahlGewonneneSoli, int anzahlGewonneneSoliTout,
                int anzahlWeiter) {
            this.anzahlSpieleGesamt = anzahlSpieleGesamt;
            this.anzahlSpieleGesamtGewonnen = anzahlSpieleGesamtGewonnen;
            this.teuerstesRufspiel = teuerstesRufspiel;
            this.teuerstesSolo = teuerstesSolo;
            this.teuerstesSoloTout = teuerstesSoloTout;
            this.teuerstesSoloSie = teuerstesSoloSie;
            this.anzahlRufspiele = anzahlRufspiele;
            this.anzahlSolo = anzahlSolo;
            this.anzahlSoloTout = anzahlSoloTout;
            this.anzahlSoloSie = anzahlSoloSie;
            this.anzahlGewonneneRufspiele = anzahlGewonneneRufspiele;
            this.anzahlGewonneneSoli = anzahlGewonneneSoli;
            this.anzahlGewonneneSoliTout = anzahlGewonneneSoliTout;
            this.anzahlWeiter = anzahlWeiter;
        }
    }
}


changed the logging of ppi-related process instance to only do so, if there are actually ppis defined on the process definition. This way, this feature is also switched off, if you are not using the PPI engine configuration.

/* Copyright 2012 Thorben Lindhauer
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package de.unipotsdam.hpi.thorben.ppi.aspects;

import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;

import de.unipotsdam.hpi.thorben.ppi.measure.instance.entity.PPIProcessInstanceEntity;

public aspect ProcessInstanceAspect {

	pointcut newInstance(ProcessDefinitionEntity processDefinition) : target(processDefinition) && call(ExecutionEntity ProcessDefinitionEntity.createProcessInstance(String, ActivityImpl));

	after(ProcessDefinitionEntity processDefinition) returning (ExecutionEntity processInstance): newInstance(processDefinition) {
		if (!processDefinition.getPPIs().isEmpty()) {
			PPIProcessInstanceEntity instanceEntity = PPIProcessInstanceEntity
					.fromExecution(processInstance);
			CommandContext commandContext = Context.getCommandContext();
			commandContext.getDbSqlSession().insert(instanceEntity);
		}
	}
}

/* Copyright 2012 Thorben Lindhauer
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package de.unipotsdam.hpi.thorben.ppi.aspects;

import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;

import de.unipotsdam.hpi.thorben.ppi.measure.instance.entity.PPIProcessInstanceEntity;

public aspect ProcessInstanceAspect {

	pointcut newInstance(ProcessDefinitionEntity processDefinition) : target(processDefinition) && call(ExecutionEntity ProcessDefinitionEntity.createProcessInstance(String, ActivityImpl));
	after(ProcessDefinitionEntity processDefinition) returning (ExecutionEntity processInstance): newInstance(processDefinition) {
		PPIProcessInstanceEntity instanceEntity = PPIProcessInstanceEntity.fromExecution(processInstance);
		CommandContext commandContext = Context.getCommandContext();
		commandContext
        .getDbSqlSession()
        .insert(instanceEntity);
	}
}


removed DummyAspect

removed DummyAspect

/**
 * Copyright 2010 CosmoCode GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package de.cosmocode.palava.core.aop;

/**
 * Used to check whether {@link AbstractPalavaAspect} works as aspected.
 * Just switch from abstract to final to enable.
 *
 * @author Willi Schoenborn
 */
abstract aspect DummyAspect extends AbstractPalavaAspect issingleton() {

}


Don't index Scala binary files for Scala special types.

Exclude classifies for
* anonymous classes (`$anonfun`)
* top-level objects (`*$.class`)
* trait imll classes (`..$class.class`)

Fixed #1001035.

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

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

import org.eclipse.core.runtime.IPath;
import org.eclipse.jdt.core.search.SearchDocument;
import org.eclipse.jdt.internal.core.search.indexing.AbstractIndexer;
import org.eclipse.jdt.internal.core.search.JavaSearchParticipant;

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

@SuppressWarnings("restriction")
public aspect IndexerProviderAspect {

  pointcut indexDocument(SearchDocument document, IPath indexPath) :
    execution(public void JavaSearchParticipant.indexDocument(SearchDocument, IPath)) &&
    args(document, indexPath);

  void around(SearchDocument document, IPath indexPath) :
    indexDocument(document, indexPath) {

    String path = document.getPath();
    if (path.endsWith(".scala")) {
      for (IIndexerFactory provider : IndexerProviderRegistry.getInstance().getProviders()) {
        try {
          AbstractIndexer indexer = provider.createIndexer(document);
          indexer.indexDocument();
        } catch (Throwable t) {
          ScalaJDTWeavingPlugin.logException(t);
        }
      }
    } else if (!isScalaArtifact(path)) {
      proceed(document, indexPath);
    }
  }

  private boolean isScalaArtifact(String path) {
    return path.endsWith(".class")
        && (path.endsWith("$.class")          // top-level object
            || path.endsWith("$class.class")  // trait implementation class
            || path.contains("$anon"));       // anonymous class or function
  }
}

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

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

import org.eclipse.core.runtime.IPath;
import org.eclipse.jdt.core.search.SearchDocument;
import org.eclipse.jdt.internal.core.search.indexing.AbstractIndexer;
import org.eclipse.jdt.internal.core.search.JavaSearchParticipant;

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

@SuppressWarnings("restriction")
public aspect IndexerProviderAspect {

  pointcut indexDocument(SearchDocument document, IPath indexPath) :
    execution(public void JavaSearchParticipant.indexDocument(SearchDocument, IPath)) &&
    args(document, indexPath);

  void around(SearchDocument document, IPath indexPath) :
    indexDocument(document, indexPath) {

    String path = document.getPath();
    if (path.endsWith(".scala")) {
      for (IIndexerFactory provider : IndexerProviderRegistry.getInstance().getProviders()) {
        try {
          AbstractIndexer indexer = provider.createIndexer(document);
          indexer.indexDocument();
        } catch (Throwable t) {
          ScalaJDTWeavingPlugin.logException(t);
        }
      }
    } else {
      proceed(document, indexPath);
    }
  }
}


Attempt to fix duplicate setRollbackOnly calls

/**
 * palava - a java-php-bridge
 * Copyright (C) 2007-2010  CosmoCode GmbH
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA  02110-1301, USA.
 */

package de.cosmocode.palava.jta;

import javax.transaction.NotSupportedException;
import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

import org.aspectj.lang.annotation.SuppressAjWarnings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.google.inject.Provider;

import de.cosmocode.palava.core.aop.AbstractPalavaAspect;

public abstract aspect AbstractUserTransactionAspect extends AbstractPalavaAspect issingleton() {

    private static final Logger LOG = LoggerFactory.getLogger(AbstractUserTransactionAspect.class);

    private Provider<UserTransaction> provider;

    @Inject
    void setProvider(Provider<UserTransaction> provider) {
        this.provider = Preconditions.checkNotNull(provider, "Provider");
    }

    protected abstract pointcut transactional();

    @SuppressAjWarnings("adviceDidNotMatch")
    Object around(): transactional() {
        final UserTransaction tx = provider.get();
        LOG.trace("Using transaction {}", tx);

        final boolean local;

        try {
            local = tx.getStatus() == Status.STATUS_NO_TRANSACTION;
        } catch (SystemException e) {
            throw new IllegalStateException(e);
        }

        if (local) {
            LOG.trace("Beginning automatic transaction {}", tx);
            try {
                tx.begin();
            } catch (NotSupportedException e) {
                throw new IllegalStateException(e);
            } catch (SystemException e) {
                throw new IllegalStateException(e);
            }
        } else {
            LOG.trace("Transaction {} already active", tx);
        }

        final Object returnValue;

        try {
            returnValue = proceed();
        } catch (Exception e) {
            LOG.error("Exception inside automatic transaction context", e);
            try {
                if (local &&
                    (tx.getStatus() == Status.STATUS_ACTIVE || tx.getStatus() == Status.STATUS_MARKED_ROLLBACK)) {
                    LOG.info("Rolling back local/active transaction {}", tx);
                    tx.rollback();
                } else if (tx.getStatus() != Status.STATUS_ROLLEDBACK || tx.getStatus() != Status.STATUS_ROLLING_BACK) {
                    LOG.debug("Setting transaction {} as rollback only", tx);
                    tx.setRollbackOnly();
                }
            } catch (SystemException inner) {
                throw new IllegalStateException(inner);
            }
            throw new IllegalStateException(e);
        }

        final int status;

        try {
            status = tx.getStatus();
        } catch (SystemException e) {
            throw new IllegalStateException(e);
        }

        if (local) {
            if (status == Status.STATUS_MARKED_ROLLBACK) {
                try {
                    LOG.trace("Rolling back marked transaction {}", tx);
                    tx.rollback();
                } catch (SystemException e) {
                    throw new IllegalStateException(e);
                }
            } else {
                try {
                    tx.commit();
                    LOG.trace("Committed automatic transaction {}", tx);
                } catch (Exception e) {
                    LOG.error("Commit in automatic transaction context failed", e);
                    try {
                        LOG.info("Rolling back transaction {}", tx);
                        tx.rollback();
                    } catch (SystemException inner) {
                        throw new IllegalStateException(inner);
                    }
                    throw new IllegalStateException(e);
                }
            }
        }

        return returnValue;
    }

}

/**
 * palava - a java-php-bridge
 * Copyright (C) 2007-2010  CosmoCode GmbH
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA  02110-1301, USA.
 */

package de.cosmocode.palava.jta;

import javax.transaction.NotSupportedException;
import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

import org.aspectj.lang.annotation.SuppressAjWarnings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.google.inject.Provider;

import de.cosmocode.palava.core.aop.AbstractPalavaAspect;

public abstract aspect AbstractUserTransactionAspect extends AbstractPalavaAspect issingleton() {

    private static final Logger LOG = LoggerFactory.getLogger(AbstractUserTransactionAspect.class);

    private Provider<UserTransaction> provider;

    @Inject
    void setProvider(Provider<UserTransaction> provider) {
        this.provider = Preconditions.checkNotNull(provider, "Provider");
    }

    protected abstract pointcut transactional();

    @SuppressAjWarnings("adviceDidNotMatch")
    Object around(): transactional() {
        final UserTransaction tx = provider.get();
        LOG.trace("Using transaction {}", tx);

        final boolean local;

        try {
            local = tx.getStatus() == Status.STATUS_NO_TRANSACTION;
        } catch (SystemException e) {
            throw new IllegalStateException(e);
        }

        if (local) {
            LOG.trace("Beginning automatic transaction {}", tx);
            try {
                tx.begin();
            } catch (NotSupportedException e) {
                throw new IllegalStateException(e);
            } catch (SystemException e) {
                throw new IllegalStateException(e);
            }
        } else {
            LOG.trace("Transaction {} already active", tx);
        }

        final Object returnValue;

        try {
            returnValue = proceed();
        } catch (Exception e) {
            LOG.error("Exception inside automatic transaction context", e);
            try {
                if (local && tx.getStatus() == Status.STATUS_ACTIVE) {
                    LOG.info("Rolling back local/active transaction {}", tx);
                    tx.rollback();
                } else {
                    LOG.debug("Setting transaction {} as rollback only", tx);
                    tx.setRollbackOnly();
                }
            } catch (SystemException inner) {
                throw new IllegalStateException(inner);
            }
            throw new IllegalStateException(e);
        }

        final int status;

        try {
            status = tx.getStatus();
        } catch (SystemException e) {
            throw new IllegalStateException(e);
        }

        if (local) {
            if (status == Status.STATUS_MARKED_ROLLBACK) {
                try {
                    LOG.trace("Rolling back marked transaction {}", tx);
                    tx.rollback();
                } catch (SystemException e) {
                    throw new IllegalStateException(e);
                }
            } else {
                try {
                    tx.commit();
                    LOG.trace("Committed automatic transaction {}", tx);
                } catch (Exception e) {
                    LOG.error("Commit in automatic transaction context failed", e);
                    try {
                        LOG.info("Rolling back transaction {}", tx);
                        tx.rollback();
                    } catch (SystemException inner) {
                        throw new IllegalStateException(inner);
                    }
                    throw new IllegalStateException(e);
                }
            }
        }

        return returnValue;
    }

}


comments for RemoveLastDealer

comments for RemoveLastDealer

public privileged aspect RemoveLastDealer {

    /** decrease dealer when game is removed */
    before() : execution (* RemoveLastGameListener.actionPerformed(*)) {
      Dealer.dealerIndex--;
      if (Dealer.dealerIndex < 0) {
          Dealer.dealerIndex = 3;
      }
      Dealer.updateShownDealer();
    }
}

public privileged aspect RemoveLastDealer {

    before() : execution (* RemoveLastGameListener.actionPerformed(*)) {
      Dealer.dealerIndex--;
      if (Dealer.dealerIndex < 0) {
          Dealer.dealerIndex = 3;
      }
      Dealer.updateShownDealer();
    }
}


Fixing injection of plexus-utils imports for XPP3 stuff.

git-svn-id: 2c527eb49caa05e19d6b2be874bf74fa9d7ea670@633750 13f79535-47bb-0310-9956-ffa450edef68

package org.apache.maven.compat;

import org.apache.maven.lifecycle.binding.DefaultLifecycleBindingManager;
import org.apache.maven.lifecycle.binding.LifecycleBindingManager;
import org.codehaus.plexus.PlexusContainer;
import org.apache.maven.DefaultMaven;
import org.apache.maven.lifecycle.DefaultLifecycleExecutor;
import org.apache.maven.lifecycle.MojoBindingUtils;
import org.apache.maven.lifecycle.LifecycleUtils;
import org.apache.maven.lifecycle.NoSuchPhaseException;
import org.apache.maven.execution.MavenExecutionRequest;
import org.apache.maven.execution.MavenExecutionResult;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.extension.DefaultExtensionManager;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.metadata.ResolutionGroup;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
import org.apache.maven.artifact.versioning.VersionRange;
import org.apache.maven.lifecycle.model.MojoBinding;
import org.apache.maven.model.Plugin;
import org.apache.maven.plugin.DefaultPluginManager;
import org.apache.maven.plugin.InvalidPluginException;
import org.apache.maven.plugin.PluginManager;
import org.apache.maven.plugin.PluginManagerException;
import org.apache.maven.plugin.PluginNotFoundException;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugin.version.PluginVersionNotFoundException;
import org.apache.maven.plugin.version.PluginVersionResolutionException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.realm.MavenRealmManager;
import org.apache.maven.settings.MavenSettingsBuilder;
import org.apache.maven.settings.DefaultMavenSettingsBuilder;
import org.apache.maven.settings.Settings;
import org.codehaus.plexus.classworlds.realm.ClassRealm;
import org.codehaus.plexus.classworlds.realm.NoSuchRealmException;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.codehaus.plexus.logging.Logger;

import java.util.List;
import java.io.IOException;
import java.util.Iterator;
import java.util.Collection;
import java.util.Set;
import java.util.LinkedHashSet;

public privileged aspect Maven20xCompatAspect
{

    // GRAB Session as soon as it's constructed.
    private MavenSession session;

    // GRAB the request when it's passed into a method that returns a corresponding result.
    // NOTE: We'll use this in multiple places below...
    private MavenExecutionRequest request;

    // Grab this so we have a voice!
    private Logger logger;

    // used for injecting plexus-utils into extension and plugin artifact sets.
    private VersionRange vr = null;
    private Artifact plexusUtilsArtifact = null;

    private pointcut mavenEmbedderStop():
        execution( * org.apache.maven.embedder.MavenEmbedder.stop( .. ) );

    // TODO: There must be a more elegant way to release these resources than depending on MavenEmbedder.stop().
    after(): mavenEmbedderStop()
    {
        session = null;
        request = null;
        logger = null;
        vr = null;
        plexusUtilsArtifact = null;
    }

    // pointcut to avoid recursive matching on behavior injected by this aspect.
    private pointcut notHere(): !within( Maven20xCompatAspect );

    private pointcut sessionCreation( MavenSession session ):
        execution( public MavenSession+.new(..) )
        && this( session )
        && notHere();

    // capture the session instance.
    after( MavenSession session ): sessionCreation( session )
    {
        if ( logger != null && logger.isDebugEnabled() )
        {
            logger.debug( "Capturing session for backward compatibility aspect: " + session );
        }

        this.session = session;
    }

    // Re-Introduce old verifyPlugin(..) API.
    public PluginDescriptor PluginManager.verifyPlugin( Plugin plugin,
                                                        MavenProject project,
                                                        Settings settings,
                                                        ArtifactRepository localRepository )
        throws ArtifactResolutionException, ArtifactNotFoundException, PluginNotFoundException,
        PluginVersionResolutionException, InvalidPluginException, PluginManagerException,
        PluginVersionNotFoundException
    {
        // this will always be diverted, so no need to do anything.
        throw new IllegalStateException( "This introduced method should ALWAYS be intercepted by backward compatibility aspect." );
    }

    // USE Session to compensate for old verifyPlugin(..) API.
    private pointcut verifyPlugin( Plugin plugin, MavenProject project, PluginManager manager ):
        execution( PluginDescriptor PluginManager+.verifyPlugin( Plugin, MavenProject, Settings, ArtifactRepository+ ) )
        && args( plugin, project, .. )
        && this( manager );

    // redirect the old verifyPlugin(..) call to the new one, using the captured session instance above.
    PluginDescriptor around( Plugin plugin,
                             MavenProject project,
                             PluginManager manager )
        throws ArtifactResolutionException, ArtifactNotFoundException, PluginNotFoundException,
        PluginVersionResolutionException, InvalidPluginException, PluginManagerException,
        PluginVersionNotFoundException:
            verifyPlugin( plugin, project, manager )
    {
        if ( logger != null && logger.isDebugEnabled() )
        {
            logger.debug( "Diverting legacy PluginManager.verifyPlugin(..) call to replacement method using session: " + session );
        }

        return manager.verifyPlugin( plugin, project, session );
    }

    private pointcut getPluginDescriptorForPrefix( String prefix, PluginManager manager ):
        execution( public PluginDescriptor PluginManager+.getPluginDescriptorForPrefix( String ) )
        && args( prefix )
        && this( manager )
        && notHere();

    PluginDescriptor around( String prefix, PluginManager manager ): getPluginDescriptorForPrefix( prefix, manager )
    {
        // TODO: Implement Me!
        throw new UnsupportedOperationException( "This method has not yet been implemented in Maven's backward-compatibility library." );
    }

    public PluginDescriptor PluginManager.getPluginDescriptorForPrefix( String prefix )
    {
        return null;
    }

    // Intercept retrieval of artifact dependencies of an extension, inject plexus-utils if it's not there.
    private pointcut extDepArtifactsResolved( DefaultExtensionManager mgr ):
        call( public Set ResolutionGroup+.getArtifacts() )
        && within( DefaultExtensionManager+ )
        && this( mgr )
        && notHere();

    // We use the same hack here to make sure that plexus 1.1 is available for extensions that do
    // not declare plexus-utils but need it. MNG-2900
    Set around( DefaultExtensionManager mgr ): extDepArtifactsResolved( mgr )
    {
        Set result = proceed( mgr );

        result = checkPlexusUtils( result, mgr.artifactFactory );

        return result;
    }

    // Intercept retrieval of artifact dependencies of a plugin, inject plexus-utils if it's not there.
    private pointcut pluginDepArtifactsResolved( DefaultPluginManager mgr ):
        call( public Set ResolutionGroup+.getArtifacts() )
        && cflow( execution( Set DefaultPluginManager+.getPluginArtifacts(..) ) )
        && this( mgr )
        && notHere();

    Set around( DefaultPluginManager mgr ): pluginDepArtifactsResolved( mgr )
    {
        Set result = proceed( mgr );

        result = checkPlexusUtils( result, mgr.artifactFactory );

        return result;
    }

    private pointcut methodsTakingRequest( MavenExecutionRequest request ):
        execution( MavenExecutionResult *.*( MavenExecutionRequest ) )
        && !withincode( * *.*( MavenExecutionRequest ) )
        && args( request )
        && notHere();

    // capture the request instance before it's passed into any method that returns a corresponding MavenExecutionResult.
    Object around( MavenExecutionRequest request ): methodsTakingRequest( request )
    {
        this.request = request;

        try
        {
            return proceed( request );
        }
        finally
        {
            this.request = null;
        }
    }

    // Re-Introduce old buildSettings() API.
    public Settings MavenSettingsBuilder.buildSettings()
        throws IOException, XmlPullParserException
    {
        return null;
    }

    public Settings DefaultMavenSettingsBuilder.buildSettings()
    throws IOException, XmlPullParserException
    {
        return null;
    }

    // USE Request to compensate for old buildSettings() API.
    private pointcut buildSettings( MavenSettingsBuilder builder ):
        execution( public Settings MavenSettingsBuilder+.buildSettings() )
        && target( builder );

    // redirect old buildSettings() call to the new one, using the request captured above.
    Settings around( MavenSettingsBuilder builder )
        throws IOException, XmlPullParserException:
            buildSettings( builder )
    {
        return builder.buildSettings( request );
    }

    private pointcut pluginManager( DefaultPluginManager manager ):
        execution( * DefaultPluginManager.*( .. ) )
        && this( manager );

    private pointcut pluginRealmCreation( Plugin plugin, DefaultPluginManager manager ):
        call( ClassRealm MavenRealmManager+.createPluginRealm( Plugin, Artifact, Collection, .. ) )
        && cflow( pluginManager( manager ) )
        && args( plugin, .. );

    // Add various imports for Xpp3 stuff back into the core realm every time a plugin realm is created.
    ClassRealm around( Plugin plugin, DefaultPluginManager manager ): pluginRealmCreation( plugin, manager )
    {
        ClassRealm pluginRealm = proceed( plugin, manager );

        try
        {
            String parentRealmId = manager.container.getContainerRealm().getId();

            // adding for MNG-3012 to try to work around problems with Xpp3Dom (from plexus-utils)
            // spawning a ClassCastException when a mojo calls plugin.getConfiguration() from maven-model...
            pluginRealm.importFrom( parentRealmId, Xpp3Dom.class.getName() );
            pluginRealm.importFrom( parentRealmId, "org.codehaus.plexus.util.xml.pull" );

            // Adding for MNG-2878, since maven-reporting-impl was removed from the
            // internal list of artifacts managed by maven, the classloader is different
            // between maven-reporting-impl and maven-reporting-api...so this resource
            // is not available from the AbstractMavenReport since it uses:
            // getClass().getResourceAsStream( "/default-report.xml" )
            // (maven-reporting-impl version 2.0; line 134; affects: checkstyle plugin, and probably others)
            pluginRealm.importFrom( parentRealmId, "/default-report.xml" );
        }
        catch ( NoSuchRealmException e )
        {
            // can't happen here. All realms are concretely resolved by now.
        }

        return pluginRealm;
    }

    before( DefaultMaven maven ):
        execution( MavenExecutionResult DefaultMaven.execute( MavenExecutionRequest ) )
        && this( maven )
    {
        if ( this.logger == null )
        {
            this.logger = maven.getLogger();
        }
    }

    private pointcut addMojoBindingCall( String phase, MojoBinding binding ):
        call( void LifecycleUtils.addMojoBinding( String, MojoBinding, .. ) )
        && args( phase, binding, .. );

    void around( String phase, MojoBinding binding ): addMojoBindingCall( phase, binding )
    {
        try
        {
            proceed( phase, binding );
        }
        catch ( NoSuchPhaseException e )
        {
            logger.debug( "Mojo execution: " + MojoBindingUtils.toString( binding )
                          + " cannot be attached to lifecycle phase: " + phase
                          + "; it does not exist. Ignoring this binding." );
        }
    }

    // --------------------------
    // UTILITIES
    // --------------------------

    private Set checkPlexusUtils( Set dependencyArtifacts, ArtifactFactory artifactFactory )
    {
        // ----------------------------------------------------------------------------
        // If the plugin already declares a dependency on plexus-utils then we're all
        // set as the plugin author is aware of its use. If we don't have a dependency
        // on plexus-utils then we must protect users from stupid plugin authors who
        // did not declare a direct dependency on plexus-utils because the version
        // Maven uses is hidden from downstream use. We will also bump up any
        // anything below 1.1 to 1.1 as this mimics the behaviour in 2.0.5 where
        // plexus-utils 1.1 was being forced into use.
        // ----------------------------------------------------------------------------

        if ( vr == null )
        {
            try
            {
                vr = VersionRange.createFromVersionSpec( "[1.1,)" );
            }
            catch ( InvalidVersionSpecificationException e )
            {
                // Won't happen
            }
        }

        for ( Iterator i = dependencyArtifacts.iterator(); i.hasNext(); )
        {
            Artifact a = (Artifact) i.next();

            if ( a.getArtifactId().equals( "plexus-utils" )
                 && vr.containsVersion( new DefaultArtifactVersion( a.getVersion() ) ) )
            {
                return dependencyArtifacts;
            }
        }

        // We will add plexus-utils as every plugin was getting this anyway from Maven itself. We will set the
        // version to the latest version we know that works as of the 2.0.6 release. We set the scope to runtime
        // as this is what's implicitly happening in 2.0.6.

        if ( plexusUtilsArtifact == null )
        {
            plexusUtilsArtifact = artifactFactory.createArtifact( "org.codehaus.plexus",
                                                                  "plexus-utils",
                                                                  "1.1",
                                                                  Artifact.SCOPE_RUNTIME,
                                                                  "jar" );
        }

        Set result = new LinkedHashSet( dependencyArtifacts );
        result.add( plexusUtilsArtifact );

        return result;
    }

    // This is to support the maven-enforcer-plugin.
    private List DefaultLifecycleExecutor.lifecycles;

    private pointcut lifecycleExecutorExecute( DefaultLifecycleExecutor executor ):
        execution( * DefaultLifecycleExecutor.execute( .. ) )
        && this( executor );

    before( DefaultLifecycleExecutor executor ): lifecycleExecutorExecute( executor )
    {
        PlexusContainer container = executor.container;
        DefaultLifecycleBindingManager bindingMgr;
        try
        {
            bindingMgr = (DefaultLifecycleBindingManager) container.lookup( LifecycleBindingManager.ROLE, "default" );
        }
        catch ( ComponentLookupException e )
        {
            IllegalStateException err = new IllegalStateException( "Cannot lookup default role-hint for: " + LifecycleBindingManager.ROLE );
            err.initCause( e );

            throw err;
        }

        executor.lifecycles = bindingMgr.lifecycles;
    }

}

package org.apache.maven.compat;

import org.apache.maven.lifecycle.binding.DefaultLifecycleBindingManager;
import org.apache.maven.lifecycle.binding.LifecycleBindingManager;
import org.codehaus.plexus.PlexusContainer;
import org.apache.maven.DefaultMaven;
import org.apache.maven.lifecycle.DefaultLifecycleExecutor;
import org.apache.maven.lifecycle.MojoBindingUtils;
import org.apache.maven.lifecycle.LifecycleUtils;
import org.apache.maven.lifecycle.NoSuchPhaseException;
import org.apache.maven.execution.MavenExecutionRequest;
import org.apache.maven.execution.MavenExecutionResult;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.extension.DefaultExtensionManager;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.metadata.ResolutionGroup;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
import org.apache.maven.artifact.versioning.VersionRange;
import org.apache.maven.lifecycle.model.MojoBinding;
import org.apache.maven.model.Plugin;
import org.apache.maven.plugin.DefaultPluginManager;
import org.apache.maven.plugin.InvalidPluginException;
import org.apache.maven.plugin.PluginManager;
import org.apache.maven.plugin.PluginManagerException;
import org.apache.maven.plugin.PluginNotFoundException;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugin.version.PluginVersionNotFoundException;
import org.apache.maven.plugin.version.PluginVersionResolutionException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.realm.MavenRealmManager;
import org.apache.maven.settings.MavenSettingsBuilder;
import org.apache.maven.settings.DefaultMavenSettingsBuilder;
import org.apache.maven.settings.Settings;
import org.codehaus.plexus.classworlds.realm.ClassRealm;
import org.codehaus.plexus.classworlds.realm.NoSuchRealmException;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.codehaus.plexus.logging.Logger;

import java.util.List;
import java.io.IOException;
import java.util.Iterator;
import java.util.Collection;
import java.util.Set;
import java.util.LinkedHashSet;

public privileged aspect Maven20xCompatAspect
{

    // GRAB Session as soon as it's constructed.
    private MavenSession session;

    // GRAB the request when it's passed into a method that returns a corresponding result.
    // NOTE: We'll use this in multiple places below...
    private MavenExecutionRequest request;

    // Grab this so we have a voice!
    private Logger logger;

    // used for injecting plexus-utils into extension and plugin artifact sets.
    private VersionRange vr = null;
    private Artifact plexusUtilsArtifact = null;

    private pointcut mavenEmbedderStop():
        execution( * org.apache.maven.embedder.MavenEmbedder.stop( .. ) );

    // TODO: There must be a more elegant way to release these resources than depending on MavenEmbedder.stop().
    after(): mavenEmbedderStop()
    {
        session = null;
        request = null;
        logger = null;
        vr = null;
        plexusUtilsArtifact = null;
    }

    // pointcut to avoid recursive matching on behavior injected by this aspect.
    private pointcut notHere(): !within( Maven20xCompatAspect );

    private pointcut sessionCreation( MavenSession session ):
        execution( public MavenSession+.new(..) )
        && this( session )
        && notHere();

    // capture the session instance.
    after( MavenSession session ): sessionCreation( session )
    {
        if ( logger != null && logger.isDebugEnabled() )
        {
            logger.debug( "Capturing session for backward compatibility aspect: " + session );
        }

        this.session = session;
    }

    // USE Session to compensate for old verifyPlugin(..) API.
    private pointcut verifyPlugin( Plugin plugin, MavenProject project, PluginManager manager ):
        execution( PluginDescriptor PluginManager+.verifyPlugin( Plugin, MavenProject, Settings, ArtifactRepository+ ) )
        && args( plugin, project, .. )
        && target( manager );

    // redirect the old verifyPlugin(..) call to the new one, using the captured session instance above.
    PluginDescriptor around( Plugin plugin,
                             MavenProject project,
                             PluginManager manager )
        throws ArtifactResolutionException, ArtifactNotFoundException, PluginNotFoundException,
        PluginVersionResolutionException, InvalidPluginException, PluginManagerException,
        PluginVersionNotFoundException:
            verifyPlugin( plugin, project, manager )
    {
        if ( logger != null && logger.isDebugEnabled() )
        {
            logger.debug( "Diverting legacy PluginManager.verifyPlugin(..) call to replacement method using session: " + session );
        }

        return manager.verifyPlugin( plugin, project, session );
    }

    // Re-Introduce old verifyPlugin(..) API.
    public PluginDescriptor PluginManager.verifyPlugin( Plugin plugin,
                                                        MavenProject project,
                                                        Settings settings,
                                                        ArtifactRepository localRepository )
        throws ArtifactResolutionException, ArtifactNotFoundException, PluginNotFoundException,
        PluginVersionResolutionException, InvalidPluginException, PluginManagerException,
        PluginVersionNotFoundException
    {
        // this will always be diverted, so no need to do anything.
        throw new IllegalStateException( "This introduced method should ALWAYS be intercepted by backward compatibility aspect." );
    }

    private pointcut getPluginDescriptorForPrefix( String prefix, PluginManager manager ):
        execution( public PluginDescriptor PluginManager+.getPluginDescriptorForPrefix( String ) )
        && args( prefix )
        && target( manager )
        && notHere();

    PluginDescriptor around( String prefix, PluginManager manager ): getPluginDescriptorForPrefix( prefix, manager )
    {
        // TODO: Implement Me!
        throw new UnsupportedOperationException( "This method has not yet been implemented in Maven's backward-compatibility library." );
    }

    public PluginDescriptor PluginManager.getPluginDescriptorForPrefix( String prefix )
    {
        return null;
    }

    // Intercept retrieval of artifact dependencies of an extension, inject plexus-utils if it's not there.
    private pointcut extDepArtifactsResolved( DefaultExtensionManager mgr ):
        call( public Set ResolutionGroup+.getArtifacts() )
        && within( DefaultExtensionManager+ )
        && this( mgr )
        && notHere();

    // We use the same hack here to make sure that plexus 1.1 is available for extensions that do
    // not declare plexus-utils but need it. MNG-2900
    Set around( DefaultExtensionManager mgr ): extDepArtifactsResolved( mgr )
    {
        Set result = proceed( mgr );

        result = checkPlexusUtils( result, mgr.artifactFactory );

        return result;
    }

    // Intercept retrieval of artifact dependencies of a plugin, inject plexus-utils if it's not there.
    private pointcut pluginDepArtifactsResolved( DefaultPluginManager mgr ):
        call( public Set ResolutionGroup+.getArtifacts() )
        && cflow( execution( Set DefaultPluginManager+.getPluginArtifacts(..) ) )
        && this( mgr )
        && notHere();

    Set around( DefaultPluginManager mgr ): pluginDepArtifactsResolved( mgr )
    {
        Set result = proceed( mgr );

        result = checkPlexusUtils( result, mgr.artifactFactory );

        return result;
    }

    private pointcut methodsTakingRequest( MavenExecutionRequest request ):
        execution( MavenExecutionResult *.*( MavenExecutionRequest ) )
        && !withincode( * *.*( MavenExecutionRequest ) )
        && args( request )
        && notHere();

    // capture the request instance before it's passed into any method that returns a corresponding MavenExecutionResult.
    Object around( MavenExecutionRequest request ): methodsTakingRequest( request )
    {
        this.request = request;

        try
        {
            return proceed( request );
        }
        finally
        {
            this.request = null;
        }
    }

    // USE Request to compensate for old buildSettings() API.
    private pointcut buildSettings( MavenSettingsBuilder builder ):
        execution( public Settings MavenSettingsBuilder+.buildSettings() )
        && target( builder )
        && notHere();

    // redirect old buildSettings() call to the new one, using the request captured above.
    Settings around( MavenSettingsBuilder builder )
        throws IOException, XmlPullParserException:
            buildSettings( builder )
    {
        return builder.buildSettings( request );
    }

    // Re-Introduce old buildSettings() API.
    public Settings MavenSettingsBuilder.buildSettings()
        throws IOException, XmlPullParserException
    {
        return null;
    }

    public Settings DefaultMavenSettingsBuilder.buildSettings()
    throws IOException, XmlPullParserException
    {
        return null;
    }

    private pointcut pluginManager( DefaultPluginManager manager ):
        execution( * DefaultPluginManager.*( .. ) )
        && this( manager );

    private pointcut pluginRealmCreation( Plugin plugin, DefaultPluginManager manager ):
        call( ClassRealm MavenRealmManager+.createPluginRealm( Plugin, Artifact, Collection ) )
        && cflow( pluginManager( manager ) )
        && args( plugin, .. );

    // Add various imports for Xpp3 stuff back into the core realm every time a plugin realm is created.
    ClassRealm around( Plugin plugin, DefaultPluginManager manager ): pluginRealmCreation( plugin, manager )
    {
        ClassRealm pluginRealm = proceed( plugin, manager );

        try
        {
            String parentRealmId = manager.container.getContainerRealm().getId();

            // adding for MNG-3012 to try to work around problems with Xpp3Dom (from plexus-utils)
            // spawning a ClassCastException when a mojo calls plugin.getConfiguration() from maven-model...
            pluginRealm.importFrom( parentRealmId, Xpp3Dom.class.getName() );
            pluginRealm.importFrom( parentRealmId, "org.codehaus.plexus.util.xml.pull" );

            // Adding for MNG-2878, since maven-reporting-impl was removed from the
            // internal list of artifacts managed by maven, the classloader is different
            // between maven-reporting-impl and maven-reporting-api...so this resource
            // is not available from the AbstractMavenReport since it uses:
            // getClass().getResourceAsStream( "/default-report.xml" )
            // (maven-reporting-impl version 2.0; line 134; affects: checkstyle plugin, and probably others)
            pluginRealm.importFrom( parentRealmId, "/default-report.xml" );
        }
        catch ( NoSuchRealmException e )
        {
            // can't happen here. All realms are concretely resolved by now.
        }

        return pluginRealm;
    }

    before( DefaultMaven maven ):
        execution( MavenExecutionResult DefaultMaven.execute( MavenExecutionRequest ) )
        && this( maven )
    {
        if ( this.logger == null )
        {
            this.logger = maven.getLogger();
        }
    }

    private pointcut addMojoBindingCall( String phase, MojoBinding binding ):
        call( void LifecycleUtils.addMojoBinding( String, MojoBinding, .. ) )
        && args( phase, binding, .. );

    void around( String phase, MojoBinding binding ): addMojoBindingCall( phase, binding )
    {
        try
        {
            proceed( phase, binding );
        }
        catch ( NoSuchPhaseException e )
        {
            logger.debug( "Mojo execution: " + MojoBindingUtils.toString( binding )
                          + " cannot be attached to lifecycle phase: " + phase
                          + "; it does not exist. Ignoring this binding." );
        }
    }

    // --------------------------
    // UTILITIES
    // --------------------------

    private Set checkPlexusUtils( Set dependencyArtifacts, ArtifactFactory artifactFactory )
    {
        // ----------------------------------------------------------------------------
        // If the plugin already declares a dependency on plexus-utils then we're all
        // set as the plugin author is aware of its use. If we don't have a dependency
        // on plexus-utils then we must protect users from stupid plugin authors who
        // did not declare a direct dependency on plexus-utils because the version
        // Maven uses is hidden from downstream use. We will also bump up any
        // anything below 1.1 to 1.1 as this mimics the behaviour in 2.0.5 where
        // plexus-utils 1.1 was being forced into use.
        // ----------------------------------------------------------------------------

        if ( vr == null )
        {
            try
            {
                vr = VersionRange.createFromVersionSpec( "[1.1,)" );
            }
            catch ( InvalidVersionSpecificationException e )
            {
                // Won't happen
            }
        }

        for ( Iterator i = dependencyArtifacts.iterator(); i.hasNext(); )
        {
            Artifact a = (Artifact) i.next();

            if ( a.getArtifactId().equals( "plexus-utils" )
                 && vr.containsVersion( new DefaultArtifactVersion( a.getVersion() ) ) )
            {
                return dependencyArtifacts;
            }
        }

        // We will add plexus-utils as every plugin was getting this anyway from Maven itself. We will set the
        // version to the latest version we know that works as of the 2.0.6 release. We set the scope to runtime
        // as this is what's implicitly happening in 2.0.6.

        if ( plexusUtilsArtifact == null )
        {
            plexusUtilsArtifact = artifactFactory.createArtifact( "org.codehaus.plexus",
                                                                  "plexus-utils",
                                                                  "1.1",
                                                                  Artifact.SCOPE_RUNTIME,
                                                                  "jar" );
        }

        Set result = new LinkedHashSet( dependencyArtifacts );
        result.add( plexusUtilsArtifact );

        return result;
    }

    // This is to support the maven-enforcer-plugin.
    private List DefaultLifecycleExecutor.lifecycles;

    private pointcut lifecycleExecutorExecute( DefaultLifecycleExecutor executor ):
        execution( * DefaultLifecycleExecutor.execute( .. ) )
        && this( executor );

    before( DefaultLifecycleExecutor executor ): lifecycleExecutorExecute( executor )
    {
        PlexusContainer container = executor.container;
        DefaultLifecycleBindingManager bindingMgr;
        try
        {
            bindingMgr = (DefaultLifecycleBindingManager) container.lookup( LifecycleBindingManager.ROLE, "default" );
        }
        catch ( ComponentLookupException e )
        {
            IllegalStateException err = new IllegalStateException( "Cannot lookup default role-hint for: " + LifecycleBindingManager.ROLE );
            err.initCause( e );

            throw err;
        }

        executor.lifecycles = bindingMgr.lifecycles;
    }

}


Aspect in package

Aspect in package

package edu.mit.meet.googleapps;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.javascript.host.css.CSSStyleSheet;

import org.w3c.css.sac.Selector;

aspect CSSStyleSheetMonkeyPatch {
    pointcut selects(Selector s, HtmlElement e):
        execution(boolean CSSStyleSheet.selects(..)) && args(BrowserVersion, s, e);

    boolean around(Selector s, HtmlElement e): selects(s, e) {
        if (s.getSelectorType() == Selector.SAC_CHILD_SELECTOR && ! (e.getParentNode() instanceof HtmlElement)) {
            // XXX ClassCastException when HtmlUnit tries to cast parent to HtmlElement!
            return false;
        }
        return proceed(s, e);
    }
}