fixed bug in statistics graph drawing function

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.Games;
import model.SystemValues.Players;
import view.GUI;
import view.UIUpdater;
import de.erichseifert.gral.data.DataTable;
import de.erichseifert.gral.plots.BarPlot;
import de.erichseifert.gral.plots.BarPlot.BarRenderer;
import de.erichseifert.gral.plots.PiePlot;
import de.erichseifert.gral.plots.PiePlot.PieSliceRenderer;
import de.erichseifert.gral.plots.points.PointRenderer;
import de.erichseifert.gral.ui.InteractivePanel;
import de.erichseifert.gral.util.GraphicsUtils;
import de.erichseifert.gral.util.Insets2D;
import de.erichseifert.gral.util.Location;

public privileged aspect StatPlayerWiseGraph {
    /**
     * Statistics has to be the last feature executed, such that the subfeatures
     * have the correct gui object before statistics can create the tabbed pane
     */
    declare precedence : Statistics, StatPlayerWiseGraph, StatPlayerWiseTxt, StatOverallGraph, StatOverallTxt;

    private static GUI gui;

    private static final JTabbedPane playersTabs = new JTabbedPane();
    private static final Color COLOR1 = Color.GREEN;

    private static DataTable playedTypes[] = new DataTable[4];
    private static DataTable wonGames[] = new DataTable[4];

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

    @SuppressWarnings("unchecked")
    after(JTabbedPane tabbedPane):
                        execution(public static void StatisticsHelper.StatisticsPaneCreated(JTabbedPane))
                        && args(tabbedPane) {

        for (int i = 0; i < Players.values().length; i++) {
            playedTypes[i] = new DataTable(Integer.class, String.class);
            wonGames[i] = new DataTable(Integer.class, Double.class,String.class);
        }

        for (Players player : Players.values()) {
            playersTabs.addTab(player.toString(), createPlayersPanel(player));
        }
        tabbedPane.addTab("Einzelstatistiken", playersTabs);
    }

    private JPanel createPlayersPanel(Players player) {
        JPanel containerPanel = new JPanel();
        containerPanel.setLayout(new GridLayout(2, 2));

        containerPanel.add(new InteractivePanel(createWonGamesBarPlot(player)));
        containerPanel.add(new InteractivePanel(createPlayedTypesPlot(player)));
        return containerPanel;
    }

    after() : execution(* UIUpdater.run()) {
        updateData();
        for (Players player : Players.values()) {
            playersTabs.setTitleAt(player.ordinal(), player.toString());
        }
    }

    private static void updateData() {
        for (Players player : Players.values()) {
            PlayerWiseStatistics data = gui.model.getGameData().getPlayerWiseStatistics(player);

            int curPlayer = player.ordinal();

            while (playedTypes[curPlayer].getRowCount() > 0) {
                playedTypes[curPlayer].removeLast();
            }
            playedTypes[curPlayer].add(data.getGamesPlayedPerType()[Games.RUFSPIEL.ordinal()], "Rufspiele");
            playedTypes[curPlayer].add(data.getGamesPlayedPerType()[Games.SOLO.ordinal()], "Soli");
            playedTypes[curPlayer].add(data.getGamesPlayedPerType()[Games.TOUT.ordinal()], "Soli Tout");
            playedTypes[curPlayer].add(data.getGamesPlayedPerType()[Games.SIE.ordinal()],"Soli Sie");
            playedTypes[curPlayer].add(data.getGamesPlayedPerType()[Games.WEITER.ordinal()], "Weiter");

            // percentage of won games by gametype
            int soliCompleteAmount = data.getGamesPlayedPerType()[Games.SOLO.ordinal()]
                    + data.getGamesPlayedPerType()[Games.SIE.ordinal()]
                    + data.getGamesPlayedPerType()[Games.TOUT.ordinal()];
            int soliCompleteAmountWon = data.getGamesWonPerType()[Games.SOLO.ordinal()]
                    + data.getGamesWonPerType()[Games.SIE.ordinal()]
                    + data.getGamesWonPerType()[Games.TOUT.ordinal()];
            double soliGesamtWonPerc = (soliCompleteAmount > 0
                    ? (double) soliCompleteAmountWon / soliCompleteAmount
                    : 0.0) * 100;

            while (wonGames[curPlayer].getRowCount() > 0) {
                wonGames[curPlayer].removeLast();
            }
            wonGames[curPlayer].add(1, data.getGamesWonPerc(), "Gesamt");
            wonGames[curPlayer].add(2, data.getGamesWonPerTypePerc()[Games.RUFSPIEL.ordinal()], "Rufspiele");
            wonGames[curPlayer].add(3, soliGesamtWonPerc, "Soli gesamt");
            wonGames[curPlayer].add(4, data.getGamesWonPerTypePerc()[Games.SOLO.ordinal()], "Soli normal");
            wonGames[curPlayer].add(5, data.getGamesWonPerTypePerc()[Games.TOUT.ordinal()], "Soli Tout");
            wonGames[curPlayer].add(6, data.getGamesWonPerTypePerc()[Games.SIE.ordinal()], "Soli Sie");
        }
    }

    private static PiePlot createPlayedTypesPlot(Players player) {
        int playerIndex = player.ordinal();

        PiePlot plot = new PiePlot(playedTypes[playerIndex]);

        PointRenderer pointRenderer = plot
                .getPointRenderer(playedTypes[playerIndex]);
        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[playerIndex]);

        // 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 createWonGamesBarPlot(Players player) {
        int playerIndex = player.ordinal();

        // Create new bar plot
        BarPlot plot = new BarPlot(wonGames[playerIndex]);

        // 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[playerIndex]);
        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;
    }
}

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.Games;
import model.SystemValues.Players;
import view.GUI;
import view.UIUpdater;
import de.erichseifert.gral.data.DataTable;
import de.erichseifert.gral.plots.BarPlot;
import de.erichseifert.gral.plots.BarPlot.BarRenderer;
import de.erichseifert.gral.plots.PiePlot;
import de.erichseifert.gral.plots.PiePlot.PieSliceRenderer;
import de.erichseifert.gral.plots.points.PointRenderer;
import de.erichseifert.gral.ui.InteractivePanel;
import de.erichseifert.gral.util.GraphicsUtils;
import de.erichseifert.gral.util.Insets2D;
import de.erichseifert.gral.util.Location;

