commit 46c49b79ea575837e15bae84b034d54682cd158b
Author: Iyappan Srinivasan <iyappans@yahoo-inc.com>
Date:   Fri Jul 23 05:52:01 2010 +0000

    MAPREDUCE-1955 https://issues.apache.org/jira/secure/attachment/12450264/1955-ydist-security-patch.txt

git-svn-id: 7e7a2d564dde2945c3a26e08d1235fcc0cb7aba1@1077581 13f79535-47bb-0310-9956-ffa450edef68

/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.apache.hadoop.mapred;

import java.io.IOException;
import org.apache.hadoop.mapreduce.test.system.JobInfo;

/**
 * Aspect to add a utility method in the JobInProgress for easing up the
 * construction of the JobInfo object.
 */
privileged aspect JobInProgressAspect {

  /**
   * Returns a read only view of the JobInProgress object which is used by the
   * client.
   *
   * @return JobInfo of the current JobInProgress object
   */
  public JobInfo JobInProgress.getJobInfo() {
    String historyLoc = getHistoryPath();
    JobInfoImpl jobInfoImpl;
    if (tasksInited) {
      jobInfoImpl = new JobInfoImpl(
          this.getJobID(), this.isSetupLaunched(), this.isSetupFinished(), this
              .isCleanupLaunched(), this.runningMaps(), this.runningReduces(),
          this.pendingMaps(), this.pendingReduces(), this.finishedMaps(), this
              .finishedReduces(), this.getStatus(), historyLoc, this
              .getBlackListedTrackers(), false, this.numMapTasks,
          this.numReduceTasks, this.isHistoryFileCopied());
    } else {
      jobInfoImpl = new JobInfoImpl(
          this.getJobID(), false, false, false, 0, 0, this.pendingMaps(), this
              .pendingReduces(), this.finishedMaps(), this.finishedReduces(),
          this.getStatus(), historyLoc, this.getBlackListedTrackers(), this
              .isComplete(), this.numMapTasks, this.numReduceTasks,
              this.isHistoryFileCopied());
    }
    jobInfoImpl.setFinishTime(getJobFinishTime());
    jobInfoImpl.setLaunchTime(getJobLaunchTime());
    jobInfoImpl.setNumSlotsPerReduce(getJobNumSlotsPerReduce());
    jobInfoImpl.setNumSlotsPerMap(getJobNumSlotsPerMap());
    return jobInfoImpl;
  }

  private long JobInProgress.getJobFinishTime() {
    long finishTime = 0;
    if (this.isComplete()) {
      finishTime = this.getFinishTime();
    }
    return finishTime;
  }

  private long JobInProgress.getJobLaunchTime() {
    long LaunchTime = 0;
    if (this.isComplete()) {
      LaunchTime = this.getLaunchTime();
    }
    return LaunchTime;
  }

  private int JobInProgress.getJobNumSlotsPerReduce() {
    int numSlotsPerReduce = 0;
    if (this.isComplete()) {
      numSlotsPerReduce = this.getNumSlotsPerReduce();
    }
    return numSlotsPerReduce;
  }

  private int JobInProgress.getJobNumSlotsPerMap() {
    int numSlotsPerMap = 0;
    if (this.isComplete()) {
      numSlotsPerMap = this.getNumSlotsPerMap();
    }
    return numSlotsPerMap;
 }

  private String JobInProgress.getHistoryPath() {
    String historyLoc = "";
    if(this.isComplete()) {
      historyLoc = this.getHistoryFile();
    } else {
      String historyFileName = null;
      try {
        historyFileName  = JobHistory.JobInfo.getJobHistoryFileName(conf,
            jobId);
      } catch(IOException e) {
      }
      if(historyFileName != null) {
        historyLoc = JobHistory.JobInfo.getJobHistoryLogLocation(
            historyFileName).toString();
      }
    }
    return historyLoc;
  }

}

/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.apache.hadoop.mapred;

import java.io.IOException;
import org.apache.hadoop.mapreduce.test.system.JobInfo;

/**
 * Aspect to add a utility method in the JobInProgress for easing up the
 * construction of the JobInfo object.
 */
privileged aspect JobInProgressAspect {

  /**
   * Returns a read only view of the JobInProgress object which is used by the
   * client.
   *
   * @return JobInfo of the current JobInProgress object
   */
  public JobInfo JobInProgress.getJobInfo() {
    String historyLoc = getHistoryPath();
    JobInfoImpl jobInfoImpl;
    if (tasksInited.get()) {
      jobInfoImpl = new JobInfoImpl(
          this.getJobID(), this.isSetupLaunched(), this.isSetupFinished(), this
              .isCleanupLaunched(), this.runningMaps(), this.runningReduces(),
          this.pendingMaps(), this.pendingReduces(), this.finishedMaps(), this
              .finishedReduces(), this.getStatus(), historyLoc, this
              .getBlackListedTrackers(), false, this.numMapTasks,
          this.numReduceTasks, this.isHistoryFileCopied());
    } else {
      jobInfoImpl = new JobInfoImpl(
          this.getJobID(), false, false, false, 0, 0, this.pendingMaps(), this
              .pendingReduces(), this.finishedMaps(), this.finishedReduces(),
          this.getStatus(), historyLoc, this.getBlackListedTrackers(), this
              .isComplete(), this.numMapTasks, this.numReduceTasks,
              this.isHistoryFileCopied());
    }
    jobInfoImpl.setFinishTime(getJobFinishTime());
    jobInfoImpl.setLaunchTime(getJobLaunchTime());
    jobInfoImpl.setNumSlotsPerReduce(getJobNumSlotsPerReduce());
    jobInfoImpl.setNumSlotsPerMap(getJobNumSlotsPerMap());
    return jobInfoImpl;
  }

  private long JobInProgress.getJobFinishTime() {
    long finishTime = 0;
    if (this.isComplete()) {
      finishTime = this.getFinishTime();
    }
    return finishTime;
  }

  private long JobInProgress.getJobLaunchTime() {
    long LaunchTime = 0;
    if (this.isComplete()) {
      LaunchTime = this.getLaunchTime();
    }
    return LaunchTime;
  }

  private int JobInProgress.getJobNumSlotsPerReduce() {
    int numSlotsPerReduce = 0;
    if (this.isComplete()) {
      numSlotsPerReduce = this.getNumSlotsPerReduce();
    }
    return numSlotsPerReduce;
  }

  private int JobInProgress.getJobNumSlotsPerMap() {
    int numSlotsPerMap = 0;
    if (this.isComplete()) {
      numSlotsPerMap = this.getNumSlotsPerMap();
    }
    return numSlotsPerMap;
 }

  private String JobInProgress.getHistoryPath() {
    String historyLoc = "";
    if(this.isComplete()) {
      historyLoc = this.getHistoryFile();
    } else {
      String historyFileName = null;
      try {
        historyFileName  = JobHistory.JobInfo.getJobHistoryFileName(conf,
            jobId);
      } catch(IOException e) {
      }
      if(historyFileName != null) {
        historyLoc = JobHistory.JobInfo.getJobHistoryLogLocation(
            historyFileName).toString();
      }
    }
    return historyLoc;
  }

}


Improving binding for PluginParameterException report.

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

package org.apache.maven.errors;

import org.codehaus.plexus.logging.console.ConsoleLogger;
import org.codehaus.plexus.logging.Logger;
import org.apache.maven.project.path.PathTranslator;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.plugin.PluginConfigurationException;
import org.apache.maven.plugin.descriptor.Parameter;
import org.apache.maven.plugin.loader.PluginLoaderException;
import org.apache.maven.plugin.PluginExecutionException;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.lifecycle.model.MojoBinding;
import org.apache.maven.lifecycle.DefaultLifecycleExecutor;
import org.apache.maven.lifecycle.LifecycleException;
import org.apache.maven.lifecycle.LifecycleExecutionException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.plugin.DefaultPluginManager;
import org.apache.maven.plugin.PluginManager;
import org.apache.maven.plugin.PluginParameterExpressionEvaluator;
import org.apache.maven.plugin.PluginParameterException;
import org.apache.maven.plugin.Mojo;
import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.codehaus.plexus.configuration.PlexusConfiguration;

import java.util.List;

