<commit_before>/*
 * Copyright 2013-2014 <NAME> (gs<EMAIL>ikowski at gmail dot com)
 *
 * 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 com.google.code.play2.plugin;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.plugin.MojoExecutionException;
//import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuildingException;
import org.apache.maven.project.artifact.InvalidDependencyVersionException;

import com.google.code.sbt.compiler.api.AnalysisProcessor;
import com.google.code.sbt.compiler.api.Compiler;
//import com.google.code.sbt.compiler.api.Compiler;
import com.google.code.sbt.compiler.api.CompilerHelper;

public abstract class AbstractPlay2EnhanceMojo
    extends AbstractPlay2Mojo
{

    /**
     * Forced SBT version.<br>
     * <br>
     * Used to automatically select one of the "well known" SBT compilers if no compiler added explicitly as plugin's dependency.
     * There are three cases possible:
     * <ul>
     * <li>
     * If {@link #sbtVersion} is specified, compatible {@link Compiler} implementation
     * is selected and configured to use {@link #sbtVersion} SBT version for compilation.
     * </li>
     * <li>
     * If {@link #sbtVersion} is not specified, and {@link #playVersion} is specified
     * {@link #playVersion} parameter value is used to indirectly select compatible {@link Compiler} implementation
     * and it's {@link Compiler#getDefaultSbtVersion()} SBT version used for compilation.
     * </li>
     * <li>
     * If both {@link #sbtVersion} and {@link #playVersion} are not specified
     * the most recent {@link Compiler} implementation is selected
     * and it's {@link Compiler#getDefaultSbtVersion()} SBT version used for compilation.
     * </li>
     * </ul>
     * 
     * @since 1.0.0
     */
    @Parameter( property = "sbt.version" )
    protected String sbtVersion;

    private static final String sbtCompilerPluginGroupId = "com.google.code.sbt-compiler-maven-plugin";

    private static final String sbtCompilerPluginApiArtifactId = "sbt-compiler-api";

    /**
     * Map of SBT compiler implementations. For now only zero or one allowed.
     */
    @Component( role = AnalysisProcessor.class )
    private Map<String, AnalysisProcessor> analysisProcessors;

    // SBT compiler resolution for Analysis cache processing

    // Cached classloaders
    private static final ConcurrentHashMap<String, ClassLoader> sbtCompilerCachedClassLoaders = new ConcurrentHashMap<String, ClassLoader>( 2 );

    private static ClassLoader getSbtCompilerCachedClassLoader( String compilerId )
    {
        return sbtCompilerCachedClassLoaders.get( compilerId );
    }

    private static void setSbtCompilerCachedClassLoader( String compilerId, ClassLoader classLoader )
    {
        sbtCompilerCachedClassLoaders.put( compilerId, classLoader );
    }

    protected AnalysisProcessor getSbtAnalysisProcessor()
        throws MojoExecutionException
    {
        AnalysisProcessor sbtAnalysisProcessor = null;
        if ( !analysisProcessors.isEmpty() )
        {
            sbtAnalysisProcessor = getDeclaredSbtAnalysisProcessor();
        }
        else
        {
            sbtAnalysisProcessor = getWellKnownSbtAnalysisProcessor();
        }
        return sbtAnalysisProcessor;
    }

    private AnalysisProcessor getDeclaredSbtAnalysisProcessor()
        throws MojoExecutionException
    {
        if ( analysisProcessors.size() > 1 )
        {
            throw new MojoExecutionException( "Too many compiles defined. A maximum of one allowed." );
        }

        Map.Entry<String, AnalysisProcessor> compilerEntry = analysisProcessors.entrySet().iterator().next();
        String compilerId = compilerEntry.getKey();
        AnalysisProcessor sbtAnalysisProcessor = compilerEntry.getValue();

        getLog().debug( String.format( "Using declared compiler \"%s\".", compilerId ) );

        return sbtAnalysisProcessor;
    }

    private AnalysisProcessor getWellKnownSbtAnalysisProcessor()
        throws MojoExecutionException
    {
        try
        {
            String compilerId = CompilerHelper.getDefaultCompilerId( sbtVersion, playVersion );
            ClassLoader compilerClassLoader = getSbtCompilerCachedClassLoader( compilerId );
            if ( compilerClassLoader == null )
            {
                getLog().debug( String.format( "Cached classloader for compiler \"%s\" not available.", compilerId ) );
            }
            else
            {
                if ( compilerClassLoader.getParent() == Thread.currentThread().getContextClassLoader() )
                {
                    getLog().debug( String.format( "Using cached classloader for compiler \"%s\".", compilerId ) );
                }
                else
                {
                    getLog().debug( String.format( "Invalidated cached classloader for compiler \"%s\". Parent classloader changed from %d to %d.",
                                                   compilerId,
                                                   Integer.valueOf( compilerClassLoader.getParent().hashCode() ),
                                                   Integer.valueOf( Thread.currentThread().getContextClassLoader().hashCode() ) ) );
                    compilerClassLoader = null;
                }
            }
            if ( compilerClassLoader == null )
            {
                Artifact compilerArtifact =
                    getResolvedArtifact( sbtCompilerPluginGroupId, "sbt-compiler-" + compilerId,
                                         getSbtCompilerPluginVersion() );

                Set<Artifact> compilerDependencies = getAllDependencies( compilerArtifact );
                List<File> classPathFiles = new ArrayList<File>( compilerDependencies.size() + 2 );
                classPathFiles.add( compilerArtifact.getFile() );
                for ( Artifact dependencyArtifact : compilerDependencies )<commit_msg>#32 - Class enhancement mojos do not use defined SBT version - small refactoring - class CompilerHelper renamed to Compilers.<commit_after>/*
 * Copyright 2013-2014 <NAME> (<EMAIL> at gmail dot com)
 *
 * 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 com.google.code.play2.plugin;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.plugin.MojoExecutionException;
//import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuildingException;
import org.apache.maven.project.artifact.InvalidDependencyVersionException;

import com.google.code.sbt.compiler.api.AnalysisProcessor;
import com.google.code.sbt.compiler.api.Compiler;
import com.google.code.sbt.compiler.api.Compilers;

public abstract class AbstractPlay2EnhanceMojo
    extends AbstractPlay2Mojo
{

    /**
     * Forced SBT version.<br>
     * <br>
     * Used to automatically select one of the "well known" SBT compilers if no compiler added explicitly as plugin's dependency.
     * There are three cases possible:
     * <ul>
     * <li>
     * If {@link #sbtVersion} is specified, compatible {@link Compiler} implementation
     * is selected and configured to use {@link #sbtVersion} SBT version for compilation.
     * </li>
     * <li>
     * If {@link #sbtVersion} is not specified, and {@link #playVersion} is specified
     * {@link #playVersion} parameter value is used to indirectly select compatible {@link Compiler} implementation
     * and it's {@link Compiler#getDefaultSbtVersion()} SBT version used for compilation.
     * </li>
     * <li>
     * If both {@link #sbtVersion} and {@link #playVersion} are not specified
     * the most recent {@link Compiler} implementation is selected
     * and it's {@link Compiler#getDefaultSbtVersion()} SBT version used for compilation.
     * </li>
     * </ul>
     * 
     * @since 1.0.0
     */
    @Parameter( property = "sbt.version" )
    protected String sbtVersion;

    private static final String sbtCompilerPluginGroupId = "com.google.code.sbt-compiler-maven-plugin";

    private static final String sbtCompilerPluginApiArtifactId = "sbt-compiler-api";

    /**
     * Map of SBT compiler implementations. For now only zero or one allowed.
     */
    @Component( role = AnalysisProcessor.class )
    private Map<String, AnalysisProcessor> analysisProcessors;

    // SBT compiler resolution for Analysis cache processing

    // Cached classloaders
    private static final ConcurrentHashMap<String, ClassLoader> sbtCompilerCachedClassLoaders = new ConcurrentHashMap<String, ClassLoader>( 2 );

    private static ClassLoader getSbtCompilerCachedClassLoader( String compilerId )
    {
        return sbtCompilerCachedClassLoaders.get( compilerId );
    }

    private static void setSbtCompilerCachedClassLoader( String compilerId, ClassLoader classLoader )
    {
        sbtCompilerCachedClassLoaders.put( compilerId, classLoader );
    }

    protected AnalysisProcessor getSbtAnalysisProcessor()
        throws MojoExecutionException
    {
        AnalysisProcessor sbtAnalysisProcessor = null;
        if ( !analysisProcessors.isEmpty() )
        {
            sbtAnalysisProcessor = getDeclaredSbtAnalysisProcessor();
        }
        else
        {
            sbtAnalysisProcessor = getWellKnownSbtAnalysisProcessor();
        }
        return sbtAnalysisProcessor;
    }

    private AnalysisProcessor getDeclaredSbtAnalysisProcessor()
        throws MojoExecutionException
    {
        if ( analysisProcessors.size() > 1 )
        {
            throw new MojoExecutionException( "Too many compiles defined. A maximum of one allowed." );
        }

        Map.Entry<String, AnalysisProcessor> compilerEntry = analysisProcessors.entrySet().iterator().next();
        String compilerId = compilerEntry.getKey();
        AnalysisProcessor sbtAnalysisProcessor = compilerEntry.getValue();

        getLog().debug( String.format( "Using declared compiler \"%s\".", compilerId ) );

        return sbtAnalysisProcessor;
    }

    private AnalysisProcessor getWellKnownSbtAnalysisProcessor()
        throws MojoExecutionException
    {
        try
        {
            String compilerId = Compilers.getDefaultCompilerId( sbtVersion, playVersion );
            ClassLoader compilerClassLoader = getSbtCompilerCachedClassLoader( compilerId );
            if ( compilerClassLoader == null )
            {
                getLog().debug( String.format( "Cached classloader for compiler \"%s\" not available.", compilerId ) );
            }
            else
            {
                if ( compilerClassLoader.getParent() == Thread.currentThread().getContextClassLoader() )
                {
                    getLog().debug( String.format( "Using cached classloader for compiler \"%s\".", compilerId ) );
                }
                else
                {
                    getLog().debug( String.format( "Invalidated cached classloader for compiler \"%s\". Parent classloader changed from %d to %d.",
                                                   compilerId,
                                                   Integer.valueOf( compilerClassLoader.getParent().hashCode() ),
                                                   Integer.valueOf( Thread.currentThread().getContextClassLoader().hashCode() ) ) );
                    compilerClassLoader = null;
                }
            }
            if ( compilerClassLoader == null )
            {
                Artifact compilerArtifact =
                    getResolvedArtifact( sbtCompilerPluginGroupId, "sbt-compiler-" + compilerId,
                                         getSbtCompilerPluginVersion() );

                Set<Artifact> compilerDependencies = getAllDependencies( compilerArtifact );
                List<File> classPathFiles = new ArrayList<File>( compilerDependencies.size() + 2 );
                classPathFiles.add( compilerArtifact.getFile() );
                for ( Artifact dependencyArtifact : compilerDependencies )
{'fraction_non_alphanumeric': 0.087336860670194, 'fraction_numerical': 0.0031040564373897707, 'mean_word_length': 2.7542372881355934, 'pattern_counts': {'":': 0, '<': 41, '<?xml version=': 0, '>': 43, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 16, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1468988', 'n_tokens_mistral': 3613, 'n_tokens_neox': 3486, 'n_words': 982}