public privileged aspect StatPlayerWiseGraph {
    /**
     * Statistics has to be the last feature executed, such that the subfeatures
     * have the correct gui object before statistics can create the tabbed pane
     */
    declare precedence : Statistics, StatPlayerWiseGraph, StatPlayerWiseTxt, StatOverallGraph, StatOverallTxt;

    private static GUI gui;

    private static final JTabbedPane playersTabs = new JTabbedPane();
    private static final Color COLOR1 = Color.GREEN;

    private static DataTable playedTypes[] = new DataTable[4];
    private static DataTable wonGames[] = new DataTable[4];

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

    @SuppressWarnings("unchecked")
    after(JTabbedPane tabbedPane):
                        execution(public static void StatisticsHelper.StatisticsPaneCreated(JTabbedPane))
                        && args(tabbedPane) {

        for (int i = 0; i < Players.values().length; i++) {
            playedTypes[i] = new DataTable(Integer.class, String.class);
            wonGames[i] = new DataTable(Integer.class, Double.class,String.class);
        }

        for (Players player : Players.values()) {
            playersTabs.addTab(player.toString(), createPlayersPanel(player));
        }
        tabbedPane.addTab("Einzelstatistiken", playersTabs);
    }

    private JPanel createPlayersPanel(Players player) {
        JPanel containerPanel = new JPanel();
        containerPanel.setLayout(new GridLayout(2, 2));

        containerPanel.add(new InteractivePanel(createWonGamesBarPlot(player)));
        containerPanel.add(new InteractivePanel(createPlayedTypesPlot(player)));
        return containerPanel;
    }

    after() : execution(* UIUpdater.run()) {
        updateData();
        for (Players player : Players.values()) {
            playersTabs.setTitleAt(player.ordinal(), player.toString());
        }
    }

    private static void updateData() {
        for (Players player : Players.values()) {
            PlayerWiseStatistics data = gui.model.getGameData().getPlayerWiseStatistics(player);

            int curPlayer = player.ordinal();

            while (playedTypes[curPlayer].getRowCount() > 0) {
                playedTypes[curPlayer].removeLast();
            }
            playedTypes[curPlayer].add(data.getGamesPlayedPerType()[Games.RUFSPIEL.ordinal()], "Rufspiele");
            playedTypes[curPlayer].add(data.getGamesPlayedPerType()[Games.SOLO.ordinal()], "Soli");
            playedTypes[curPlayer].add(data.getGamesPlayedPerType()[Games.TOUT.ordinal()], "Soli Tout");
            playedTypes[curPlayer].add(data.getGamesPlayedPerType()[Games.SIE.ordinal()],"Soli Sie");
            playedTypes[curPlayer].add(data.getGamesPlayedPerType()[Games.WEITER.ordinal()], "Weiter");

            // percentage of won games by gametype
            int soliCompleteAmount = data.getGamesPlayedPerType()[Games.SOLO.ordinal()]
                    + data.getGamesPlayedPerType()[Games.SIE.ordinal()]
                    + data.getGamesPlayedPerType()[Games.TOUT.ordinal()];
            int soliCompleteAmountWon = data.getGamesWonPerType()[Games.SOLO.ordinal()]
                    + data.getGamesWonPerType()[Games.SIE.ordinal()]
                    + data.getGamesWonPerType()[Games.TOUT.ordinal()];
            double soliGesamtWonPerc = (soliCompleteAmount > 0
                    ? (double) soliCompleteAmountWon / soliCompleteAmount
                    : 0.0) * 100;

            while (wonGames[curPlayer].getRowCount() > 0) {
                wonGames[curPlayer].removeLast();
            }
            wonGames[curPlayer].add(1, data.getGamesWonPerc(), "Gesamt");
            wonGames[curPlayer].add(2, data.getGamesWonPerTypePerc()[Games.RUFSPIEL.ordinal()], "Rufspiele");
            wonGames[curPlayer].add(3, soliGesamtWonPerc, "Soli gesamt");
            wonGames[curPlayer].add(4, data.getGamesWonPerTypePerc()[Games.SOLO.ordinal()], "Soli normal");
            wonGames[curPlayer].add(5, data.getGamesWonPerTypePerc()[Games.TOUT.ordinal()], "Soli Tout");
            wonGames[curPlayer].add(6, data.getGamesWonPerTypePerc()[Games.SIE.ordinal()], "Soli Sie");
        }
    }

    private static PiePlot createPlayedTypesPlot(Players player) {
        int playerIndex = player.ordinal();

        PiePlot plot = new PiePlot(playedTypes[playerIndex]);

        PointRenderer pointRenderer = plot
                .getPointRenderer(playedTypes[playerIndex]);
        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[playerIndex]);

        // 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 createWonGamesBarPlot(Players player) {
        int playerIndex = player.ordinal();

        // 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[playerIndex]);
        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;
    }
}


[MNG-3193] Adding pointcut and advice to provide backward compat on invalid lifecycle phase names (these bindings will be ignored).

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

package org.apache.maven.compat.plugin;

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.execution.MavenRealmManager;
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.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.util.xml.pull.XmlPullParserException;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.logging.LogEnabled;
import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.PlexusConstants;
import org.codehaus.plexus.context.Context;
import org.codehaus.plexus.context.ContextException;

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

public privileged aspect Maven20xCompatAspect
{

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

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

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

    // capture the session instance.
    after( MavenSession session ): sessionCreation( session )
    {
        this.session = session;
    }

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

    // 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 )
    {
        return manager.verifyPlugin( plugin, project, session );
    }

    // Re-Introduce old verifyPlugin(..) API.
    public PluginDescriptor PluginManager.verifyPlugin( Plugin plugin,
                                                        MavenProject project,
                                                        Settings settings,
                                                        ArtifactRepository localRepository )
    {
        // this will always be diverted, so no need to do anything.
        return null;
    }

    public PluginDescriptor DefaultPluginManager.verifyPlugin( Plugin plugin,
                                                        MavenProject project,
                                                        Settings settings,
                                                        ArtifactRepository localRepository )
    {
        // this will always be diverted, so no need to do anything.
        return null;
    }

    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!
        return null;
    }

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

    public PluginDescriptor DefaultPluginManager.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 );

        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 );

        checkPlexusUtils( result, mgr.artifactFactory );

        return result;
    }

    // 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;

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

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

    // 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;
    }

    // container used in the plugin manager.
    private PlexusContainer container;

    private pointcut pluginManagerContextualized( Context context ):
        execution( void DefaultPluginManager+.contextualize( Context ) )
        && args( context );

    // capture the container when the DefaultPluginManager is contextualized.
    void around( Context context ) throws ContextException: pluginManagerContextualized( context )
    {
        proceed( context );
        container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY );
    }

    private pointcut pluginRealmCreation( Plugin plugin ):
        call( ClassRealm MavenRealmManager+.createPluginRealm( Plugin, Artifact, Collection ) )
        && withincode( void DefaultPluginManager.addPlugin(..) )
        && args( plugin, .. );

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

        try
        {
            String parentRealmId = 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;
    }

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

    private pointcut enableLoggingCall( Logger logger ):
        execution( void LogEnabled+.enableLogging( Logger ) )
        && args( logger );

    after( Logger logger ): enableLoggingCall( logger )
    {
        if ( this.logger == null )
        {
            this.logger = logger;
        }
    }

    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 VersionRange vr = null;
    private Artifact plexusUtilsArtifact = null;

    private void 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
            }
        }

        boolean plexusUtilsPresent = false;

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

            if ( a.getArtifactId().equals( "plexus-utils" )
                 && vr.containsVersion( new DefaultArtifactVersion( a.getVersion() ) ) )
            {
                plexusUtilsPresent = true;

                break;
            }
        }

        if ( !plexusUtilsPresent )
        {
            // 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" );
            }

            dependencyArtifacts.add( plexusUtilsArtifact );
        }
    }

}

package org.apache.maven.compat.plugin;

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.execution.MavenRealmManager;
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.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.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.util.xml.pull.XmlPullParserException;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.PlexusConstants;
import org.codehaus.plexus.context.Context;
import org.codehaus.plexus.context.ContextException;

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