public privileged aspect LifecycleErrorReporterAspect
    extends AbstractCoreReporterAspect
{

    private pointcut le_executeGoalAndHandleFailures( MojoBinding binding ):
        execution( void DefaultLifecycleExecutor.executeGoalAndHandleFailures( MojoBinding, .. ) )
        && args( binding, .. );

    private pointcut pm_executeMojo( MavenProject project ):
        execution( void PluginManager+.executeMojo( MavenProject, .. ) )
        && args( project, .. );

    private pointcut within_pm_executeMojo( MavenProject project ):
        withincode( void PluginManager+.executeMojo( MavenProject, .. ) )
        && args( project, .. );

    before( MojoBinding binding, MavenProject project, LifecycleExecutionException err ):
        cflow( le_executeGoalAndHandleFailures( binding ) )
        && execution( LifecycleExecutionException.new( String, MavenProject ) )
        && args( .., project )
        && this( err )
    {
        getReporter().reportMissingPluginDescriptor( binding, project, err );
    }

    before( MojoBinding binding, MavenProject project, PluginLoaderException cause ):
        cflow( le_executeGoalAndHandleFailures( binding ) )
        && call( LifecycleExecutionException.new( String, MavenProject, PluginLoaderException ) )
        && args( *, project, cause )
    {
        getReporter().reportErrorLoadingPlugin( binding, project, cause );
    }

    before( MojoBinding binding, MavenProject project, MojoExecutionException cause ):
        cflow( le_executeGoalAndHandleFailures( binding ) )
        && cflow( pm_executeMojo( project ) )
        && handler( MojoExecutionException )
        && args( cause )
    {
        getReporter().reportMojoExecutionException( binding, project, cause );
    }

    PluginExecutionException around( MojoBinding binding, MavenProject project ):
        cflow( le_executeGoalAndHandleFailures( binding ) )
        && cflow( pm_executeMojo( project ) )
        && call( PluginExecutionException.new( .., String ) )
    {
        PluginExecutionException cause = proceed( binding, project );
        getReporter().reportInvalidPluginExecutionEnvironment( binding, project, cause );

        return cause;
    }

    before( MojoBinding binding, MavenProject project, ComponentLookupException cause ):
        cflow( le_executeGoalAndHandleFailures( binding ) )
        && cflow( pm_executeMojo( project ) )
        && withincode( Mojo DefaultPluginManager.getConfiguredMojo( .. ) )
        && handler( ComponentLookupException )
        && args( cause )
    {
        getReporter().reportMojoLookupError( binding, project, cause );
    }

    Parameter currentParameter;

    private pointcut paramGetName( Parameter parameter ):
        call( String Parameter.getName() )
        && target( parameter );

    private pointcut pm_validatePomConfig():
        execution( void DefaultPluginManager.validatePomConfiguration( .. ) );

    private pointcut within_pm_validatePomConfig():
        withincode( void DefaultPluginManager.validatePomConfiguration( .. ) );

    private pointcut pm_checkRequiredParameters():
        execution( void DefaultPluginManager.checkRequiredParameters( .. ) );

    private pointcut within_pm_checkRequiredParameters():
        withincode( void DefaultPluginManager.checkRequiredParameters( .. ) );

    before( Parameter parameter ):
        ( within_pm_validatePomConfig()
          || within_pm_checkRequiredParameters() )
        && paramGetName( parameter )
    {
        currentParameter = parameter;
    }

    after() returning:
        pm_validatePomConfig() ||
        pm_checkRequiredParameters()
    {
        currentParameter = null;
    }

    private pointcut pm_executeMojoWithSessionAndExec( MavenProject project, MojoExecution exec, MavenSession session, DefaultPluginManager manager ):
        execution( void DefaultPluginManager.executeMojo( MavenProject, MojoExecution, MavenSession ) )
        && args( project, exec, session )
        && this( manager );

    after( MojoBinding binding, MavenProject project, MojoExecution exec, MavenSession session, DefaultPluginManager manager ) throwing( PluginConfigurationException cause ):
        cflow( le_executeGoalAndHandleFailures( binding ) )
        && cflow( pm_executeMojoWithSessionAndExec( project, exec, session, manager ) )
        && pm_validatePomConfig()
    {
        PathTranslator translator = manager.pathTranslator;
        Logger logger = new ConsoleLogger( Logger.LEVEL_INFO, "error reporting" );
        getReporter().reportAttemptToOverrideUneditableMojoParameter( currentParameter, binding, project, session, exec, translator, logger, cause );
    }

    PluginParameterException around( MojoBinding binding, MavenProject project, List invalidParameters ):
        cflow( le_executeGoalAndHandleFailures( binding ) )
        && cflow( pm_executeMojo( project ) )
        && cflow( pm_checkRequiredParameters() )
        && call( PluginParameterException.new( .., List ) )
        && args( .., invalidParameters )
    {
        PluginParameterException err = proceed( binding, project, invalidParameters );

        getReporter().reportMissingRequiredMojoParameter( binding, project, invalidParameters, err );

        return err;
    }

    private pointcut ppee_evaluate( String expression ):
        execution( Object PluginParameterExpressionEvaluator.evaluate( String ) )
        && args( expression );

    private pointcut within_ppee_evaluate( String expression ):
        withincode( Object PluginParameterExpressionEvaluator.evaluate( String ) )
        && args( expression );

    before( MojoBinding binding, MavenProject project, String expression, ExpressionEvaluationException err ):
        cflow( le_executeGoalAndHandleFailures( binding ) )
        && cflow( pm_executeMojo( project ) )
        && cflow( pm_checkRequiredParameters() )
        && cflow( ppee_evaluate( expression ) )
        && execution( ExpressionEvaluationException.new( String ) )
        && this( err )
    {
        getReporter().reportUseOfBannedMojoParameter( currentParameter,
                                                      binding,
                                                      project,
                                                      expression,
                                                      (String) PluginParameterExpressionEvaluator.BANNED_EXPRESSIONS.get( expression ),
                                                      err );
    }

    before( MojoBinding binding, MavenProject project, String expression, Exception cause ):
        cflow( le_executeGoalAndHandleFailures( binding ) )
        && cflow( pm_executeMojo( project ) )
        && cflow( pm_checkRequiredParameters() )
        && cflow( ppee_evaluate( expression ) )
        && within( PluginParameterExpressionEvaluator )
        && handler( Exception )
        && args( cause )
    {
        getReporter().reportReflectionErrorWhileEvaluatingMojoParameter( currentParameter,
                                                      binding,
                                                      project,
                                                      expression,
                                                      cause );
    }

    after( MojoBinding binding, MavenProject project, PlexusConfiguration config ) throwing( PluginConfigurationException cause ):
        cflow( le_executeGoalAndHandleFailures( binding ) )
        && cflow( pm_executeMojo( project ) )
        && execution( void DefaultPluginManager.populatePluginFields( *, *, PlexusConfiguration, .. ) )
        && args( *, *, config, .. )
    {
        getReporter().reportErrorApplyingMojoConfiguration( binding, project, config, cause );
    }

    private pointcut pm_resolveTransitiveDependencies( MavenProject project, String scope ):
        execution( void DefaultPluginManager.resolveTransitiveDependencies( *, *, String, *, MavenProject ) )
        && args( *, *, scope, *, project );

    after( MavenProject project, String scope ) throwing( ArtifactNotFoundException cause ):
        pm_resolveTransitiveDependencies( project, scope )
    {
        getReporter().reportProjectDependenciesNotFound( project, scope, cause );
    }

    after( MavenProject project, String scope ) throwing( ArtifactResolutionException cause ):
        pm_resolveTransitiveDependencies( project, scope )
    {
        getReporter().reportProjectDependenciesUnresolvable( project, scope, cause );
    }

    private pointcut within_pm_downloadDependencies( MavenProject project ):
        withincode( void DefaultPluginManager.downloadDependencies( MavenProject, .. ) )
        && args( project, .. );

    private pointcut ar_resolve( Artifact artifact ):
        call( * ArtifactResolver+.resolve( Artifact, ..) )
        && args( artifact, .. );

    after( MavenProject project, Artifact artifact ) throwing( ArtifactNotFoundException cause ):
        within_pm_downloadDependencies( project )
        && ar_resolve( artifact )
    {
        getReporter().reportProjectDependencyArtifactNotFound( project, artifact, cause );
    }

    after( MavenProject project, Artifact artifact ) throwing( ArtifactResolutionException cause ):
        within_pm_downloadDependencies( project )
        && ar_resolve( artifact )
    {
        getReporter().reportProjectDependencyArtifactUnresolvable( project, artifact, cause );
    }

    private pointcut le_getLifecycleBindings( List tasks, MavenProject configuringProject, String targetDescription ):
        execution( List DefaultLifecycleExecutor.getLifecycleBindings( List, MavenProject, *, String ) )
        && args( tasks, configuringProject, *, targetDescription );

    before( List tasks, MavenProject configuringProject, String targetDescription, LifecycleException cause ):
        cflow( le_getLifecycleBindings( tasks, configuringProject, targetDescription ) )
        && call( LifecycleExecutionException.new( .., LifecycleException ) )
        && args( .., cause )
    {
        getReporter().reportErrorFormulatingBuildPlan( tasks, configuringProject, targetDescription, cause );
    }

}

