private List<URL> generateExecutionClasspath(
      Set<Artifact> resolvedArtifacts, String... excludeGroups) throws MojoExecutionException {
    /*
     * Convert each resolved artifact into a URL/classpath element.
     */
    final ArrayList<URL> classpath = new ArrayList<URL>();

    final List<String> excludes = Arrays.asList(excludeGroups);

    try {

      for (Artifact resolvedArtifact : resolvedArtifacts) {
        if (excludes.contains(resolvedArtifact.getGroupId())) continue;
        final File file = resolvedArtifact.getFile();
        //        System.out.println("artifact " + resolvedArtifact.toString());
        if (file != null) {
          if (artifactIdsToInsertAtStartOfClasspath.contains(resolvedArtifact.getArtifactId())) {
            getLog().info("adding at the start" + file.getAbsolutePath());
            // a patch? grails is full of them, insert it at the start
            classpath.add(0, file.toURI().toURL());
          } else { // insert it at the end
            classpath.add(file.toURI().toURL());
          }
        }
      }
    } catch (MalformedURLException murle) {
      throw new MojoExecutionException("Unable to find files", murle);
    }

    return classpath;
  }
  /**
   * Converts a collection of Dependency objects to a list of corresponding Artifact objects.
   *
   * @param deps The collection of dependencies to convert.
   * @return A list of Artifact instances.
   */
  private List<Artifact> dependenciesToArtifacts(final Collection<Dependency> deps) {
    final List<Artifact> artifacts = new ArrayList<Artifact>(deps.size());
    for (Dependency dep : deps) {
      artifacts.add(dependencyToArtifact(dep));
    }

    return artifacts;
  }
  private Set<Artifact> filterArtifacts(Set<Artifact> resolvedArtifacts, String... scopes) {
    HashSet<Artifact> artifacts = new HashSet<Artifact>();
    List<String> checkScopes = Arrays.asList(scopes);

    for (Artifact artifact : resolvedArtifacts) {
      if (checkScopes.contains(artifact.getScope())) artifacts.add(artifact);
    }

    return artifacts;
  }
  private static Collection<String> collectActivatedProfiles(MavenProject mavenProject) {
    // for some reason project's active profiles do not contain parent's profiles - only local and
    // settings'.
    // parent's profiles do not contain settings' profiles.

    List<Profile> profiles = new ArrayList<Profile>();
    while (mavenProject != null) {
      profiles.addAll(mavenProject.getActiveProfiles());
      mavenProject = mavenProject.getParent();
    }
    return collectProfilesIds(profiles);
  }
  /**
   * Returns only the dependencies matching the supplied group ID value, filtering out all others.
   *
   * @param dependencies A list of dependencies to be filtered.
   * @return The filtered list of dependencies.
   */
  private List<Dependency> filterGrailsDependencies(final List<Dependency> dependencies) {
    final List<Dependency> filteredDependencies = new ArrayList<Dependency>();
    for (final Dependency dependency : dependencies) {

      if (dependency.getArtifactId().equals("grails-scripts")
          || dependency.getArtifactId().equals("grails-bootstrap")
          || dependency.getArtifactId().equals("grails-launcher")) {
        filteredDependencies.add(dependency);
      }
    }
    return filteredDependencies;
  }
  /**
   * Converts a collection of Maven artifacts to files. For this method to function properly, the
   * artifacts MUST be resolved first.
   *
   * @param artifacts A collection of artifacts.
   * @return The list of files pointed to by the artifacts.
   */
  private List<File> artifactsToFiles(final Collection<Artifact> artifacts) {
    final List<File> files = new ArrayList<File>(artifacts.size());
    StringBuilder sb = new StringBuilder();
    for (Artifact artifact : artifacts) {
      sb.append("\natof " + artifact.getFile().getAbsolutePath());
      files.add(artifact.getFile());
    }

    if (logDependencies) getLog().info(sb.toString());

    return files;
  }
  /**
   * Generates the classpath to be used by the launcher to execute the requested Grails script.
   *
   * @return An array of {@code URL} objects representing the dependencies required on the classpath
   *     to execute the selected Grails script.
   * @throws MojoExecutionException if an error occurs while attempting to resolve the dependencies
   *     and generate the classpath array.
   */
  @SuppressWarnings("unchecked")
  private URL[] generateGrailsExecutionClasspath(Set<Artifact> resolvedArtifacts)
      throws MojoExecutionException {
    try {

      final List<URL> classpath = generateExecutionClasspath(resolvedArtifacts);

      // check to see if someone is adding build listeners on the classpath, and if so, bring in the
      // system classpath and add it to our urls
      // IDEA for example does this
      if (System.getProperty("grails.build.listeners") != null) {
        String cp = System.getProperty("java.class.path");
        for (String c : cp.split(":")) {
          File f = new File(c);
          if (f.exists()) classpath.add(f.toURI().toURL());
        }
      }

      if (System.getProperty("grails.debug.classpath") != null) {
        for (URL url : classpath) {
          getLog().info("classpath " + url.toString());
        }
      }

      /*
       * Add the "tools.jar" to the classpath so that the Grails scripts can run native2ascii.
       * First assume that "java.home" points to a JRE within a JDK.  NOTE that this will not
       * provide a valid path on Mac OSX.  This is not a big deal, as the JDK on Mac OSX already
       * adds the required JAR's to the classpath.  This logic is really only for Windows/*Unix.
       */
      final String javaHome = System.getProperty("java.home");
      File toolsJar = new File(javaHome, "../lib/tools.jar");
      if (!toolsJar.exists()) {
        // The "tools.jar" cannot be found with that path, so
        // now try with the assumption that "java.home" points
        // to a JDK.
        toolsJar = new File(javaHome, "tools.jar");
      }

      if (toolsJar.exists()) {
        java.net.URL url = toolsJar.toURI().toURL();
        if (url != null) {
          classpath.add(url);
        }
      }

      return classpath.toArray(new URL[classpath.size()]);
    } catch (final Exception e) {
      throw new MojoExecutionException("Failed to create classpath for Grails execution.", e);
    }
  }
 private List<ArtifactRepository> convertRepositories(List<MavenRemoteRepository> repositories)
     throws RemoteException {
   List<ArtifactRepository> result = new ArrayList<ArtifactRepository>();
   for (MavenRemoteRepository each : repositories) {
     try {
       ArtifactRepositoryFactory factory = getComponent(ArtifactRepositoryFactory.class);
       result.add(
           ProjectUtils.buildArtifactRepository(
               MavenModelConverter.toNativeRepository(each), factory, myContainer));
     } catch (InvalidRepositoryException e) {
       Maven3ServerGlobals.getLogger().warn(e);
     }
   }
   return result;
 }
  private MavenExecutionResult doExecute(
      @NotNull final File file,
      @NotNull final List<String> activeProfiles,
      @NotNull final List<String> inactiveProfiles,
      @NotNull final List<String> goals,
      @NotNull final List<String> selectedProjects,
      boolean alsoMake,
      boolean alsoMakeDependents)
      throws RemoteException {
    MavenExecutionRequest request = createRequest(file, activeProfiles, inactiveProfiles, goals);

    if (!selectedProjects.isEmpty()) {
      request.setRecursive(true);
      request.setSelectedProjects(selectedProjects);
      if (alsoMake && alsoMakeDependents) {
        request.setMakeBehavior(ReactorManager.MAKE_BOTH_MODE);
      } else if (alsoMake) {
        request.setMakeBehavior(ReactorManager.MAKE_MODE);
      } else if (alsoMakeDependents) {
        request.setMakeBehavior(ReactorManager.MAKE_DEPENDENTS_MODE);
      }
    }

    Maven maven = getComponent(Maven.class);
    org.apache.maven.execution.MavenExecutionResult executionResult = maven.execute(request);

    return new MavenExecutionResult(
        executionResult.getProject(), filterExceptions(executionResult.getExceptions()));
  }
  private void resolveClasspath() throws MojoExecutionException {
    parsePatchArtifacts();

    getLog()
        .info(
            "Resolving dependencies"
                + (useTransitives
                    ? ""
                    : " - warning! we are not using transitive dependencies, only those directly in the pom.xml"));

    resolvedArtifacts = collectAllProjectArtifacts();

    /*
     * Remove any Grails plugins that may be in the resolved artifact set.  This is because we
     * do not need them on the classpath, as they will be handled later on by a separate call to
     * "install" them.
     */
    pluginArtifacts = removePluginArtifacts(resolvedArtifacts);

    pluginDirectories = new ArrayList<File>();

    for (Artifact artifact : pluginArtifacts)
      pluginDirectories.add(getPluginDirAndInstallIfNecessary(artifact));

    if (getLog().isInfoEnabled()) {
      for (File f : pluginDirectories) {
        getLog().info("plugin: " + f.getAbsolutePath());
      }
    }

    classpath = generateGrailsExecutionClasspath(resolvedArtifacts);

    System.gc();
  }
  protected void parsePatchArtifacts() {
    if (patchArtifacts != null) {
      StringTokenizer st = new StringTokenizer(patchArtifacts, ",");

      while (st.hasMoreTokens()) {
        artifactIdsToInsertAtStartOfClasspath.add(st.nextToken());
      }
    }
  }
  /**
   * Gets around an issue where a binary plugin's resource refers to a source plugins's resource and
   * the binary plugin is subsequently requested in a binary or source artifact.
   *
   * @param existing - the existing decoded classpath
   * @return - the new classpath with the extra directories in it where source plugins will be
   *     stored
   * @throws MalformedURLException
   */
  protected URL[] addBinaryPluginWorkaround(URL[] existing) throws MalformedURLException {

    List<URL> classpath = new ArrayList<URL>();

    classpath.add(new File(basedir, "target/plugin-build-classes").toURI().toURL());
    classpath.add(new File(basedir, "target/plugin-provided-classes").toURI().toURL());
    classpath.add(new File(basedir, "target/plugin-classes").toURI().toURL());
    classpath.add(new File(basedir, "target/resources").toURI().toURL());

    classpath.addAll(Arrays.asList(existing));

    URL[] workaround = new URL[classpath.size()];

    return classpath.toArray(workaround);
  }
  public static ProfileApplicationResult applyProfiles(
      MavenModel model,
      File basedir,
      Collection<String> explicitProfiles,
      Collection<String> alwaysOnProfiles)
      throws RemoteException {
    Model nativeModel = MavenModelConverter.toNativeModel(model);

    List<Profile> activatedPom = new ArrayList<Profile>();
    List<Profile> activatedExternal = new ArrayList<Profile>();
    List<Profile> activeByDefault = new ArrayList<Profile>();

    List<Profile> rawProfiles = nativeModel.getProfiles();
    List<Profile> expandedProfilesCache = null;

    for (int i = 0; i < rawProfiles.size(); i++) {
      Profile eachRawProfile = rawProfiles.get(i);

      boolean shouldAdd =
          explicitProfiles.contains(eachRawProfile.getId())
              || alwaysOnProfiles.contains(eachRawProfile.getId());

      Activation activation = eachRawProfile.getActivation();
      if (activation != null) {
        if (activation.isActiveByDefault()) {
          activeByDefault.add(eachRawProfile);
        }

        // expand only if necessary
        if (expandedProfilesCache == null)
          expandedProfilesCache = doInterpolate(nativeModel, basedir).getProfiles();
        Profile eachExpandedProfile = expandedProfilesCache.get(i);

        for (ProfileActivator eachActivator : getProfileActivators(basedir)) {
          try {
            if (eachActivator.canDetermineActivation(eachExpandedProfile)
                && eachActivator.isActive(eachExpandedProfile)) {
              shouldAdd = true;
              break;
            }
          } catch (ProfileActivationException e) {
            Maven3ServerGlobals.getLogger().warn(e);
          }
        }
      }

      if (shouldAdd) {
        if (MavenConstants.PROFILE_FROM_POM.equals(eachRawProfile.getSource())) {
          activatedPom.add(eachRawProfile);
        } else {
          activatedExternal.add(eachRawProfile);
        }
      }
    }

    List<Profile> activatedProfiles =
        new ArrayList<Profile>(activatedPom.isEmpty() ? activeByDefault : activatedPom);
    activatedProfiles.addAll(activatedExternal);

    for (Profile each : activatedProfiles) {
      new DefaultProfileInjector().injectProfile(nativeModel, each, null, null);
    }

    return new ProfileApplicationResult(
        MavenModelConverter.convertModel(nativeModel, null), collectProfilesIds(activatedProfiles));
  }