public privileged aspect Maven20xCompatAspect
{

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

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

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

    // capture the session instance.
    after( MavenSession session ): sessionCreation( session )
    {
        this.session = session;
    }

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

    // 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 )
    {
        return manager.verifyPlugin( plugin, project, session );
    }

    // Re-Introduce old verifyPlugin(..) API.
    public PluginDescriptor PluginManager.verifyPlugin( Plugin plugin,
                                                        MavenProject project,
                                                        Settings settings,
                                                        ArtifactRepository localRepository )
    {
        // this will always be diverted, so no need to do anything.
        return null;
    }

    public PluginDescriptor DefaultPluginManager.verifyPlugin( Plugin plugin,
                                                        MavenProject project,
                                                        Settings settings,
                                                        ArtifactRepository localRepository )
    {
        // this will always be diverted, so no need to do anything.
        return null;
    }

    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!
        return null;
    }

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

    public PluginDescriptor DefaultPluginManager.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 );

        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 );

        checkPlexusUtils( result, mgr.artifactFactory );

        return result;
    }

    // GRAB the request when it's passed into a method that returns a corresponding result.
    private MavenExecutionRequest request;

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

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

    // 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;
    }

    // container used in the plugin manager.
    private PlexusContainer container;

    private pointcut pluginManagerContextualized( Context context ):
        execution( void DefaultPluginManager+.contextualize( Context ) )
        && args( context );

    // capture the container when the DefaultPluginManager is contextualized.
    void around( Context context ) throws ContextException: pluginManagerContextualized( context )
    {
        proceed( context );
        container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY );
    }

    private pointcut pluginRealmCreation( Plugin plugin ):
        call( ClassRealm MavenRealmManager+.createPluginRealm( Plugin, Artifact, Collection ) )
        && withincode( void DefaultPluginManager.addPlugin(..) )
        && args( plugin, .. );

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

        try
        {
            String parentRealmId = 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;
    }

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

    private VersionRange vr = null;
    private Artifact plexusUtilsArtifact = null;

    private void 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
            }
        }

        boolean plexusUtilsPresent = false;

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

            if ( a.getArtifactId().equals( "plexus-utils" )
                 && vr.containsVersion( new DefaultArtifactVersion( a.getVersion() ) ) )
            {
                plexusUtilsPresent = true;

                break;
            }
        }

        if ( !plexusUtilsPresent )
        {
            // 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" );
            }

            dependencyArtifacts.add( plexusUtilsArtifact );
        }
    }

}


SPR-2718 - customise annotation source to allow annotations on non-public methods

git-svn-id: b619a0c99665f88f1afe72824344cefe9a1c8c90@12137 fd5a2b45-1f63-4059-99e9-3c7cb7fd75c8

/*
 * Copyright 2002-2005 the original author or 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.springframework.transaction.aspectj;

import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource;
import org.springframework.transaction.annotation.Transactional;

/**
 * Concrete AspectJ transaction aspect using Spring Transactional annotation
 * for JDK 1.5+.
 *
 *

 * When using this aspect, you must annotate the implementation class
 * (and/or methods within that class), not the interface (if any) that
 * the class implements. AspectJ follows Java's rule that annotations on
 * interfaces are not inherited.
 *

 *
A @Transactional annotation on a class specifies the default transaction
 * semantics for the execution of any public operation in the class.

 *
A @Transactional annotation on a method within the class overrides the
 * default transaction semantics given by the class annotation (if present).
 * Methods with public, protected, and default visibility may all be annotated.
 * Annotating protected and default visibility methods directly is the only way
 * to get transaction demarcation for the execution of such operations.

 *
 * @author Rod Johnson
 * @author Ramnivas Laddad
 * @author Adrian Colyer
 * @since 2.0
 * @see org.springframework.transaction.annotation.Transactional
 */
public aspect AnnotationTransactionAspect extends AbstractTransactionAspect {

	public AnnotationTransactionAspect() {
		super(new AnnotationTransactionAttributeSource() {
			protected boolean allowPublicMethodsOnly() {
				return false;
			}
		});
	}

	/**
	 * 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 executionOfAnyPublicMethodInAtTransactionalType() :
		execution(public * ((@Transactional *)+).*(..)) && @this(Transactional);

	/**
	 * Matches the execution of any non-private method with the
	 * Transactional annotation.
	 */
	private pointcut executionOfTransactionalNonPrivateMethod() :
		execution(!private * *(..)) && @annotation(Transactional);

	/**
	 * Definition of pointcut from super aspect - matched join points
	 * will have Spring transaction management applied.
	 */
	protected pointcut transactionalMethodExecution(Object txObject) :
		(executionOfAnyPublicMethodInAtTransactionalType()
		 || executionOfTransactionalNonPrivateMethod() )
		 && this(txObject);

	/**
	 * Annotating private methods with @Transactional has no effect...
	 */
	declare warning
	    // note, we should be able to say the following in one execution pcd, but
	    // aj doesn't like it...
		: execution(@Transactional * *(..)) &&
		  execution(private * *(..))
		: "@Transactional annotation on private method will be ignored";
}

/*
 * Copyright 2002-2005 the original author or 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.springframework.transaction.aspectj;

import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource;
import org.springframework.transaction.annotation.Transactional;

/**
 * Concrete AspectJ transaction aspect using Spring Transactional annotation
 * for JDK 1.5+.
 *
 *

 * When using this aspect, you must annotate the implementation class
 * (and/or methods within that class), not the interface (if any) that
 * the class implements. AspectJ follows Java's rule that annotations on
 * interfaces are not inherited.
 *

 *
A @Transactional annotation on a class specifies the default transaction
 * semantics for the execution of any public operation in the class.

 *
A @Transactional annotation on a method within the class overrides the
 * default transaction semantics given by the class annotation (if present).
 * Methods with public, protected, and default visibility may all be annotated.
 * Annotating protected and default visibility methods directly is the only way
 * to get transaction demarcation for the execution of such operations.

 *
 * @author Rod Johnson
 * @author Ramnivas Laddad
 * @author Adrian Colyer
 * @since 2.0
 * @see org.springframework.transaction.annotation.Transactional
 */
public aspect AnnotationTransactionAspect extends AbstractTransactionAspect {

	public AnnotationTransactionAspect() {
		super(new AnnotationTransactionAttributeSource());
	}

	/**
	 * 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 executionOfAnyPublicMethodInAtTransactionalType() :
		execution(public * ((@Transactional *)+).*(..)) && @this(Transactional);

	/**
	 * Matches the execution of any non-private method with the
	 * Transactional annotation.
	 */
	private pointcut executionOfTransactionalNonPrivateMethod() :
		execution(!private * *(..)) && @annotation(Transactional);

	/**
	 * Definition of pointcut from super aspect - matched join points
	 * will have Spring transaction management applied.
	 */
	protected pointcut transactionalMethodExecution(Object txObject) :
		(executionOfAnyPublicMethodInAtTransactionalType()
		 || executionOfTransactionalNonPrivateMethod() )
		 && this(txObject);

	/**
	 * Annotating private methods with @Transactional has no effect...
	 */
	declare warning
	    // note, we should be able to say the following in one execution pcd, but
	    // aj doesn't like it...
		: execution(@Transactional * *(..)) &&
		  execution(private * *(..))
		: "@Transactional annotation on private method will be ignored";
}


add @Override in class AnnotationBeanConfigurerAspect

/*
 * Copyright 2002-2017 the original author or 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
 *
 *      https://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.springframework.beans.factory.aspectj;

import java.io.Serializable;

import org.aspectj.lang.annotation.control.CodeGenerationHint;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.AnnotationBeanWiringInfoResolver;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.wiring.BeanConfigurerSupport;

/**
 * Concrete aspect that uses the {@link Configurable} annotation to identify
 * which classes need autowiring.
 *
 * <p>The bean name to look up will be taken from the {@code @Configurable}
 * annotation if specified; otherwise, the default bean name to look up will be
 * the fully qualified name of the class being configured.
 *
 * @author Rod Johnson
 * @author Ramnivas Laddad
 * @author Juergen Hoeller
 * @author Adrian Colyer
 * @since 2.0
 * @see org.springframework.beans.factory.annotation.Configurable
 * @see org.springframework.beans.factory.annotation.AnnotationBeanWiringInfoResolver
 */