package org.apache.maven.errors;

import org.codehaus.plexus.logging.console.ConsoleLogger;
import org.codehaus.plexus.logging.Logger;
import org.apache.maven.project.path.PathTranslator;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.plugin.PluginConfigurationException;
import org.apache.maven.plugin.descriptor.Parameter;
import org.apache.maven.plugin.loader.PluginLoaderException;
import org.apache.maven.plugin.PluginExecutionException;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.lifecycle.model.MojoBinding;
import org.apache.maven.lifecycle.DefaultLifecycleExecutor;
import org.apache.maven.lifecycle.LifecycleException;
import org.apache.maven.lifecycle.LifecycleExecutionException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.plugin.DefaultPluginManager;
import org.apache.maven.plugin.PluginManager;
import org.apache.maven.plugin.PluginParameterExpressionEvaluator;
import org.apache.maven.plugin.PluginParameterException;
import org.apache.maven.plugin.Mojo;
import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.codehaus.plexus.configuration.PlexusConfiguration;

import java.util.List;

public privileged aspect LifecycleErrorReporterAspect
    extends AbstractCoreReporterAspect
{

    private pointcut le_executeGoalAndHandleFailures( MojoBinding binding ):
        execution( void DefaultLifecycleExecutor.executeGoalAndHandleFailures( MojoBinding, .. ) )
        && args( binding, .. );

    private pointcut pm_executeMojo( MavenProject project ):
        execution( void PluginManager+.executeMojo( MavenProject, .. ) )
        && args( project, .. );

    private pointcut within_pm_executeMojo( MavenProject project ):
        withincode( void PluginManager+.executeMojo( MavenProject, .. ) )
        && args( project, .. );

    before( MojoBinding binding, MavenProject project, LifecycleExecutionException err ):
        cflow( le_executeGoalAndHandleFailures( binding ) )
        && execution( LifecycleExecutionException.new( String, MavenProject ) )
        && args( .., project )
        && this( err )
    {
        getReporter().reportMissingPluginDescriptor( binding, project, err );
    }

    before( MojoBinding binding, MavenProject project, PluginLoaderException cause ):
        cflow( le_executeGoalAndHandleFailures( binding ) )
        && call( LifecycleExecutionException.new( String, MavenProject, PluginLoaderException ) )
        && args( *, project, cause )
    {
        getReporter().reportErrorLoadingPlugin( binding, project, cause );
    }

    before( MojoBinding binding, MavenProject project, MojoExecutionException cause ):
        cflow( le_executeGoalAndHandleFailures( binding ) )
        && cflow( pm_executeMojo( project ) )
        && handler( MojoExecutionException )
        && args( cause )
    {
        getReporter().reportMojoExecutionException( binding, project, cause );
    }

    PluginExecutionException around( MojoBinding binding, MavenProject project ):
        cflow( le_executeGoalAndHandleFailures( binding ) )
        && cflow( pm_executeMojo( project ) )
        && call( PluginExecutionException.new( .., String ) )
    {
        PluginExecutionException cause = proceed( binding, project );
        getReporter().reportInvalidPluginExecutionEnvironment( binding, project, cause );

        return cause;
    }

    before( MojoBinding binding, MavenProject project, ComponentLookupException cause ):
        cflow( le_executeGoalAndHandleFailures( binding ) )
        && cflow( pm_executeMojo( project ) )
        && withincode( Mojo DefaultPluginManager.getConfiguredMojo( .. ) )
        && handler( ComponentLookupException )
        && args( cause )
    {
        getReporter().reportMojoLookupError( binding, project, cause );
    }

    Parameter currentParameter;

    private pointcut paramGetName( Parameter parameter ):
        call( String Parameter.getName() )
        && target( parameter );

    private pointcut pm_validatePomConfig():
        execution( void DefaultPluginManager.validatePomConfiguration( .. ) );

    private pointcut within_pm_validatePomConfig():
        withincode( void DefaultPluginManager.validatePomConfiguration( .. ) );

    private pointcut pm_checkRequiredParameters():
        execution( void DefaultPluginManager.checkRequiredParameters( .. ) );

    private pointcut within_pm_checkRequiredParameters():
        withincode( void DefaultPluginManager.checkRequiredParameters( .. ) );

    before( Parameter parameter ):
        ( within_pm_validatePomConfig()
          || within_pm_checkRequiredParameters() )
        && paramGetName( parameter )
    {
        currentParameter = parameter;
    }

    after() returning:
        pm_validatePomConfig() ||
        pm_checkRequiredParameters()
    {
        currentParameter = null;
    }

    private pointcut pm_executeMojoWithSessionAndExec( MavenProject project, MojoExecution exec, MavenSession session, DefaultPluginManager manager ):
        execution( void DefaultPluginManager.executeMojo( MavenProject, MojoExecution, MavenSession ) )
        && args( project, exec, session )
        && this( manager );

    after( MojoBinding binding, MavenProject project, MojoExecution exec, MavenSession session, DefaultPluginManager manager ) throwing( PluginConfigurationException cause ):
        cflow( le_executeGoalAndHandleFailures( binding ) )
        && cflow( pm_executeMojoWithSessionAndExec( project, exec, session, manager ) )
        && pm_validatePomConfig()
    {
        PathTranslator translator = manager.pathTranslator;
        Logger logger = new ConsoleLogger( Logger.LEVEL_INFO, "error reporting" );
        getReporter().reportAttemptToOverrideUneditableMojoParameter( currentParameter, binding, project, session, exec, translator, logger, cause );
    }

    before( MojoBinding binding, MavenProject project, List invalidParameters, PluginParameterException err ):
        cflow( le_executeGoalAndHandleFailures( binding ) )
        && cflow( pm_executeMojo( project ) )
        && cflow( pm_checkRequiredParameters() )
        && execution( PluginParameterException.new( .., List ) )
        && args( .., invalidParameters )
        && this( err )
    {
        getReporter().reportMissingRequiredMojoParameter( binding, project, invalidParameters, err );
    }

    private pointcut ppee_evaluate( String expression ):
        execution( Object PluginParameterExpressionEvaluator.evaluate( String ) )
        && args( expression );

    private pointcut within_ppee_evaluate( String expression ):
        withincode( Object PluginParameterExpressionEvaluator.evaluate( String ) )
        && args( expression );

    before( MojoBinding binding, MavenProject project, String expression, ExpressionEvaluationException err ):
        cflow( le_executeGoalAndHandleFailures( binding ) )
        && cflow( pm_executeMojo( project ) )
        && cflow( pm_checkRequiredParameters() )
        && cflow( ppee_evaluate( expression ) )
        && execution( ExpressionEvaluationException.new( String ) )
        && this( err )
    {
        getReporter().reportUseOfBannedMojoParameter( currentParameter,
                                                      binding,
                                                      project,
                                                      expression,
                                                      (String) PluginParameterExpressionEvaluator.BANNED_EXPRESSIONS.get( expression ),
                                                      err );
    }

    before( MojoBinding binding, MavenProject project, String expression, Exception cause ):
        cflow( le_executeGoalAndHandleFailures( binding ) )
        && cflow( pm_executeMojo( project ) )
        && cflow( pm_checkRequiredParameters() )
        && cflow( ppee_evaluate( expression ) )
        && within( PluginParameterExpressionEvaluator )
        && handler( Exception )
        && args( cause )
    {
        getReporter().reportReflectionErrorWhileEvaluatingMojoParameter( currentParameter,
                                                      binding,
                                                      project,
                                                      expression,
                                                      cause );
    }

    after( MojoBinding binding, MavenProject project, PlexusConfiguration config ) throwing( PluginConfigurationException cause ):
        cflow( le_executeGoalAndHandleFailures( binding ) )
        && cflow( pm_executeMojo( project ) )
        && execution( void DefaultPluginManager.populatePluginFields( *, *, PlexusConfiguration, .. ) )
        && args( *, *, config, .. )
    {
        getReporter().reportErrorApplyingMojoConfiguration( binding, project, config, cause );
    }

    private pointcut pm_resolveTransitiveDependencies( MavenProject project, String scope ):
        execution( void DefaultPluginManager.resolveTransitiveDependencies( *, *, String, *, MavenProject ) )
        && args( *, *, scope, *, project );

    after( MavenProject project, String scope ) throwing( ArtifactNotFoundException cause ):
        pm_resolveTransitiveDependencies( project, scope )
    {
        getReporter().reportProjectDependenciesNotFound( project, scope, cause );
    }

    after( MavenProject project, String scope ) throwing( ArtifactResolutionException cause ):
        pm_resolveTransitiveDependencies( project, scope )
    {
        getReporter().reportProjectDependenciesUnresolvable( project, scope, cause );
    }

    private pointcut within_pm_downloadDependencies( MavenProject project ):
        withincode( void DefaultPluginManager.downloadDependencies( MavenProject, .. ) )
        && args( project, .. );

    private pointcut ar_resolve( Artifact artifact ):
        call( * ArtifactResolver+.resolve( Artifact, ..) )
        && args( artifact, .. );

    after( MavenProject project, Artifact artifact ) throwing( ArtifactNotFoundException cause ):
        within_pm_downloadDependencies( project )
        && ar_resolve( artifact )
    {
        getReporter().reportProjectDependencyArtifactNotFound( project, artifact, cause );
    }

    after( MavenProject project, Artifact artifact ) throwing( ArtifactResolutionException cause ):
        within_pm_downloadDependencies( project )
        && ar_resolve( artifact )
    {
        getReporter().reportProjectDependencyArtifactUnresolvable( project, artifact, cause );
    }

    private pointcut le_getLifecycleBindings( List tasks, MavenProject configuringProject, String targetDescription ):
        execution( List DefaultLifecycleExecutor.getLifecycleBindings( List, MavenProject, *, String ) )
        && args( tasks, configuringProject, *, targetDescription );

    before( List tasks, MavenProject configuringProject, String targetDescription, LifecycleException cause ):
        cflow( le_getLifecycleBindings( tasks, configuringProject, targetDescription ) )
        && call( LifecycleExecutionException.new( .., LifecycleException ) )
        && args( .., cause )
    {
        getReporter().reportErrorFormulatingBuildPlan( tasks, configuringProject, targetDescription, cause );
    }

}