public aspect AnnotationBeanConfigurerAspect extends AbstractInterfaceDrivenDependencyInjectionAspect
		implements BeanFactoryAware, InitializingBean, DisposableBean {

	private BeanConfigurerSupport beanConfigurerSupport = new BeanConfigurerSupport();

	@Override
	public void setBeanFactory(BeanFactory beanFactory) {
		this.beanConfigurerSupport.setBeanWiringInfoResolver(new AnnotationBeanWiringInfoResolver());
		this.beanConfigurerSupport.setBeanFactory(beanFactory);
	}

	@Override
	public void afterPropertiesSet() {
		this.beanConfigurerSupport.afterPropertiesSet();
	}

	@Override
	public void configureBean(Object bean) {
		this.beanConfigurerSupport.configureBean(bean);
	}

	@Override
	public void destroy() {
		this.beanConfigurerSupport.destroy();
	}

	public pointcut inConfigurableBean() : @this(Configurable);

	public pointcut preConstructionConfiguration() : preConstructionConfigurationSupport(*);

	/*
	 * An intermediary to match preConstructionConfiguration signature (that doesn't expose the annotation object)
	 */
	@CodeGenerationHint(ifNameSuffix="bb0")
	private pointcut preConstructionConfigurationSupport(Configurable c) : @this(c) && if (c.preConstruction());

	declare parents: @Configurable * implements ConfigurableObject;

	/*
	 * This declaration shouldn't be needed,
	 * except for an AspectJ bug (https://bugs.eclipse.org/bugs/show_bug.cgi?id=214559)
	 */
	declare parents: @Configurable Serializable+ implements ConfigurableDeserializationSupport;

}

/*
 * Copyright 2002-2017 the original author or 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
 *
 *      https://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.springframework.beans.factory.aspectj;

import java.io.Serializable;

import org.aspectj.lang.annotation.control.CodeGenerationHint;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.AnnotationBeanWiringInfoResolver;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.wiring.BeanConfigurerSupport;

/**
 * Concrete aspect that uses the {@link Configurable} annotation to identify
 * which classes need autowiring.
 *
 * <p>The bean name to look up will be taken from the {@code @Configurable}
 * annotation if specified; otherwise, the default bean name to look up will be
 * the fully qualified name of the class being configured.
 *
 * @author Rod Johnson
 * @author Ramnivas Laddad
 * @author Juergen Hoeller
 * @author Adrian Colyer
 * @since 2.0
 * @see org.springframework.beans.factory.annotation.Configurable
 * @see org.springframework.beans.factory.annotation.AnnotationBeanWiringInfoResolver
 */
public aspect AnnotationBeanConfigurerAspect extends AbstractInterfaceDrivenDependencyInjectionAspect
		implements BeanFactoryAware, InitializingBean, DisposableBean {

	private BeanConfigurerSupport beanConfigurerSupport = new BeanConfigurerSupport();

	public void setBeanFactory(BeanFactory beanFactory) {
		this.beanConfigurerSupport.setBeanWiringInfoResolver(new AnnotationBeanWiringInfoResolver());
		this.beanConfigurerSupport.setBeanFactory(beanFactory);
	}

	public void afterPropertiesSet() {
		this.beanConfigurerSupport.afterPropertiesSet();
	}

	public void configureBean(Object bean) {
		this.beanConfigurerSupport.configureBean(bean);
	}

	public void destroy() {
		this.beanConfigurerSupport.destroy();
	}

	public pointcut inConfigurableBean() : @this(Configurable);

	public pointcut preConstructionConfiguration() : preConstructionConfigurationSupport(*);

	/*
	 * An intermediary to match preConstructionConfiguration signature (that doesn't expose the annotation object)
	 */
	@CodeGenerationHint(ifNameSuffix="bb0")
	private pointcut preConstructionConfigurationSupport(Configurable c) : @this(c) && if (c.preConstruction());

	declare parents: @Configurable * implements ConfigurableObject;

	/*
	 * This declaration shouldn't be needed,
	 * except for an AspectJ bug (https://bugs.eclipse.org/bugs/show_bug.cgi?id=214559)
	 */
	declare parents: @Configurable Serializable+ implements ConfigurableDeserializationSupport;

}


Aspects ordering doing my head in

Aspects ordering doing my head in

package edu.brown.cs.systems.tracing.aspects;

import edu.brown.cs.systems.retro.aspects.cpu.Sleeping;
import edu.brown.cs.systems.retro.aspects.cpu.XTraceAPICalls;
import edu.brown.cs.systems.xtrace.logging.BaggageWrappers;

/** Declares aspect ordering for aspects from Retro and XTrace that modify the same classes */
public aspect AspectsOrdering {
    declare precedence : BaggageWrappers, /* --- */ XTraceAPICalls, Sleeping, /* --- */ Futures, Runnables;
}

package edu.brown.cs.systems.tracing.aspects;

import edu.brown.cs.systems.retro.aspects.cpu.Sleeping;
import edu.brown.cs.systems.retro.aspects.cpu.XTraceAPICalls;
import edu.brown.cs.systems.xtrace.logging.BaggageWrappers;

/** Declares aspect ordering for aspects from Retro and XTrace that modify the same classes */
public aspect AspectsOrdering {
    declare precedence : BaggageWrappers, Futures, Runnables, /* --- */ XTraceAPICalls, Sleeping;
}


o Added svn:eol-style=native

o Added svn:eol-style=native

git-svn-id: dcbd4fc8c11328f69dc395471f1d5a9d33f6e6b1@6564 52ab4f32-60fc-0310-b215-8acea882cd1b

/**
 * The MIT License
 *
 * Copyright 2005-2006 The Codehaus.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do
 * so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
public aspect AppAspect
{

    pointcut appCut() : call(* *.printHelloWorld(..));

    before() : appCut() {
        System.out.println( "I'm saying " );
    }
}


HIGHLY UNTESTED COMMIT: attempt to throw checked exceptions

/**
 * 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.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.Registry;
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;

    private TransactionBeginEvent begin;
    private TransactionBeganEvent began;
    private TransactionCommitEvent commit;
    private TransactionCommittedEvent committed;
    private TransactionRollbackEvent rollback;
    private TransactionRolledbackEvent rolledback;

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

    @Inject
    void setRegistry(Registry registry) {
        Preconditions.checkNotNull(registry, "Registry");
        this.begin = registry.proxy(TransactionBeginEvent.class);
        this.began = registry.proxy(TransactionBeganEvent.class);
        this.commit = registry.proxy(TransactionCommitEvent.class);
        this.committed = registry.proxy(TransactionCommittedEvent.class);
        this.rollback = registry.proxy(TransactionRollbackEvent.class);
        this.rolledback = registry.proxy(TransactionRolledbackEvent.class);
    }

    protected abstract pointcut transactional();

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

        try {
            LOG.trace("Status of transaction: {}", tx.getStatus());
        } catch (SystemException e) {
            throw new IllegalStateException(e);
        }

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

        local = status == Status.STATUS_NO_TRANSACTION;

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

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

        final Object returnValue;

        try {
            LOG.trace("Status before execution: {}", status);
            returnValue = proceed();
        } catch (Exception e) {
            try {
                if (local &&
                    (tx.getStatus() == Status.STATUS_ACTIVE || tx.getStatus() == Status.STATUS_MARKED_ROLLBACK)) {
                    LOG.info("Rolling back local/active transaction {}", tx);
                    rollback(tx);
                } else if (tx.getStatus() != Status.STATUS_ROLLEDBACK || tx.getStatus() != Status.STATUS_ROLLING_BACK) {
                    LOG.debug("Setting transaction {} as rollback only", tx);
                    tx.setRollbackOnly();
                }
            } catch (Exception inner) {
                LOG.error("Rollback failed", inner);
            }
            // FIXME this effectively shadows the real exceptions thus preventing correct exception handling
            throw sneakyThrow(e);
            //throw new IllegalStateException(e);
        }

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

        LOG.trace("Status after execution: {}", status);

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

        return returnValue;
    }

    private void rollback(UserTransaction tx) throws SystemException {
        rollback.eventTransactionRollback(tx);
        tx.rollback();
        rolledback.eventTransactionRolledback(tx);
    }

    private RuntimeException sneakyThrow(Throwable t) {
        return this.<RuntimeException>doSneakyThrow(t);
    }

    @SuppressWarnings("unchecked")
    private <T extends Throwable> T doSneakyThrow(Throwable t) throws T {
        return (T)t;
    }

}

/**
 * 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.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.Registry;
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;

    private TransactionBeginEvent begin;
    private TransactionBeganEvent began;
    private TransactionCommitEvent commit;
    private TransactionCommittedEvent committed;
    private TransactionRollbackEvent rollback;
    private TransactionRolledbackEvent rolledback;

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

    @Inject
    void setRegistry(Registry registry) {
        Preconditions.checkNotNull(registry, "Registry");
        this.begin = registry.proxy(TransactionBeginEvent.class);
        this.began = registry.proxy(TransactionBeganEvent.class);
        this.commit = registry.proxy(TransactionCommitEvent.class);
        this.committed = registry.proxy(TransactionCommittedEvent.class);
        this.rollback = registry.proxy(TransactionRollbackEvent.class);
        this.rolledback = registry.proxy(TransactionRolledbackEvent.class);
    }

    protected abstract pointcut transactional();

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

        try {
            LOG.trace("Status of transaction: {}", tx.getStatus());
        } catch (SystemException e) {
            throw new IllegalStateException(e);
        }

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

        local = status == Status.STATUS_NO_TRANSACTION;

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

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

        final Object returnValue;

        try {
            LOG.trace("Status before execution: {}", status);
            returnValue = proceed();
        } catch (Exception e) {
            try {
                if (local &&
                    (tx.getStatus() == Status.STATUS_ACTIVE || tx.getStatus() == Status.STATUS_MARKED_ROLLBACK)) {
                    LOG.info("Rolling back local/active transaction {}", tx);
                    rollback(tx);
                } else if (tx.getStatus() != Status.STATUS_ROLLEDBACK || tx.getStatus() != Status.STATUS_ROLLING_BACK) {
                    LOG.debug("Setting transaction {} as rollback only", tx);
                    tx.setRollbackOnly();
                }
            } catch (Exception inner) {
                LOG.error("Rollback failed", inner);
            }
            // FIXME this effectively shadows the real exceptions thus preventing correct exception handling
            throw new IllegalStateException(e);
        }

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

        LOG.trace("Status after execution: {}", status);

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

        return returnValue;
    }

    private void rollback(UserTransaction tx) throws SystemException {
        rollback.eventTransactionRollback(tx);
        tx.rollback();
        rolledback.eventTransactionRolledback(tx);
    }

}


CThread2 renamed to CThread

CThread2 renamed to CThread

import properties.Property;
import properties.competition.JavaMOP;
import structure.impl.other.Verdict;
import benchmark.competition.java.QEAMonitoringAspect;

public aspect JavaMOPThreeAspect extends QEAMonitoringAspect {

	private final int A = 1;
	private final int B = 2;
	private final int C = 3;

	public JavaMOPThreeAspect() {
		super(new JavaMOP().make(Property.JAVAMOP_THREE));
		validationMsg = "Property JavaMOP 3 satisfied";
		violationMsg = "Property JavaMOP 3 violated. The functions A(), B(), C() must be called equal times";
	}

	pointcut A() : call(void CThread.A());

	pointcut B() : call(void CThread.B());

	pointcut C() : call(void CThread.C());

	before() : A() {
		Verdict verdict;
		synchronized (monitor) {
			verdict = monitor.step(A);
		}
		if (verdict == Verdict.FAILURE) {
			System.err.println(violationMsg);
			printTimeAndExit();
		}
	}

	before() : B() {
		Verdict verdict;
		synchronized (monitor) {
			verdict = monitor.step(B);
		}
		if (verdict == Verdict.FAILURE) {
			System.err.println(violationMsg);
			printTimeAndExit();
		}
	}

	before() : C() {
		Verdict verdict;
		synchronized (monitor) {
			verdict = monitor.step(C);
		}
		if (verdict == Verdict.FAILURE) {
			System.err.println(violationMsg);
			printTimeAndExit();
		}
	}
}

import properties.Property;
import properties.competition.JavaMOP;
import structure.impl.other.Verdict;
import benchmark.competition.java.QEAMonitoringAspect;

public aspect JavaMOPThreeAspect extends QEAMonitoringAspect {

	private final int A = 1;
	private final int B = 2;
	private final int C = 3;

	public JavaMOPThreeAspect() {
		super(new JavaMOP().make(Property.JAVAMOP_THREE));
		validationMsg = "Property JavaMOP 3 satisfied";
		violationMsg = "Property JavaMOP 3 violated. The functions A(), B(), C() must be called equal times";
	}

	pointcut A() : call(void CThread2.A());

	pointcut B() : call(void CThread2.B());

	pointcut C() : call(void CThread2.C());

	before() : A() {
		Verdict verdict;
		synchronized (monitor) {
			verdict = monitor.step(A);
		}
		if (verdict == Verdict.FAILURE) {
			System.err.println(violationMsg);
			printTimeAndExit();
		}
	}

	before() : B() {
		Verdict verdict;
		synchronized (monitor) {
			verdict = monitor.step(B);
		}
		if (verdict == Verdict.FAILURE) {
			System.err.println(violationMsg);
			printTimeAndExit();
		}
	}

	before() : C() {
		Verdict verdict;
		synchronized (monitor) {
			verdict = monitor.step(C);
		}
		if (verdict == Verdict.FAILURE) {
			System.err.println(violationMsg);
			printTimeAndExit();
		}
	}
}


replace system.out in aspect with log.debug

package org.folio.rest.annotations;

import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;

import java.util.Arrays;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.ValidatorFactory;
import javax.validation.executable.ExecutableValidator;

import org.aspectj.lang.reflect.MethodSignature;
import org.aspectj.lang.annotation.SuppressAjWarnings;

public aspect RestValidator {

  static private ValidatorFactory factory;
  static final Logger log = LoggerFactory.getLogger(RestValidator.class);

  static {
    factory = Validation.buildDefaultValidatorFactory();
  }

  static private ExecutableValidator getMethodValidator() {
    return factory.getValidator().forExecutables();
  }

  pointcut validatedMethodCall() : execution(@Validate * *(..));

  /**
   * Validates the method parameters.
   */
  @SuppressAjWarnings({"adviceDidNotMatch"})
  before() : validatedMethodCall() {

    MethodSignature methodSignature = (MethodSignature) thisJoinPoint.getSignature();

    String[] params = methodSignature.getParameterNames();

    Set<? extends ConstraintViolation<?>> validationErrors = getMethodValidator().validateParameters(thisJoinPoint.getThis(),
        methodSignature.getMethod(), thisJoinPoint.getArgs());

    if (validationErrors.isEmpty()) {
      log.debug("Valid call: with args " + methodSignature.getMethod() + Arrays.toString(thisJoinPoint.getArgs()));
    } else {
      log.debug("Invalid call: with args " + methodSignature.getMethod() + Arrays.toString(thisJoinPoint.getArgs()));
      RuntimeException ex = buildValidationException(validationErrors, params);
      throw ex;
    }
  }

  /**
   * @param validationErrors
   *          The errors detected in a method/constructor call.
   * @return A RuntimeException with information about the detected validation
   *         errors.
   */
  private RuntimeException buildValidationException(Set<? extends ConstraintViolation<?>> validationErrors, String[] paramNames) {
    StringBuilder sb = new StringBuilder();
    for (ConstraintViolation<?> cv : validationErrors) {
      // sb.append("\n" + cv.getPropertyPath() + "{" + cv.getInvalidValue() +
      // "} : " + cv.getMessage());
      String positionOfBadParam = cv.getPropertyPath().toString();
      if (positionOfBadParam != null) {
        try {
          String paramName = paramNames[Integer.valueOf(positionOfBadParam.substring(positionOfBadParam.length() - 1,
              positionOfBadParam.length()))];
          sb.append("\n '" + paramName + "' parameter is incorrect. parameter value {" + cv.getInvalidValue() + "} is not valid: "
              + cv.getMessage());

        } catch (Exception e) {
          sb.append("\n not all parameters were passed properly. parameter value {" + cv.getInvalidValue() + "} is not valid: "
              + cv.getMessage());

        }
      }
    }
    return new ValidationException(sb.toString());
  }
}