AbstractUserTransactionAspect now logs exceptions during rollback handling and rethrows the original one

/**
 * palava - a java-php-bridge
 * Copyright (C) 2007-2010  CosmoCode GmbH
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA  02110-1301, USA.
 */

package de.cosmocode.palava.jta;

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

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

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

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

public abstract aspect AbstractUserTransactionAspect extends AbstractPalavaAspect issingleton() {

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

    private Provider<UserTransaction> provider;

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

    protected abstract pointcut transactional();

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

        final boolean local;

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

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

        final Object returnValue;

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

        final int status;

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

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

        return returnValue;
    }

}

/**
 * palava - a java-php-bridge
 * Copyright (C) 2007-2010  CosmoCode GmbH
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA  02110-1301, USA.
 */

package de.cosmocode.palava.jta;

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

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

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

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

public abstract aspect AbstractUserTransactionAspect extends AbstractPalavaAspect issingleton() {

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

    private Provider<UserTransaction> provider;

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

    protected abstract pointcut transactional();

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

        final boolean local;

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

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

        final Object returnValue;

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

        final int status;

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

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

        return returnValue;
    }

}


XWIKI-8559: Use SLF4J to log test messages and use the Logback binding * Fix log usage.

/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package com.xpn.xwiki.plugin.skinx;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Add a backward compatibility layer to the {@link com.xpn.xwiki.plugin.skinx.SkinFileExtensionPluginApi} class.
 *
 * @version $Id$
 */
public aspect SkinFileExtensionPluginApiCompatibilityAspect
{
    /**
     * Compatibility mapping that associates a deprecated resource file to its new relative path
     */
    private static Map<String, String> compatibilityMap = new HashMap<String, String>();

    static {
        // fullScreen script has been moved and renamed in XWiki 2.6RC2 / 2.7M1 See XWIKI-5659
        compatibilityMap.put("js/xwiki/editors/fullScreenEdit.js", "uicomponents/widgets/fullScreen.js");
        compatibilityMap.put("js/xwiki/editors/fullScreenEdit.css", "uicomponents/widgets/fullScreen.css");
        // suggest script has been moved and renamed in XWiki 3.1M3 See XWIKI-6043
        compatibilityMap.put("js/xwiki/suggest/ajaxSuggest.js", "uicomponents/suggest/suggest.js");
        compatibilityMap.put("js/xwiki/suggest/ajaxSuggest.css", "uicomponents/suggest/suggest.css");
    }

    /**
     * Pointcut that catches all skin file extensions "use" join points.
     */
    private pointcut sfxUse(String path) : execution(void SkinFileExtensionPluginApi.use(..)) && args(path, ..);

    /**
     * Advice around skin file extensions "use" join points, that checks if the requested file is declared in the map of
     * deprecated extensions paths. If it is, it logs a warning message in the console, and calls the skin extension
     * plugin with the new path, declared in the map.
     */
    void around(String path): sfxUse(path)
    {
        if (compatibilityMap.containsKey(path)) {

            Logger logger = LoggerFactory.getLogger(thisJoinPoint.getSignature().getDeclaringType());
            logger.warn("Skin file extension with path [{}] is deprecated. Please use [{}] instead.", path,
                compatibilityMap.get(path));

            proceed(compatibilityMap.get(path));
        }

        proceed(path);
    }
}

/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package com.xpn.xwiki.plugin.skinx;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

/**
 * Add a backward compatibility layer to the {@link com.xpn.xwiki.plugin.skinx.SkinFileExtensionPluginApi} class.
 *
 * @version $Id$
 */
public aspect SkinFileExtensionPluginApiCompatibilityAspect
{
    /**
     * Compatibility mapping that associates a deprecated resource file to its new relative path
     */
    private static Map<String, String> compatibilityMap = new HashMap<String, String>();

    static {
        // fullScreen script has been moved and renamed in XWiki 2.6RC2 / 2.7M1 See XWIKI-5659
        compatibilityMap.put("js/xwiki/editors/fullScreenEdit.js", "uicomponents/widgets/fullScreen.js");
        compatibilityMap.put("js/xwiki/editors/fullScreenEdit.css", "uicomponents/widgets/fullScreen.css");
        // suggest script has been moved and renamed in XWiki 3.1M3 See XWIKI-6043
        compatibilityMap.put("js/xwiki/suggest/ajaxSuggest.js", "uicomponents/suggest/suggest.js");
        compatibilityMap.put("js/xwiki/suggest/ajaxSuggest.css", "uicomponents/suggest/suggest.css");
    }

    /**
     * Pointcut that catches all skin file extensions "use" join points.
     */
    private pointcut sfxUse(String path) : execution(void SkinFileExtensionPluginApi.use(..)) && args(path, ..);

    /**
     * Advice around skin file extensions "use" join points, that checks if the requested file is declared in the map of
     * deprecated extensions paths. If it is, it logs a warning message in the console, and calls the skin extension
     * plugin with the new path, declared in the map.
     */
    void around(String path): sfxUse(path)
    {
        if (compatibilityMap.containsKey(path)) {

            Logger logger = Logger.getLogger(thisJoinPoint.getSignature().getDeclaringType());
            logger.warn(MessageFormat.format(
                "Skin file extension with path [{0}] is deprecated. Please use [{1}] instead.", new Object[] {path,
                    compatibilityMap.get(path)}));

            proceed(compatibilityMap.get(path));
        }

        proceed(path);
    }
}


Disable the pluginRepository deprecation message until the first release of 2.1 is imminent, to avoid confusion when using IDEs that use 2.1 snapshots (where the CLI still uses 2.0.x).

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

package org.apache.maven.project.aspect.compat;

import org.apache.maven.model.Model;
import org.apache.maven.project.build.model.ModelLineage;
import org.apache.maven.project.build.model.ModelLineageIterator;
import org.apache.maven.project.build.model.ModelLineageBuilder;
import org.apache.maven.project.DefaultMavenProjectBuilder;
import org.apache.maven.project.artifact.MavenMetadataSource;
import org.apache.maven.profiles.build.DefaultProfileAdvisor;
import org.apache.maven.model.Profile;
import org.apache.maven.profiles.ProfileManager;

import java.util.Iterator;
import java.util.List;
import java.util.HashSet;
import java.util.Set;
import java.util.Map;

public privileged aspect Maven20xProjectCompatAspect
{

    // FIXME: Re-enable this when we're closer to a 2.1 release.
//    private pointcut reactorProjectBuilds():
//        cflow( execution( * DefaultMavenProjectBuilder.buildFromSourceFileInternal( .. ) ) )
//        && !cflow( execution( * MavenMetadataSource.*( .. ) ) );
//
//    private pointcut lineageBuildResumed( DefaultMavenProjectBuilder projectBuilder, ModelLineage lineage ):
//        call( * ModelLineageBuilder.resumeBuildingModelLineage( ModelLineage, .. ) )
//        && this( projectBuilder )
//        && args( lineage, .. );
//
//    after( DefaultMavenProjectBuilder projectBuilder, ModelLineage lineage ):
//        reactorProjectBuilds()
//        && lineageBuildResumed( projectBuilder, lineage )
//    {
//        for ( ModelLineageIterator it = lineage.lineageIterator(); it.hasNext(); )
//        {
//            Model model = (Model) it.next();
//            List pluginRepos = model.getPluginRepositories();
//
//            if ( pluginRepos != null && !pluginRepos.isEmpty() )
//            {
//                StringBuffer message = new StringBuffer();
//                message.append( "The <pluginRepositories/> section of the POM has been deprecated. Please update your POM (" );
//                message.append( model.getId() );
//                message.append( ")." );
//
//                projectBuilder.logger.warn( message.toString() );
//            }
//        }
//    }
//
//    private pointcut externalProfilesApplied( DefaultProfileAdvisor advisor, ProfileManager profileManager ):
//        execution( * DefaultProfileAdvisor.applyActivatedExternalProfiles( .., ProfileManager+ ) )
//        && this( advisor )
//        && args( .., profileManager );
//
//
//    private boolean settingsProfilesChecked = false;
//
//    before( DefaultProfileAdvisor advisor, ProfileManager profileManager ):
//        reactorProjectBuilds()
//        && externalProfilesApplied( advisor, profileManager )
//    {
//        if ( profileManager == null )
//        {
//            return;
//        }
//
//        Map profilesById = profileManager.getProfilesById();
//        Set invalidProfiles = new HashSet();
//
//        boolean settingsProfilesEncountered = false;
//        for ( Iterator it = profilesById.values().iterator(); it.hasNext(); )
//        {
//            Profile profile = (Profile) it.next();
//
//            if ( "settings.xml".equals( profile.getSource() ) )
//            {
//                settingsProfilesEncountered = true;
//
//                if ( settingsProfilesChecked )
//                {
//                    continue;
//                }
//            }
//
//            List pluginRepos = profile.getPluginRepositories();
//            if ( pluginRepos != null && !pluginRepos.isEmpty() )
//            {
//                invalidProfiles.add( profile );
//            }
//        }
//
//        if ( !invalidProfiles.isEmpty() )
//        {
//            StringBuffer message = new StringBuffer();
//            message.append( "The <pluginRepositories/> section of the POM has been deprecated. Please update the following profiles:\n" );
//
//            for ( Iterator it = invalidProfiles.iterator(); it.hasNext(); )
//            {
//                Profile profile = (Profile) it.next();
//                message.append( "\n- " ).append( profile.getId() ).append( " (source: " ).append( profile.getSource() ).append( ")" );
//            }
//
//            message.append( "\n" );
//
//            advisor.logger.warn( message.toString() );
//        }
//
//        settingsProfilesChecked = settingsProfilesChecked || settingsProfilesEncountered;
//    }

}

package org.apache.maven.project.aspect.compat;

import org.apache.maven.model.Model;
import org.apache.maven.project.build.model.ModelLineage;
import org.apache.maven.project.build.model.ModelLineageIterator;
import org.apache.maven.project.build.model.ModelLineageBuilder;
import org.apache.maven.project.DefaultMavenProjectBuilder;
import org.apache.maven.project.artifact.MavenMetadataSource;
import org.apache.maven.profiles.build.DefaultProfileAdvisor;
import org.apache.maven.model.Profile;
import org.apache.maven.profiles.ProfileManager;

import java.util.Iterator;
import java.util.List;
import java.util.HashSet;
import java.util.Set;
import java.util.Map;

public privileged aspect Maven20xProjectCompatAspect
{

    private pointcut reactorProjectBuilds():
        cflow( execution( * DefaultMavenProjectBuilder.buildFromSourceFileInternal( .. ) ) )
        && !cflow( execution( * MavenMetadataSource.*( .. ) ) );

    private pointcut lineageBuildResumed( DefaultMavenProjectBuilder projectBuilder, ModelLineage lineage ):
        call( * ModelLineageBuilder.resumeBuildingModelLineage( ModelLineage, .. ) )
        && this( projectBuilder )
        && args( lineage, .. );

    after( DefaultMavenProjectBuilder projectBuilder, ModelLineage lineage ):
        reactorProjectBuilds()
        && lineageBuildResumed( projectBuilder, lineage )
    {
        for ( ModelLineageIterator it = lineage.lineageIterator(); it.hasNext(); )
        {
            Model model = (Model) it.next();
            List pluginRepos = model.getPluginRepositories();

            if ( pluginRepos != null && !pluginRepos.isEmpty() )
            {
                StringBuffer message = new StringBuffer();
                message.append( "The <pluginRepositories/> section of the POM has been deprecated. Please update your POM (" );
                message.append( model.getId() );
                message.append( ")." );

                projectBuilder.logger.warn( message.toString() );
            }
        }
    }

    private pointcut externalProfilesApplied( DefaultProfileAdvisor advisor, ProfileManager profileManager ):
        execution( * DefaultProfileAdvisor.applyActivatedExternalProfiles( .., ProfileManager+ ) )
        && this( advisor )
        && args( .., profileManager );

    private boolean settingsProfilesChecked = false;

    before( DefaultProfileAdvisor advisor, ProfileManager profileManager ):
        reactorProjectBuilds()
        && externalProfilesApplied( advisor, profileManager )
    {
        if ( profileManager == null )
        {
            return;
        }

        Map profilesById = profileManager.getProfilesById();
        Set invalidProfiles = new HashSet();

        boolean settingsProfilesEncountered = false;
        for ( Iterator it = profilesById.values().iterator(); it.hasNext(); )
        {
            Profile profile = (Profile) it.next();

            if ( "settings.xml".equals( profile.getSource() ) )
            {
                settingsProfilesEncountered = true;

                if ( settingsProfilesChecked )
                {
                    continue;
                }
            }

            List pluginRepos = profile.getPluginRepositories();
            if ( pluginRepos != null && !pluginRepos.isEmpty() )
            {
                invalidProfiles.add( profile );
            }
        }

        if ( !invalidProfiles.isEmpty() )
        {
            StringBuffer message = new StringBuffer();
            message.append( "The <pluginRepositories/> section of the POM has been deprecated. Please update the following profiles:\n" );

            for ( Iterator it = invalidProfiles.iterator(); it.hasNext(); )
            {
                Profile profile = (Profile) it.next();
                message.append( "\n- " ).append( profile.getId() ).append( " (source: " ).append( profile.getSource() ).append( ")" );
            }

            message.append( "\n" );

            advisor.logger.warn( message.toString() );
        }

        settingsProfilesChecked = settingsProfilesChecked || settingsProfilesEncountered;
    }

}


Fixed #2621.

Fixed #2621.

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

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

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

import java.util.Locale;
import java.util.Map;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.AbstractVariableDeclaration;
import org.eclipse.jdt.internal.compiler.ast.AnnotationMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.Argument;
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration;
import org.eclipse.jdt.internal.compiler.ast.Expression;
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.QualifiedAllocationExpression;
import org.eclipse.jdt.internal.compiler.ast.Statement;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeParameter;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.eclipse.jdt.internal.compiler.env.AccessRestriction;
import org.eclipse.jdt.internal.compiler.env.IBinaryType;
import org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.eclipse.jdt.internal.compiler.env.ISourceType;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.impl.ITypeRequestor;
import org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
import org.eclipse.jdt.internal.compiler.lookup.PackageBinding;
import org.eclipse.jdt.internal.compiler.parser.SourceTypeConverter;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
import org.eclipse.jdt.internal.core.DefaultWorkingCopyOwner;
import org.eclipse.jdt.internal.core.JavaProject;
import org.eclipse.jdt.internal.core.SourceAnnotationMethodInfo;
import org.eclipse.jdt.internal.core.SourceMethod;
import org.eclipse.jdt.internal.core.SourceMethodElementInfo;
import org.eclipse.jdt.internal.core.SourceType;
import org.eclipse.jdt.internal.core.SourceTypeElementInfo;

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