package org.folio.rest.annotations;

import java.util.Arrays;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.ValidatorFactory;
import javax.validation.executable.ExecutableValidator;
import org.aspectj.lang.reflect.MethodSignature;
import org.aspectj.lang.annotation.SuppressAjWarnings;

public aspect RestValidator {

  static private ValidatorFactory factory;

  static {
    factory = Validation.buildDefaultValidatorFactory();
  }

  static private ExecutableValidator getMethodValidator() {
    return factory.getValidator().forExecutables();
  }

  pointcut validatedMethodCall() : execution(@Validate * *(..));

  /**
   * Validates the method parameters.
   */
  @SuppressAjWarnings({"adviceDidNotMatch"})
  before() : validatedMethodCall() {

    MethodSignature methodSignature = (MethodSignature) thisJoinPoint.getSignature();

    System.out.println("Validating call: with args " + methodSignature.getMethod() + Arrays.toString(thisJoinPoint.getArgs()));

    String[] params = methodSignature.getParameterNames();

    Set<? extends ConstraintViolation<?>> validationErrors = getMethodValidator().validateParameters(thisJoinPoint.getThis(),
        methodSignature.getMethod(), thisJoinPoint.getArgs());

    if (validationErrors.isEmpty()) {
      System.out.println("Valid call......");
    } else {
      System.out.println("Invalid call......");
      RuntimeException ex = buildValidationException(validationErrors, params);
      throw ex;
    }
  }

  /**
   * @param validationErrors
   *          The errors detected in a method/constructor call.
   * @return A RuntimeException with information about the detected validation
   *         errors.
   */
  private RuntimeException buildValidationException(Set<? extends ConstraintViolation<?>> validationErrors, String[] paramNames) {
    StringBuilder sb = new StringBuilder();
    for (ConstraintViolation<?> cv : validationErrors) {
      // sb.append("\n" + cv.getPropertyPath() + "{" + cv.getInvalidValue() +
      // "} : " + cv.getMessage());
      String positionOfBadParam = cv.getPropertyPath().toString();
      if (positionOfBadParam != null) {
        try {
          String paramName = paramNames[Integer.valueOf(positionOfBadParam.substring(positionOfBadParam.length() - 1,
              positionOfBadParam.length()))];
          sb.append("\n '" + paramName + "' parameter is incorrect. parameter value {" + cv.getInvalidValue() + "} is not valid: "
              + cv.getMessage());

        } catch (Exception e) {
          sb.append("\n not all parameters were passed properly. parameter value {" + cv.getInvalidValue() + "} is not valid: "
              + cv.getMessage());

        }
      }
    }
    return new ValidationException(sb.toString());
  }
}


Fix syntax error due to missing semicolon

git-svn-id: 7acc490bd371dbc82047a939b87dc892fdc31f59@28620 76a6fc44-f60b-0410-a9a8-e67b0e8fc65c

package tlc2.tool.distributed;

public aspect RMIMethodMonitorAspect {

	// catch all method calls to RMI methods
	pointcut callToRemoteMethod() :
		   execution(* tlc2.tool.distributed.InternRMI.*(..))
		|| execution(* tlc2.tool.distributed.TLCServerRMI.*(..))
		|| execution(* tlc2.tool.distributed.TLCWorkerRMI.*(..))
		|| execution(* tlc2.tool.distributed.fp.FPSetRMI.*(..));

	before(): (callToRemoteMethod()) {
		RMIMethodMonitor.entering(thisJoinPoint);
	}
}

package tlc2.tool.distributed;

public aspect RMIMethodMonitorAspect {

	// catch all method calls to RMI methods
	pointcut callToRemoteMethod() :
		   execution(* tlc2.tool.distributed.InternRMI.*(..))
		|| execution(* tlc2.tool.distributed.TLCServerRMI.*(..))
		|| execution(* tlc2.tool.distributed.TLCWorkerRMI.*(..))
		|| execution(* tlc2.tool.distributed.fp.FPSetRMI.*(..))

	before(): (callToRemoteMethod()) {
		RMIMethodMonitor.entering(thisJoinPoint);
	}
}


Tryint to Resolve Quota Problems

Tryint to Resolve Quota Problems

package com.chitter.aspect;

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

import javax.jdo.Extent;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;
import javax.jdo.annotations.PersistenceCapable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jsr107cache.Cache;
import net.sf.jsr107cache.CacheException;
import net.sf.jsr107cache.CacheFactory;
import net.sf.jsr107cache.CacheManager;

import com.chitter.persistence.Announcement;
import com.chitter.persistence.UserAccount;
import com.chitter.persistence.UserStatistic;
import com.chitter.persistence.UserTwitterTimeline;
import com.chitter.utility.ExceptionPrinter;