@SuppressWarnings("restriction")
public privileged aspect DOMAspect {
  pointcut internalCreateAST(ASTParser parser, IProgressMonitor monitor) :
    execution(ASTNode ASTParser.internalCreateAST(IProgressMonitor)) &&
    args(monitor) &&
    target(parser);

  pointcut convert(SourceTypeConverter stc, SourceMethod methodHandle, SourceMethodElementInfo methodInfo, CompilationResult compilationResult) :
    execution(AbstractMethodDeclaration SourceTypeConverter.convert(SourceMethod, SourceMethodElementInfo, CompilationResult)) &&
    args(methodHandle, methodInfo, compilationResult) &&
    target(stc);

  ASTNode around(ASTParser parser, IProgressMonitor monitor) :
    internalCreateAST(parser, monitor) {
    try {
      if (!(parser.typeRoot instanceof IScalaCompilationUnit))
        return proceed(parser, monitor);

      ICompilationUnit cu = (ICompilationUnit)parser.typeRoot;
      org.eclipse.jdt.internal.compiler.env.ICompilationUnit sourceUnit = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit)cu;

      IType[] topLevelTypes = cu.getTypes();
      int length = topLevelTypes.length;
      if (length == 0)
        throw new IllegalStateException();

      SourceTypeElementInfo[] topLevelInfos = new SourceTypeElementInfo[length];
      for (int i = 0; i < length; i++) {
        topLevelInfos[i] = (SourceTypeElementInfo) ((SourceType)topLevelTypes[i]).getElementInfo();
      }
      char[] fileName = ((ISourceType)topLevelInfos[0]).getFileName();

      CompilationResult result = new CompilationResult(fileName, 1, 1, 100);

      JavaProject javaProject = (JavaProject)cu.getJavaProject();
      Map compilerOptions0 = javaProject.getOptions(true);
      CompilerOptions compilerOptions = new CompilerOptions(compilerOptions0);
      compilerOptions.storeAnnotations = true;

      ProblemReporter problemReporter =
        new ProblemReporter(
          DefaultErrorHandlingPolicies.proceedWithAllProblems(),
          compilerOptions,
          new DefaultProblemFactory(Locale.getDefault()));

      int flags = SourceTypeConverter.FIELD_AND_METHOD | SourceTypeConverter.MEMBER_TYPE;

      CompilationUnitDeclaration unit =
        SourceTypeConverter.buildCompilationUnit(topLevelInfos, flags, problemReporter, result);

      INameEnvironment ne = javaProject.newSearchableNameEnvironment(DefaultWorkingCopyOwner.PRIMARY);
      final LookupEnvironment le = new LookupEnvironment(null, compilerOptions, problemReporter, ne);
      ITypeRequestor typeRequestor = new ITypeRequestor() {
        public void accept(IBinaryType binaryType, PackageBinding packageBinding, AccessRestriction accessRestriction) {
          le.createBinaryTypeFrom(binaryType, packageBinding, accessRestriction);
        }
        public void accept(org.eclipse.jdt.internal.compiler.env.ICompilationUnit unit, AccessRestriction accessRestriction) {}
        public void accept(ISourceType[] sourceType, PackageBinding packageBinding, AccessRestriction accessRestriction) {}
      };
      le.typeRequestor = typeRequestor;

      le.buildTypeBindings(unit, null);
      le.completeTypeBindings();
      fixTypes(unit.types);

      AST ast = AST.newAST(AST.JLS3);
      ast.setFlag(AST.RESOLVED_BINDINGS);
      ast.setDefaultNodeFlag(ASTNode.ORIGINAL);

      org.eclipse.jdt.core.dom.ASTConverter converter =
        new org.eclipse.jdt.core.dom.ASTConverter(compilerOptions0, true, monitor);

      org.eclipse.jdt.core.dom.BindingResolver resolver =
        new org.eclipse.jdt.core.dom.DefaultBindingResolver(
          unit.scope,
          DefaultWorkingCopyOwner.PRIMARY,
          new org.eclipse.jdt.core.dom.DefaultBindingResolver.BindingTables(),
          true);
      ast.setBindingResolver(resolver);
      converter.setAST(ast);

      ASTNode node = converter.convert(unit, sourceUnit.getContents());
      return node;
    } catch (JavaModelException ex) {
      throw new IllegalArgumentException(ex);
    }
  }

  private void fixTypes(TypeDeclaration[] types) {
    for(int i = 0, iLimit = types.length; i < iLimit ; ++i) {
      TypeDeclaration tpe = types[i];
      tpe.binding.getAnnotationTagBits();
      tpe.scope.buildFields();
      tpe.scope.buildMethods();
      fixFields(tpe.fields);
      fixMethods(tpe.methods);
      fixTypes(tpe.memberTypes);
    }
  }

  private void fixMethods(AbstractMethodDeclaration[] methods) {
    if (methods == null)
      return;

    for(int i = 0, iLimit = methods.length; i < iLimit; ++i) {
      AbstractMethodDeclaration m = methods[i];
      m.bodyStart = m.declarationSourceStart;
      m.bodyEnd = m.declarationSourceEnd;
      m.binding.getAnnotationTagBits();
    }
  }

  private void fixFields(AbstractVariableDeclaration[] fields) {
    if (fields == null)
      return;

    for(int i = 0, iLimit = fields.length; i < iLimit; ++i) {
      AbstractVariableDeclaration f = fields[i];
      f.declarationEnd = f.declarationSourceEnd;
    }
  }

  AbstractMethodDeclaration around(SourceTypeConverter stc, SourceMethod methodHandle, SourceMethodElementInfo methodInfo, CompilationResult compilationResult) throws JavaModelException :
    convert(stc, methodHandle, methodInfo, compilationResult) {
    AbstractMethodDeclaration method;

    /* only source positions available */
    int start = methodInfo.getNameSourceStart();
    int end = methodInfo.getNameSourceEnd();

    // convert 1.5 specific constructs only if compliance is 1.5 or above
    TypeParameter[] typeParams = null;
    if (stc.has1_5Compliance) {
      /* convert type parameters */
      char[][] typeParameterNames = methodInfo.getTypeParameterNames();
      if (typeParameterNames != null) {
        int parameterCount = typeParameterNames.length;
        if (parameterCount > 0) { // method's type parameters must be null if no type parameter
          char[][][] typeParameterBounds = methodInfo.getTypeParameterBounds();
          typeParams = new TypeParameter[parameterCount];
          for (int i = 0; i < parameterCount; i++) {
            typeParams[i] = stc.createTypeParameter(typeParameterNames[i], typeParameterBounds[i], start, end);
          }
        }
      }
    }

    int modifiers = methodInfo.getModifiers();
    if (methodInfo.isConstructor()) {
      ConstructorDeclaration decl = new ConstructorDeclaration(compilationResult);
      decl.bits &= ~org.eclipse.jdt.internal.compiler.ast.ASTNode.IsDefaultConstructor;
      method = decl;
      decl.typeParameters = typeParams;
    } else {
      MethodDeclaration decl;
      if (methodInfo.isAnnotationMethod()) {
        AnnotationMethodDeclaration annotationMethodDeclaration = new AnnotationMethodDeclaration(compilationResult);

        /* conversion of default value */
        SourceAnnotationMethodInfo annotationMethodInfo = (SourceAnnotationMethodInfo) methodInfo;
        boolean hasDefaultValue = annotationMethodInfo.defaultValueStart != -1 || annotationMethodInfo.defaultValueEnd != -1;
        if ((stc.flags & SourceTypeConverter.FIELD_INITIALIZATION) != 0) {
          if (hasDefaultValue) {
            char[] defaultValueSource = CharOperation.subarray(stc.getSource(), annotationMethodInfo.defaultValueStart, annotationMethodInfo.defaultValueEnd+1);
            if (defaultValueSource != null) {
                Expression expression =  stc.parseMemberValue(defaultValueSource);
                if (expression != null) {
                  annotationMethodDeclaration.defaultValue = expression;
                }
            } else {
              // could not retrieve the default value
              hasDefaultValue = false;
            }
          }
        }
        if (hasDefaultValue)
          modifiers |= ClassFileConstants.AccAnnotationDefault;
        decl = annotationMethodDeclaration;
      } else {
        decl = new MethodDeclaration(compilationResult);
      }

      // convert return type
      decl.returnType = stc.createTypeReference(methodInfo.getReturnTypeName(), start, end);

      // type parameters
      decl.typeParameters = typeParams;

      method = decl;
    }
    method.selector = methodHandle.getElementName().toCharArray();
    boolean isVarargs = (modifiers & ClassFileConstants.AccVarargs) != 0;
    method.modifiers = modifiers & ~ClassFileConstants.AccVarargs;
    method.sourceStart = start;
    method.sourceEnd = end;
    method.declarationSourceStart = methodInfo.getDeclarationSourceStart();
    method.declarationSourceEnd = methodInfo.getDeclarationSourceEnd();

    // convert 1.5 specific constructs only if compliance is 1.5 or above
    if (stc.has1_5Compliance) {
      /* convert annotations */
      method.annotations = stc.convertAnnotations(methodHandle);
    }

    /* convert arguments */
    String[] argumentTypeSignatures = methodHandle.getParameterTypes();
    char[][] argumentNames = methodInfo.getArgumentNames();
    int argumentCount = argumentTypeSignatures == null ? 0 : argumentTypeSignatures.length;
    if (argumentCount > 0) {
      long position = ((long) start << 32) + end;
      method.arguments = new Argument[argumentCount];
      for (int i = 0; i < argumentCount; i++) {
        TypeReference typeReference = stc.createTypeReference(argumentTypeSignatures[i], start, end);
        if (isVarargs && i == argumentCount-1) {
          typeReference.bits |= org.eclipse.jdt.internal.compiler.ast.ASTNode.IsVarArgs;
        }
        method.arguments[i] =
          new Argument(
            argumentNames[i],
            position,
            typeReference,
            ClassFileConstants.AccDefault);
        // do not care whether was final or not
      }
    }

    /* convert thrown exceptions */
    char[][] exceptionTypeNames = methodInfo.getExceptionTypeNames();
    int exceptionCount = exceptionTypeNames == null ? 0 : exceptionTypeNames.length;
    if (exceptionCount > 0) {
      method.thrownExceptions = new TypeReference[exceptionCount];
      for (int i = 0; i < exceptionCount; i++) {
        method.thrownExceptions[i] =
          stc.createTypeReference(exceptionTypeNames[i], start, end);
      }
    }

    /* convert local and anonymous types */
    if ((stc.flags & SourceTypeConverter.LOCAL_TYPE) != 0) {
      IJavaElement[] children = methodInfo.getChildren();
      int typesLength = 0;
      int childrenLength = children.length;
      for (int i = 0; i < childrenLength; ++i)
        if (children[i] instanceof SourceType)
          ++typesLength;

      if (typesLength != 0) {
        Statement[] statements = new Statement[typesLength];
        int typeIndex = 0;
        for (int i = 0; i < childrenLength; i++) {
          if (children[i] instanceof SourceType) {
            SourceType type = (SourceType) children[i];
            TypeDeclaration localType = stc.convert(type, compilationResult);
            if ((localType.bits & org.eclipse.jdt.internal.compiler.ast.ASTNode.IsAnonymousType) != 0) {
              QualifiedAllocationExpression expression = new QualifiedAllocationExpression(localType);
              expression.type = localType.superclass;
              localType.superclass = null;
              localType.superInterfaces = null;
              localType.allocation = expression;
              statements[typeIndex] = expression;
            } else {
              statements[typeIndex] = localType;
            }
            ++typeIndex;
          }
        }
        method.statements = statements;
      }
    }

    return method;
  }
}

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

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