public aspect Persistence {
	private static Cache cache;
	static
	{
		try
		{
			CacheManager cacheManager = CacheManager.getInstance();
			CacheFactory cacheFactory = cacheManager.getCacheFactory();
			cache = cacheFactory.createCache(Collections.EMPTY_MAP);
		} catch (CacheException e) {
			ExceptionPrinter.print(System.err, e, "Couldn't create cache at PersistenceAspect");
		}
	}

	/**
	 * captures ctors with more than one arg and
	 * all setters of @PersistenceCapable objects.
	 */
	pointcut pushObject(Object o): target(o) && (call(* (@PersistenceCapable *).set*(..)) || execution((@PersistenceCapable *).new(*,*,..)));
	pointcut pullObject(Object pk): args(pk) && call((@PersistenceCapable *).new(*));
	pointcut pullList(): call(List (@PersistenceCapable *).get*List());
	pointcut pullExtent(): call(Extent (@PersistenceCapable *).get*Extent());

	pointcut pmShouldClose() : call(* com.chitter..*Servlet.processRequest(HttpServletRequest,HttpServletResponse));

	pointcut withinEscapePersistence(): withincode(@EscapePersistence * *(..));

	@SuppressWarnings("all")
	public static Extent UserAccount.getUserAccountExtent(){
		return null;
	}

	@SuppressWarnings("all")
	public static List UserAccount.getUserAccountList(){
		return new ArrayList<UserAccount>();
	}

	@SuppressWarnings("all")
	public static List UserAccount.getTimelineActiveAndOnlineUsers(){
		PersistenceManager pm = getPM();

		try {
			Query q = pm.newQuery(UserAccount.class, "this.isTimelineActive == true && this.isOnline == true");
			return (List) q.execute();
		} catch (Exception e) {
			ExceptionPrinter.print(System.err,e,"I couldn't fetch timeline active and online users");
			return (List)(new ArrayList<Object>());
		}
	}

	@SuppressWarnings("all")
	public static List UserAccount.getTimelineActiveUsers(){
		PersistenceManager pm = getPM();

		try {
			Query q = pm.newQuery(UserAccount.class, "this.isTimelineActive == true");
			return (List) q.execute();
		} catch (Exception e) {
			ExceptionPrinter.print(System.err,e,"I couldn't fetch timeline active users");
			return (List)(new ArrayList<Object>());
		}
	}

	@SuppressWarnings("all")
	public static List UserAccount.getOnlineUsers(){
		PersistenceManager pm = getPM();

		try {
			Query q = pm.newQuery(UserAccount.class, "this.isOnline == true");
			return (List) q.execute();
		} catch (Exception e) {
			ExceptionPrinter.print(System.err,e,"I couldn't fetch online users");
			return (List)(new ArrayList<Object>());
		}
	}

	@SuppressWarnings("all")
	public static List UserStatistic.getUserStatisticList() {
		return new ArrayList<UserStatistic> ();
	}

	@SuppressWarnings("all")
	public static List UserTwitterTimeline.getUserTwitterTimelineList() {
		return new ArrayList<UserTwitterTimeline> ();
	}

	@SuppressWarnings("all")
	public static List Announcement.getAnnouncementList() {
		return new ArrayList<Announcement> ();
	}

	private static final PersistenceManagerFactory PMF =
			JDOHelper.getPersistenceManagerFactory("transactions-optional");
	private static final ThreadLocal<PersistenceManager> perThreadPM
	= new ThreadLocal<PersistenceManager>();

	private Persistence() {};

	private static PersistenceManager getPM() {
		PersistenceManager PM = perThreadPM.get();
		if (PM == null) {
			PM = PMF.getPersistenceManager();
			perThreadPM.set(PM);
		}
		return PM;
	}

	after(Object o) : pushObject(o) && !withinEscapePersistence(){
		PersistenceManager pm = getPM();
		/**
		 * First try to convert object to UserStatistic.
		 * If you can, that means the persistent object was UserStatistic,
		 * so you should flag statistics array as dirty.
		 * (o.w. it will not persist changes to the array.)
		 */
		if(o.getClass().equals(UserStatistic.class)) {
			UserStatistic statistic=(UserStatistic) o;
			JDOHelper.makeDirty(statistic, "statistics");
		}
		pm.makePersistent(o.getClass().cast(o));
		cache.put(o.getClass().getName() + "_" + pm.getObjectId(o), o);
		pm.flush();
	}

	@SuppressWarnings("all")
	Object around(Object pk) : pullObject(pk) && !withinEscapePersistence(){
		PersistenceManager pm = getPM();
		try{
			Object r = cache.peek(thisJoinPointStaticPart.getSignature().getDeclaringTypeName() + "_" + pk);
			if (r == null) {
				r = pm.getObjectById(thisJoinPoint.getSignature().getDeclaringType(),pk);
				cache.put(thisJoinPointStaticPart.getSignature().getDeclaringTypeName() + "_" + pk, r);
			}
			return r;
		} catch (Exception e) {
			cache.remove(thisJoinPointStaticPart.getSignature().getDeclaringTypeName() + "_" + pk);
			ExceptionPrinter.print(System.err, e, "I couldn't fetch persistent object for " +
					thisJoinPointStaticPart.getSignature().getDeclaringTypeName() + " " + pk);
			return null;
		}
	}

	@SuppressWarnings("all")
	List around() : pullList() {
		PersistenceManager pm = getPM();

		try {
			List list = (List) pm.newQuery(thisJoinPoint.getSignature().getDeclaringType()).execute();
			return list;
		} catch (Exception e) {
			ExceptionPrinter.print(System.err,e,"I couldn't fetch persistent list for "+getClass());
			return (List)(new ArrayList<Object>());
		}
	}

	@SuppressWarnings("all")
	/*Extent around() : pullExtent() {
		PersistenceManager pm = getPM();

		try {
			Extent extent = pm.getExtent(thisJoinPoint.getSignature().getDeclaringType(), false);
			return extent;
		} catch (Exception e) {
			ExceptionPrinter.print(System.err, e, "I couldn't fetch persistent extent for "+getClass());
			return null;
		}
    }*/

	after() : pmShouldClose() {
		PersistenceManager PM = perThreadPM.get();
		if (PM != null) {
			perThreadPM.remove();
			Transaction tx = PM.currentTransaction();
			if (tx.isActive()) {
				tx.rollback();
			}
			PM.close();
		}
	}

}

package com.chitter.aspect;

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

import javax.jdo.Extent;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;
import javax.jdo.annotations.PersistenceCapable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jsr107cache.Cache;
import net.sf.jsr107cache.CacheException;
import net.sf.jsr107cache.CacheFactory;
import net.sf.jsr107cache.CacheManager;

import com.chitter.persistence.Announcement;
import com.chitter.persistence.UserAccount;
import com.chitter.persistence.UserStatistic;
import com.chitter.persistence.UserTwitterTimeline;
import com.chitter.utility.ExceptionPrinter;

public aspect Persistence {
	private static Cache cache;
	static
	{
		try
		{
			CacheManager cacheManager = CacheManager.getInstance();
			CacheFactory cacheFactory = cacheManager.getCacheFactory();
			cache = cacheFactory.createCache(Collections.EMPTY_MAP);
		} catch (CacheException e) {
			ExceptionPrinter.print(System.err, e, "Couldn't create cache at PersistenceAspect");
		}
	}

	/**
	 * captures ctors with more than one arg and
	 * all setters of @PersistenceCapable objects.
	 */
	pointcut pushObject(Object o): target(o) && (call(* (@PersistenceCapable *).set*(..)) || execution((@PersistenceCapable *).new(*,*,..)));
	pointcut pullObject(Object pk): args(pk) && call((@PersistenceCapable *).new(*));
	pointcut pullList(): call(List (@PersistenceCapable *).get*List());
	pointcut pullExtent(): call(Extent (@PersistenceCapable *).get*Extent());

	pointcut pmShouldClose() : call(* com.chitter..*Servlet.processRequest(HttpServletRequest,HttpServletResponse));

	pointcut withinEscapePersistence(): withincode(@EscapePersistence * *(..));

	@SuppressWarnings("all")
	public static Extent UserAccount.getUserAccountExtent(){
		return null;
	}

	@SuppressWarnings("all")
	public static List UserAccount.getUserAccountList(){
		return new ArrayList<UserAccount>();
	}

	@SuppressWarnings("all")
	public static List UserAccount.getTimelineActiveAndOnlineUsers(){
		PersistenceManager pm = getPM();

		try {
			Query q = pm.newQuery(UserAccount.class, "this.isTimelineActive == true && this.isOnline == true");
			return (List) q.execute();
		} catch (Exception e) {
			ExceptionPrinter.print(System.err,e,"I couldn't fetch timeline active and online users");
			return (List)(new ArrayList<Object>());
		}
	}

	@SuppressWarnings("all")
	public static List UserAccount.getTimelineActiveUsers(){
		PersistenceManager pm = getPM();

		try {
			Query q = pm.newQuery(UserAccount.class, "this.isTimelineActive == true");
			return (List) q.execute();
		} catch (Exception e) {
			ExceptionPrinter.print(System.err,e,"I couldn't fetch timeline active users");
			return (List)(new ArrayList<Object>());
		}
	}

	@SuppressWarnings("all")
	public static List UserAccount.getOnlineUsers(){
		PersistenceManager pm = getPM();

		try {
			Query q = pm.newQuery(UserAccount.class, "this.isOnline == true");
			return (List) q.execute();
		} catch (Exception e) {
			ExceptionPrinter.print(System.err,e,"I couldn't fetch online users");
			return (List)(new ArrayList<Object>());
		}
	}

	@SuppressWarnings("all")
	public static List UserStatistic.getUserStatisticList() {
		return new ArrayList<UserStatistic> ();
	}

	@SuppressWarnings("all")
	public static List UserTwitterTimeline.getUserTwitterTimelineList() {
		return new ArrayList<UserTwitterTimeline> ();
	}

	@SuppressWarnings("all")
	public static List Announcement.getAnnouncementList() {
		return new ArrayList<Announcement> ();
	}

	private static final PersistenceManagerFactory PMF =
			JDOHelper.getPersistenceManagerFactory("transactions-optional");
	private static final ThreadLocal<PersistenceManager> perThreadPM
	= new ThreadLocal<PersistenceManager>();

	private Persistence() {};

	private static PersistenceManager getPM() {
		PersistenceManager PM = perThreadPM.get();
		if (PM == null) {
			PM = PMF.getPersistenceManager();
			perThreadPM.set(PM);
		}
		return PM;
	}

	after(Object o) : pushObject(o) && !withinEscapePersistence(){
		PersistenceManager pm = getPM();
		/**
		 * First try to convert object to UserStatistic.
		 * If you can, that means the persistent object was UserStatistic,
		 * so you should flag statistics array as dirty.
		 * (o.w. it will not persist changes to the array.)
		 */
		if(o.getClass().equals(UserStatistic.class)) {
			UserStatistic statistic=(UserStatistic) o;
			JDOHelper.makeDirty(statistic, "statistics");
		}
		pm.makePersistent(o.getClass().cast(o));
		cache.put(o.getClass().getName() + "_" + pm.getObjectId(o), o);
		pm.flush();
	}

	@SuppressWarnings("all")
	Object around(Object pk) : pullObject(pk) && !withinEscapePersistence(){
		PersistenceManager pm = getPM();
		try{
			Object r = cache.peek(thisJoinPointStaticPart.getSignature().getDeclaringTypeName() + "_" + pk);
			if (r == null) {
				r = pm.getObjectById(thisJoinPoint.getSignature().getDeclaringType(),pk);
				cache.put(thisJoinPointStaticPart.getSignature().getDeclaringTypeName() + "_" + pk, r);
			}
			return r;
		} catch (Exception e) {
			ExceptionPrinter.print(System.err, e, "I couldn't fetch persistent object for " +
					thisJoinPointStaticPart.getSignature().getDeclaringTypeName() + " " + pk);
			return null;
		}
	}

	@SuppressWarnings("all")
	List around() : pullList() {
		PersistenceManager pm = getPM();

		try {
			List list = (List) pm.newQuery(thisJoinPoint.getSignature().getDeclaringType()).execute();
			return list;
		} catch (Exception e) {
			ExceptionPrinter.print(System.err,e,"I couldn't fetch persistent list for "+getClass());
			return (List)(new ArrayList<Object>());
		}
	}

	@SuppressWarnings("all")
	/*Extent around() : pullExtent() {
		PersistenceManager pm = getPM();

		try {
			Extent extent = pm.getExtent(thisJoinPoint.getSignature().getDeclaringType(), false);
			return extent;
		} catch (Exception e) {
			ExceptionPrinter.print(System.err, e, "I couldn't fetch persistent extent for "+getClass());
			return null;
		}
    }*/

	after() : pmShouldClose() {
		PersistenceManager PM = perThreadPM.get();
		if (PM != null) {
			perThreadPM.remove();
			Transaction tx = PM.currentTransaction();
			if (tx.isActive()) {
				tx.rollback();
			}
			PM.close();
		}
	}

}