import java.util.Locale;
import java.util.Map;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.AbstractVariableDeclaration;
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.env.AccessRestriction;
import org.eclipse.jdt.internal.compiler.env.IBinaryType;
import org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.eclipse.jdt.internal.compiler.env.ISourceType;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.impl.ITypeRequestor;
import org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
import org.eclipse.jdt.internal.compiler.lookup.PackageBinding;
import org.eclipse.jdt.internal.compiler.parser.SourceTypeConverter;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
import org.eclipse.jdt.internal.core.DefaultWorkingCopyOwner;
import org.eclipse.jdt.internal.core.JavaProject;
import org.eclipse.jdt.internal.core.SourceType;
import org.eclipse.jdt.internal.core.SourceTypeElementInfo;

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

@SuppressWarnings("restriction")
public privileged aspect DOMAspect {
  pointcut internalCreateAST(ASTParser parser, IProgressMonitor monitor) :
    execution(ASTNode ASTParser.internalCreateAST(IProgressMonitor)) &&
    args(monitor) &&
    target(parser);

  ASTNode around(ASTParser parser, IProgressMonitor monitor) :
    internalCreateAST(parser, monitor) {
    try {
      if (!(parser.typeRoot instanceof IScalaCompilationUnit))
        return proceed(parser, monitor);

      ICompilationUnit cu = (ICompilationUnit)parser.typeRoot;
      org.eclipse.jdt.internal.compiler.env.ICompilationUnit sourceUnit = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit)cu;

      IType[] topLevelTypes = cu.getTypes();
      int length = topLevelTypes.length;
      if (length == 0)
        throw new IllegalStateException();

      SourceTypeElementInfo[] topLevelInfos = new SourceTypeElementInfo[length];
      for (int i = 0; i < length; i++) {
        topLevelInfos[i] = (SourceTypeElementInfo) ((SourceType)topLevelTypes[i]).getElementInfo();
      }
      char[] fileName = ((ISourceType)topLevelInfos[0]).getFileName();

      CompilationResult result = new CompilationResult(fileName, 1, 1, 100);

      JavaProject javaProject = (JavaProject)cu.getJavaProject();
      Map compilerOptions0 = javaProject.getOptions(true);
      CompilerOptions compilerOptions = new CompilerOptions(compilerOptions0);
      compilerOptions.storeAnnotations = true;

      ProblemReporter problemReporter =
        new ProblemReporter(
          DefaultErrorHandlingPolicies.proceedWithAllProblems(),
          compilerOptions,
          new DefaultProblemFactory(Locale.getDefault()));

      int flags = SourceTypeConverter.FIELD_AND_METHOD | SourceTypeConverter.MEMBER_TYPE;

      CompilationUnitDeclaration unit =
        SourceTypeConverter.buildCompilationUnit(topLevelInfos, flags, problemReporter, result);

      INameEnvironment ne = javaProject.newSearchableNameEnvironment(DefaultWorkingCopyOwner.PRIMARY);
      final LookupEnvironment le = new LookupEnvironment(null, compilerOptions, problemReporter, ne);
      ITypeRequestor typeRequestor = new ITypeRequestor() {
        public void accept(IBinaryType binaryType, PackageBinding packageBinding, AccessRestriction accessRestriction) {
          le.createBinaryTypeFrom(binaryType, packageBinding, accessRestriction);
        }
        public void accept(org.eclipse.jdt.internal.compiler.env.ICompilationUnit unit, AccessRestriction accessRestriction) {}
        public void accept(ISourceType[] sourceType, PackageBinding packageBinding, AccessRestriction accessRestriction) {}
      };
      le.typeRequestor = typeRequestor;

      le.buildTypeBindings(unit, null);
      le.completeTypeBindings();
      fixTypes(unit.types);

      AST ast = AST.newAST(AST.JLS3);
      ast.setFlag(AST.RESOLVED_BINDINGS);
      ast.setDefaultNodeFlag(ASTNode.ORIGINAL);

      org.eclipse.jdt.core.dom.ASTConverter converter =
        new org.eclipse.jdt.core.dom.ASTConverter(compilerOptions0, true, monitor);

      org.eclipse.jdt.core.dom.BindingResolver resolver =
        new org.eclipse.jdt.core.dom.DefaultBindingResolver(
          unit.scope,
          DefaultWorkingCopyOwner.PRIMARY,
          new org.eclipse.jdt.core.dom.DefaultBindingResolver.BindingTables(),
          true);
      ast.setBindingResolver(resolver);
      converter.setAST(ast);

      ASTNode node = converter.convert(unit, sourceUnit.getContents());
      return node;
    } catch (JavaModelException ex) {
      throw new IllegalArgumentException(ex);
    }
  }

  private void fixTypes(TypeDeclaration[] types) {
    for(int i = 0, iLimit = types.length; i < iLimit ; ++i) {
      TypeDeclaration tpe = types[i];
      tpe.binding.getAnnotationTagBits();
      tpe.scope.buildFields();
      tpe.scope.buildMethods();
      fixFields(tpe.fields);
      fixMethods(tpe.methods);
      fixTypes(tpe.memberTypes);
    }
  }

  private void fixMethods(AbstractMethodDeclaration[] methods) {
    if (methods == null)
      return;

    for(int i = 0, iLimit = methods.length; i < iLimit; ++i) {
      AbstractMethodDeclaration m = methods[i];
      m.bodyStart = m.declarationSourceStart;
      m.bodyEnd = m.declarationSourceEnd;
      m.binding.getAnnotationTagBits();
    }
  }

  private void fixFields(AbstractVariableDeclaration[] fields) {
    if (fields == null)
      return;

    for(int i = 0, iLimit = fields.length; i < iLimit; ++i) {
      AbstractVariableDeclaration f = fields[i];
      f.declarationEnd = f.declarationSourceEnd;
    }
  }
}


fix percentage calculation bug in textual statistics feature

import java.awt.GridLayout;

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

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