* fix changes

* fix changes

package ru.agentlab.maia.context.events2;

import ru.agentlab.maia.context.IContext;
import ru.agentlab.maia.context.events.MaiaContextChangeObjectEvent;
import ru.agentlab.maia.context.events.MaiaContextRemoveObjectEvent;
import ru.agentlab.maia.context.events.MaiaContextSetObjectEvent;
import ru.agentlab.maia.event.IMaiaEventBroker;
import ru.agentlab.maia.context.aspect.AContext;

public aspect AContextEvents extends AContext {

	void around(IContext context, String id): onRemoveByString(context, id) {
		IMaiaEventBroker broker = null;
		Object old = null;
		broker = context.get(IMaiaEventBroker.class);
		old = context.getLocal(id);

		proceed(context, id);

		if (broker != null) {
			if (old != null) {
				broker.post(new MaiaContextRemoveObjectEvent(old));
			}
		}
	}

	void around(IContext context, Class<?> id): onRemoveByClass(context, id) {
		IMaiaEventBroker broker = null;
		Object old = null;
		broker = context.get(IMaiaEventBroker.class);
		old = context.getLocal(id);

		proceed(context, id);

		if (broker != null) {
			if (old != null) {
				broker.post(new MaiaContextRemoveObjectEvent(old));
			}
		}
	}

	void around(IContext context, String id, Object value): onSetByString(context, id, value) {
		IMaiaEventBroker broker = null;
		Object old = null;
		broker = context.get(IMaiaEventBroker.class);
		old = context.getLocal(id);

		proceed(context, id, value);

		if (broker != null) {
			if (old == null) {
				broker.post(new MaiaContextSetObjectEvent(context, value));
			} else {
				broker.post(new MaiaContextChangeObjectEvent(context, value));
			}
		}
	}

	void around(IContext context, Class<?> id, Object value): onSetByClass(context, id, value) {
		IMaiaEventBroker broker = null;
		Object old = null;
		broker = context.get(IMaiaEventBroker.class);
		old = context.getLocal(id);

		proceed(context, id, value);

		if (broker != null) {
			if (old == null) {
				broker.post(new MaiaContextSetObjectEvent(context, value));
			} else {
				broker.post(new MaiaContextChangeObjectEvent(context, value));
			}
		}
	}
}

package ru.agentlab.maia.context.events2;

import ru.agentlab.maia.context.IContext;
import ru.agentlab.maia.context.events.MaiaContextChangeObjectEvent;
import ru.agentlab.maia.context.events.MaiaContextRemoveObjectEvent;
import ru.agentlab.maia.context.events.MaiaContextSetObjectEvent;
import ru.agentlab.maia.context.exception.MaiaContextKeyNotFound;
import ru.agentlab.maia.event.IMaiaEventBroker;
import ru.agentlab.maia.context.aspect.AContext;

public aspect AContextEvents extends AContext {

	void around(IContext context, String id): onRemoveByString(context, id) {
		IMaiaEventBroker broker = null;
		Object old = null;
		try {
			broker = context.getService(IMaiaEventBroker.class);
			old = context.getServiceLocal(id);
		} catch (MaiaContextKeyNotFound e) {
		}

		proceed(context, id);

		if (broker != null) {
			if (old != null) {
				broker.post(new MaiaContextRemoveObjectEvent(old));
			}
		}
	}

	void around(IContext context, Class<?> id): onRemoveByClass(context, id) {
		IMaiaEventBroker broker = null;
		Object old = null;
		try {
			broker = context.getService(IMaiaEventBroker.class);
			old = context.getServiceLocal(id);
		} catch (MaiaContextKeyNotFound e) {
		}

		proceed(context, id);

		if (broker != null) {
			if (old != null) {
				broker.post(new MaiaContextRemoveObjectEvent(old));
			}
		}
	}

	void around(IContext context, String id, Object value): onSetByString(context, id, value) {
		IMaiaEventBroker broker = null;
		Object old = null;
		try {
			broker = context.getService(IMaiaEventBroker.class);
			old = context.getServiceLocal(id);
		} catch (MaiaContextKeyNotFound e) {
		}

		proceed(context, id, value);

		if (broker != null) {
			if (old == null) {
				broker.post(new MaiaContextSetObjectEvent(context, value));
			} else {
				broker.post(new MaiaContextChangeObjectEvent(context, value));
			}
		}
	}

	void around(IContext context, Class<?> id, Object value): onSetByClass(context, id, value) {
		IMaiaEventBroker broker = null;
		Object old = null;
		try {
			broker = context.getService(IMaiaEventBroker.class);
			old = context.getServiceLocal(id);
		} catch (MaiaContextKeyNotFound e) {
		}

		proceed(context, id, value);

		if (broker != null) {
			if (old == null) {
				broker.post(new MaiaContextSetObjectEvent(context, value));
			} else {
				broker.post(new MaiaContextChangeObjectEvent(context, value));
			}
		}
	}
}