public privileged aspect StatOverallTxt {

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

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

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

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

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

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

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

		return "#Spiele (ohne weiter): " + anzahlSpieleGesamt + " (gewonnen: "
				+ (anzahlSpieleGesamt > 0 ? anzahlSpieleGesamtGewonnen
						/ ((double) anzahlSpieleGesamt) : 0) * 100 + "%)\n"
				+ "#Rufspiele: " + anzahlRufspiele + " (gewonnen: "
				+ (anzahlRufspiele > 0 ? anzahlGewonneneRufspiele
						/ ((double) anzahlRufspiele) : 0) * 100 + "%)\n"
				+ "          -> teurstes Rufspiel: " + teuerstesRufspiel + "\n"
				+ "#Soli gesamt: " + (anzahlSolo + anzahlSoloTout + anzahlSoloSie)
				+ " (gewonnen: " + sologesamtwin * 100 + "%)\n"
				+ "#Soli normal: " + anzahlSolo	+ " (gewonnen: "
				+ (anzahlSolo > 0 ? anzahlGewonneneSoli / ((double) anzahlSolo)	: 0) * 100 + "%)\n"
				+ "            -> teurstes Solo: " + teuerstesSolo + "\n"
				+ "#Solo Tout: " + anzahlSoloTout + " (gewonnen: "
				+ (anzahlSoloTout > 0 ? anzahlGewonneneSoliTout
						/ ((double) anzahlSoloTout) : 0) * 100 + "%)\n"
				+ "          -> teurstes Solo Tout: " + teuerstesSoloTout + "\n"
				+ "#Solo Sie: " + anzahlSoloSie + "\n"
				+ "         -> teurstes Solo Sie: " + teuerstesSoloSie + "\n"
				+ "#Weiter: " + anzahlWeiter;
    }
}

import java.awt.GridLayout;

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

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

public privileged aspect StatOverallTxt {

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

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

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

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

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

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

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

		return "#Spiele (ohne weiter): " + anzahlSpieleGesamt + " (gewonnen: "
				+ (anzahlSpieleGesamt > 0 ? anzahlSpieleGesamtGewonnen
						/ ((double) anzahlSpieleGesamt) : 0) + "%)\n"
				+ "#Rufspiele: " + anzahlRufspiele + " (gewonnen: "
				+ (anzahlRufspiele > 0 ? anzahlGewonneneRufspiele
						/ ((double) anzahlRufspiele) : 0) + "%)\n"
				+ "          -> teurstes Rufspiel: " + teuerstesRufspiel + "\n"
				+ "#Soli gesamt: " + (anzahlSolo + anzahlSoloTout + anzahlSoloSie)
				+ " (gewonnen: " + sologesamtwin + "%)\n"
				+ "#Soli normal: " + anzahlSolo	+ " (gewonnen: "
				+ (anzahlSolo > 0 ? anzahlGewonneneSoli / ((double) anzahlSolo)	: 0) + "%)\n"
				+ "            -> teurstes Solo: " + teuerstesSolo + "\n"
				+ "#Solo Tout: " + anzahlSoloTout + " (gewonnen: "
				+ (anzahlSoloTout > 0 ? anzahlGewonneneSoliTout
						/ ((double) anzahlSoloTout) : 0) + "%)\n"
				+ "          -> teurstes Solo Tout: " + teuerstesSoloTout + "\n"
				+ "#Solo Sie: " + anzahlSoloSie + "\n"
				+ "         -> teurstes Solo Sie: " + teuerstesSoloSie + "\n"
				+ "#Weiter: " + anzahlWeiter;
    }
}


polishing

polishing

/*
 * Copyright 2002-2010 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.mock.staticmock;

/**
 * Annotation-based aspect to use in test build to enable mocking static methods
 * on JPA-annotated @Entity classes, as used by Roo for finders.
 *
 *
Mocking will occur in the call stack of any method in a class (typically a test class)
 * that is annotated with the @MockStaticEntityMethods annotation.
 *
 *
Also provides static methods to simplify the programming model for
 * entering playback mode and setting expected return values.
 *
 *
Usage:
 *

 *
Annotate a test class with @MockStaticEntityMethods.
 *
In each test method, AnnotationDrivenStaticEntityMockingControl will begin in recording mode.
 * Invoke static methods on Entity classes, with each recording-mode invocation
 * being followed by an invocation to the static expectReturn() or expectThrow()
 * method on AnnotationDrivenStaticEntityMockingControl.
 *
Invoke the static AnnotationDrivenStaticEntityMockingControl() method.
 *
Call the code you wish to test that uses the static methods. Verification will
 * occur automatically.
 *

 *
 * @author Rod Johnson
 * @author Ramnivas Laddad
 * @see MockStaticEntityMethods
 */
public aspect AnnotationDrivenStaticEntityMockingControl extends AbstractMethodMockingControl {

	/**
	 * Stop recording mock calls and enter playback state
	 */
	public static void playback() {
		AnnotationDrivenStaticEntityMockingControl.aspectOf().playbackInternal();
	}

	public static void expectReturn(Object retVal) {
		AnnotationDrivenStaticEntityMockingControl.aspectOf().expectReturnInternal(retVal);
	}

	public static void expectThrow(Throwable throwable) {
		AnnotationDrivenStaticEntityMockingControl.aspectOf().expectThrowInternal(throwable);
	}

	// Only matches directly annotated @Test methods, to allow methods in
	// @MockStatics classes to invoke each other without resetting the mocking environment
	protected pointcut mockStaticsTestMethod() : execution(public * (@MockStaticEntityMethods *).*(..));

	protected pointcut methodToMock() : execution(public static * (@javax.persistence.Entity *).*(..));

}

/*
 * Copyright 2002-2010 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.mock.staticmock;

/**
 * Annotation-based aspect to use in test build to enable mocking static methods
 * on Entity classes, as used by Roo for finders.
 *

 * Mocking will occur in the call stack of any method in a class (typically a test class)
 * that is annotated with the @MockStaticEntityMethods annotation.
 *

 * Also provides static methods to simplify the programming model for
 * entering playback mode and setting expected return values.
 *

 * Usage:

 *
Annotate a test class with @MockStaticEntityMethods.
 *
In each test method, AnnotationDrivenStaticEntityMockingControl will begin in recording mode.
 * Invoke static methods on Entity classes, with each recording-mode invocation
 * being followed by an invocation to the static expectReturn() or expectThrow()
 * method on AnnotationDrivenStaticEntityMockingControl.
 *
Invoke the static AnnotationDrivenStaticEntityMockingControl() method.
 *
Call the code you wish to test that uses the static methods. Verification will
 * occur automatically.
 *

 *
 * @author Rod Johnson
 * @author Ramnivas Laddad
 * @see MockStaticEntityMethods
 */
public aspect AnnotationDrivenStaticEntityMockingControl extends AbstractMethodMockingControl {

	/**
	 * Stop recording mock calls and enter playback state
	 */
	public static void playback() {
		AnnotationDrivenStaticEntityMockingControl.aspectOf().playbackInternal();
	}

	public static void expectReturn(Object retVal) {
		AnnotationDrivenStaticEntityMockingControl.aspectOf().expectReturnInternal(retVal);
	}

	public static void expectThrow(Throwable throwable) {
		AnnotationDrivenStaticEntityMockingControl.aspectOf().expectThrowInternal(throwable);
	}

	// Only matches directly annotated @Test methods, to allow methods in
	// @MockStatics classes to invoke each other without resetting the mocking environment
	protected pointcut mockStaticsTestMethod() : execution(public * (@MockStaticEntityMethods *).*(..));

	protected pointcut methodToMock() : execution(public static * (@javax.persistence.Entity *).*(..));

}


Static tracing aspect

Static tracing aspect

import org.aspectj.lang.JoinPoint;

/**
 * Created with IntelliJ IDEA.
 * User: kockt
 * Date: 13-01-13
 * Time: 17:09
 * To change this template use File | Settings | File Templates.
 */
public aspect TraceRequestFlow {
    pointcut inWinstone(): within(net.winstone.*) || within(net.winstone..*);

    pointcut internalCall(Object o): target(o) && call(* *(..)) && !within(TraceRequestFlow);

    before(Object o): internalCall(o) && inWinstone() {
        System.out.println(String.format("%s:%s:%s,%s:%s", thisEnclosingJoinPointStaticPart.getSourceLocation().getFileName(), thisEnclosingJoinPointStaticPart.getSignature().getName(), thisEnclosingJoinPointStaticPart.getSourceLocation().getLine(), thisJoinPoint.getSourceLocation().getFileName(), thisJoinPoint.getSignature().getName(), thisJoinPoint.getSourceLocation().getLine()));
    }
}

/**
 * Created with IntelliJ IDEA.
 * User: kockt
 * Date: 13-01-13
 * Time: 17:09
 * To change this template use File | Settings | File Templates.
 */
public aspect TraceRequestFlow {

    pointcut was_called(Object o):
            target(o) && call(* *(..)) && within(net.winstone);

    before() calling: was_called(o) {
        System.out.println(o);
    }

}