Ejemplo n.º 1
0
  public void execute() throws MojoExecutionException {
    MavenProject project = getProject();

    if (!supportedProjectTypes.contains(project.getPackaging())) {
      getLog().info("Ignoring packaging type " + project.getPackaging());
      return;
    } else if ("NONE".equalsIgnoreCase(obrRepository)) {
      getLog().info("OBR update disabled (enable with -DobrRepository)");
      return;
    }

    Log log = getLog();
    ObrUpdate update;

    String mavenRepository = localRepository.getBasedir();

    URI repositoryXml = ObrUtils.findRepositoryXml(mavenRepository, obrRepository);
    URI obrXmlFile = ObrUtils.toFileURI(obrXml);
    URI bundleJar;

    if (null == file) {
      bundleJar = ObrUtils.findBundleJar(localRepository, project.getArtifact());
    } else {
      bundleJar = file.toURI();
    }

    Config userConfig = new Config();

    update =
        new ObrUpdate(
            repositoryXml, obrXmlFile, project, bundleJar, mavenRepository, userConfig, log);

    update.updateRepository();
  }
 /**
  * @throws MojoExecutionException
  * @throws MojoFailureException
  */
 protected void deployBuiltApk() throws MojoExecutionException, MojoFailureException {
   // If we're not on a supported packaging with just skip (Issue 112)
   // http://code.google.com/p/maven-android-plugin/issues/detail?id=112
   if (!SUPPORTED_PACKAGING_TYPES.contains(project.getPackaging())) {
     getLog().info("Skipping deployment on " + project.getPackaging());
     return;
   }
   File apkFile =
       new File(project.getBuild().getDirectory(), project.getBuild().getFinalName() + "." + APK);
   deployApk(apkFile);
 }
Ejemplo n.º 3
0
  public void execute() throws MojoExecutionException, MojoFailureException {
    if (skip || skipExec) {
      getLog().info("Skipping tests");
      return;
    }

    if (!"eclipse-test-plugin".equals(project.getPackaging())) {
      getLog().warn("Unsupported packaging type " + project.getPackaging());
      return;
    }

    if (testSuite != null || testClass != null) {
      if (testSuite == null || testClass == null) {
        throw new MojoExecutionException(
            "Both testSuite and testClass must be provided or both should be null");
      }

      MavenProject suite = getTestSuite(testSuite);

      if (suite == null) {
        throw new MojoExecutionException(
            "Cannot find test suite project with Bundle-SymbolicName " + testSuite);
      }

      if (!suite.equals(project)) {
        getLog()
            .info(
                "Not executing tests, testSuite="
                    + testSuite
                    + " and project is not the testSuite");
        return;
      }
    }

    EquinoxInstallation testRuntime =
        createEclipseInstallation(false, DefaultReactorProject.adapt(session));

    String testBundle = null;
    boolean succeeded = runTest(testRuntime, testBundle);

    if (succeeded) {
      getLog().info("All tests passed!");
    } else {
      throw new MojoFailureException(
          "There are test failures.\n\nPlease refer to "
              + reportsDirectory
              + " for the individual test results.");
    }
  }
  public TargetPlatform computeTargetPlatform(
      MavenSession session, MavenProject project, List<ReactorProject> reactorProjects) {
    TargetPlatformConfiguration configuration =
        TychoProjectUtils.getTargetPlatformConfiguration(project);

    ExecutionEnvironment ee =
        projectTypes.get(project.getPackaging()).getExecutionEnvironment(project);

    TargetPlatformBuilder tpBuilder =
        resolverFactory.createTargetPlatformBuilder( //
            ee != null ? ee.getProfileName() : null, configuration.isDisableP2Mirrors());
    tpBuilder.setProjectLocation(project.getBasedir());

    addReactorProjectsToTargetPlatform(reactorProjects, tpBuilder);

    if (TargetPlatformConfiguration.POM_DEPENDENCIES_CONSIDER.equals(
        configuration.getPomDependencies())) {
      addPomDependenciesToTargetPlatform(project, tpBuilder, reactorProjects, session);
    }

    for (ArtifactRepository repository : project.getRemoteArtifactRepositories()) {
      addEntireP2RepositoryToTargetPlatform(repository, tpBuilder, session);
    }

    if (configuration.getTarget() != null) {
      addTargetFileContentToTargetPlatform(configuration, tpBuilder, session);
    }

    tpBuilder.addFilters(configuration.getFilters());

    return tpBuilder.buildTargetPlatform();
  }
  @Override
  public void execute() throws MojoExecutionException, MojoFailureException {

    FileOutputStream fos = null;
    try {
      if (!project.getPackaging().equalsIgnoreCase("pom")) {

        String status = project.getProperties().getProperty("deegree.module.status");
        if (status == null) {
          status = "unknown";
        }

        File f = new File("/tmp/" + status + ".txt");
        fos = new FileOutputStream(f, true);
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(fos, "UTF-8"));

        writer.print("||");
        writer.print(project.getArtifactId());
        writer.print("||");
        writer.print(project.getDescription());
        writer.print("||");
        writer.print("\n");
        writer.close();
      }
    } catch (FileNotFoundException e) {
      throw new MojoExecutionException(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
      throw new MojoExecutionException(e.getMessage(), e);
    } finally {
      IOUtils.closeQuietly(fos);
    }
  }
 protected void aggregate(MavenProject parent) throws Exception {
   List<MavenProject> modules = parent.getCollectedProjects();
   File dest = new File(parent.getReporting().getOutputDirectory() + "/" + outputDirectory);
   getLog().info("start aggregation into " + dest);
   StringBuilder mpath = new StringBuilder();
   for (MavenProject module : modules) {
     if ("pom".equals(module.getPackaging().toLowerCase())) {
       continue;
     }
     if (aggregateDirectOnly && module.getParent() != parent) {
       continue;
     }
     File subScaladocPath =
         new File(module.getReporting().getOutputDirectory() + "/" + outputDirectory)
             .getAbsoluteFile();
     // System.out.println(" -> " + project.getModulePathAdjustment(module)  +" // " +
     // subScaladocPath + " // " + module.getBasedir() );
     if (subScaladocPath.exists()) {
       mpath.append(subScaladocPath).append(File.pathSeparatorChar);
     }
   }
   if (mpath.length() != 0) {
     getLog().info("aggregate vscaladoc from : " + mpath);
     JavaMainCaller jcmd = getScalaCommand();
     jcmd.addOption("-d", dest.getAbsolutePath());
     jcmd.addOption("-aggregate", mpath.toString());
     jcmd.run(displayCmd);
   } else {
     getLog().warn("no vscaladoc to aggregate");
   }
   tryAggregateUpper(parent);
 }
Ejemplo n.º 7
0
 public void execute() throws MojoExecutionException {
   if (skip) {
     getLog().info("[WarSync] WarSync is skiped. See ${warsync.skip} parameter.");
     return;
   }
   if (onlyRunWithEclipseGoal && !session.getGoals().contains("eclipse:eclipse")) {
     getLog()
         .info(
             "[WarSync] WarSync will be skiped for no 'eclipse:eclipse' goal found in current build.\n\tSet ${warsync.onlyRunWithEclipseGoal} to false to disable the feature if you want to force to run.");
     return;
   }
   if (!"war".equals(project.getPackaging())) {
     return;
   }
   try {
     prepareArtifacts();
     if (LIB_MODE_COPY.equals(libMode)) {
       copyLibJars(getClearLibDir());
     } else {
       createClasspathJarFile(getClearLibDir());
     }
     createFileSyncConfigs();
   } catch (Exception e) {
     throw new MojoExecutionException("error execute maven-warsync-plugin:eclipse", e);
   }
 }
Ejemplo n.º 8
0
  /** {@inheritDoc} */
  @Override
  public void execute() throws MojoExecutionException {

    // only ever interested in war and ear projects. silently ignore other projects.
    final String ext = project.getPackaging();
    if ("war".equals(ext) || "ear".equals(ext)) {

      pushFields();

      final Wagon wagon = getWagon();
      if (null != wagon) {

        try {
          executeServerDeploy(wagon);

        } finally {
          try {
            wagon.disconnect();

          } catch (ConnectionException ex) {
            getLog().error(ex);
            throw new MojoExecutionException("repository wagon not disconnected", ex);
          }
        }

      } else {

        executeLocalDeploy();
      }
    }
  }
Ejemplo n.º 9
0
  private List<Dependency> addWebDependencies(
      String appfuseVersion, List<Dependency> newDependencies, String webFramework) {
    // Add dependencies from appfuse-common-web
    newDependencies = addModuleDependencies(newDependencies, "web", "web");

    Double appfuseVersionAsDouble =
        new Double(appfuseVersion.substring(0, appfuseVersion.lastIndexOf(".")));

    getLog().debug("Detected AppFuse version: " + appfuseVersionAsDouble);

    if (isAppFuse() && appfuseVersionAsDouble < 2.1) {

      // Add dependencies from appfuse-common-web
      newDependencies = addModuleDependencies(newDependencies, "web-common", "web/common");

      // newDependencies = addModuleDependencies(newDependencies, webFramework, "web/" +
      // webFramework);
    }

    // modular archetypes still seem to need these - todo: figure out why
    if (isAppFuse() && project.getPackaging().equals("war") && project.hasParent()) {
      newDependencies = addModuleDependencies(newDependencies, "web-common", "web/common");

      newDependencies = addModuleDependencies(newDependencies, webFramework, "web/" + webFramework);
    }
    return newDependencies;
  }
 /**
  * Deploy the apk built with the current projects to all attached devices and emulators. Skips
  * other projects in a multi-module build without terminating.
  *
  * @throws MojoExecutionException
  * @throws MojoFailureException
  */
 protected void deployBuiltApk() throws MojoExecutionException, MojoFailureException {
   if (project.getPackaging().equals(APK)) {
     File apkFile = new File(targetDirectory, finalName + "." + APK);
     deployApk(apkFile);
   } else {
     getLog().info("Project packaging is not apk, skipping deployment.");
   }
 }
Ejemplo n.º 11
0
  private void loadPomProject() {

    if (null == pomProject) {
      pomProject = project;
      do {
        pomProject = pomProject.getParent();
      } while (!"pom".equals(pomProject.getPackaging()));
    }
  }
 public void execute() throws MojoExecutionException {
   Log log = getLog();
   if (skip) {
     log.debug("Skipping collection of artifacts");
     return;
   }
   File targetDirectoryFile = new File(targetDirectoryName);
   File outputDir;
   if (targetDirectoryFile.isAbsolute()) {
     outputDir = targetDirectoryFile;
     if (!outputDir.exists()) {
       throw new MojoExecutionException(
           "Specified targetDirectoryName " + targetDirectoryName + " doesn't exists");
     }
     if (!outputDir.isDirectory()) {
       throw new MojoExecutionException(
           "Specified targetDirectoryName " + targetDirectoryName + " is not a directory");
     }
   } else {
     MavenProject parent = getParent(project);
     while (parent != null) {
       MavenProject tmp = getParent(parent);
       if (tmp == null) {
         break;
       }
       parent = tmp;
     }
     if (parent == null) {
       log.debug("Parent not found, nothing to do");
       return;
     }
     outputDir = new File(parent.getBuild().getDirectory(), targetDirectoryName);
     log.debug("Found parent " + parent.getName() + ", output dir: " + outputDir);
   }
   if (project.getPackaging().equals(targetPackaging)) {
     log.debug("Found requested artifact for project " + project.getName());
     try {
       FileUtils.mkdir(outputDir.getCanonicalPath());
     } catch (IOException e) {
       throw new MojoExecutionException(
           "Unable to create directory " + outputDir.getAbsolutePath(), e);
     }
     File artifactFile = project.getArtifact().getFile();
     File destination = new File(outputDir, artifactFile.getName());
     try {
       log.info(
           "Copying artifact "
               + artifactFile.getCanonicalPath()
               + " to "
               + destination.getCanonicalPath());
       FileUtils.copyFile(artifactFile, destination);
     } catch (IOException e) {
       throw new MojoExecutionException("Unable to copy file", e);
     }
   }
 }
 /**
  * Creates a list of all artifacts for the build.
  *
  * @return a list of all artifacts for the build including the attached ones.
  */
 List<Artifact> getListOfArtifacts() {
   final MavenProject project = getProject();
   final List<Artifact> artifacts = new ArrayList<Artifact>(project.getAttachedArtifacts());
   final String packaging = project.getPackaging();
   // POMs return null as their artifact, which will crash the transformation lateron.
   if (!"pom".equals(packaging)) {
     artifacts.add(project.getArtifact());
   }
   return artifacts;
 }
Ejemplo n.º 14
0
 private MavenProject getTestSuite(String symbolicName) {
   for (MavenProject otherProject : session.getProjects()) {
     TychoProject projectType = projectTypes.get(otherProject.getPackaging());
     if (projectType != null
         && projectType
             .getArtifactKey(DefaultReactorProject.adapt(otherProject))
             .getId()
             .equals(symbolicName)) {
       return otherProject;
     }
   }
   return null;
 }
  public void execute() throws MojoExecutionException {
    if ("pom".equalsIgnoreCase(project.getPackaging())) {
      return;
    }

    try {
      executeWithExceptionsHandled();
    } catch (Exception e1) {
      getLog().error("error on execute: " + e1.getMessage());
      if (failOnError) {
        throw new MojoExecutionException(e1.getMessage());
      }
    }
  }
Ejemplo n.º 16
0
  public void testAccessRestrictionCompilationError() throws Exception {
    File basedir = getBasedir("projects/accessrules");
    List<MavenProject> projects = getSortedProjects(basedir, null);

    try {
      for (MavenProject project : projects) {
        if (!"pom".equals(project.getPackaging())) {
          getMojo(projects, project).execute();
        }
      }
      fail("Restricted package access");
    } catch (MojoFailureException e) {
      assertTrue(e.getLongMessage().contains("P001Impl is not accessible"));
    }
  }
Ejemplo n.º 17
0
  public void execute() throws MojoExecutionException, MojoFailureException {
    if (!"play".equals(project.getPackaging())) {
      return;
    }

    try {
      internalExecute();

      if (project.getArtifact().getFile() == null) {
        setBasedirAsArtifactFile();
      }
    } catch (IOException e) {
      throw new MojoExecutionException("?", e);
    }
  }
  private boolean isAllowConflictingDependencies(
      MavenProject project, TargetPlatformConfiguration configuration) {
    String packaging = project.getPackaging();

    if (org.eclipse.tycho.ArtifactKey.TYPE_ECLIPSE_UPDATE_SITE.equals(packaging)
        || org.eclipse.tycho.ArtifactKey.TYPE_ECLIPSE_FEATURE.equals(packaging)) {
      Boolean allow = configuration.getAllowConflictingDependencies();
      if (allow != null) {
        return allow.booleanValue();
      }
    }

    // conflicting dependencies do not make sense for products and bundles
    return false;
  }
  public IPath publishModuleFull(IProgressMonitor monitor) throws CoreException {
    IPath retval = null;

    if (runMavenGoal(getProject(), monitor)) {
      final IMavenProjectFacade projectFacade = MavenUtil.getProjectFacade(getProject(), monitor);
      final MavenProject mavenProject = projectFacade.getMavenProject(monitor);
      final String targetFolder = mavenProject.getBuild().getDirectory();
      final String targetWar =
          mavenProject.getBuild().getFinalName() + "." + mavenProject.getPackaging();

      retval = new Path(targetFolder).append(targetWar);
    }

    return retval;
  }
  private boolean shouldProcess(MavenProject project) {
    if (project == null) {
      return false;
    }

    boolean process = true;

    if (ignorePomModules && "pom".equals(project.getPackaging())) {
      process = false;
    } else if (!excludes.isEmpty() && matchAny(project.getArtifactId(), excludes)) {
      process = false;
    } else if (!includes.isEmpty() && matchAny(project.getArtifactId(), includes)) {
      process = true;
    }

    return process;
  }
Ejemplo n.º 21
0
  public void execute() throws MojoExecutionException, MojoFailureException {
    String pkg = project.getPackaging();
    if (pkg != null && pkg.equals("pom")) return; // skip POM modules

    Generator g =
        new Generator(
            outputDirectory,
            new Reporter() {
              public void debug(String msg) {
                getLog().debug(msg);
              }
            });

    for (Resource res : (List<Resource>) project.getResources()) {
      File baseDir = new File(res.getDirectory());
      if (!baseDir.exists())
        continue; // this happens for example when POM inherits the default resource folder but no
                  // such folder exists.

      FileSet fs = new FileSet();
      fs.setDir(baseDir);
      for (String name : (List<String>) res.getIncludes()) fs.createInclude().setName(name);
      for (String name : (List<String>) res.getExcludes()) fs.createExclude().setName(name);

      for (String relPath : fs.getDirectoryScanner(new Project()).getIncludedFiles()) {
        File f = new File(baseDir, relPath);
        if (!f.getName().endsWith(".properties") || f.getName().contains("_")) continue;
        if (fileMask != null && !f.getName().equals(fileMask)) continue;

        try {
          g.generate(f, relPath);
        } catch (IOException e) {
          throw new MojoExecutionException("Failed to generate a class from " + f, e);
        }
      }
    }

    try {
      g.build();
    } catch (IOException e) {
      throw new MojoExecutionException("Failed to generate source files", e);
    }

    project.addCompileSourceRoot(outputDirectory.getAbsolutePath());
  }
 private boolean hasJarPackagingExecution() {
   if (AbstractUsingBundleListMojo.JAR.equals(project.getPackaging())) {
     return true;
   } else {
     for (PluginExecution execution : plugin.getExecutions()) {
       if (execution.getGoals().contains("prepare-package")) {
         Xpp3Dom executionConfig = (Xpp3Dom) execution.getConfiguration();
         if (executionConfig != null) {
           Xpp3Dom packagingConfig = executionConfig.getChild("packaging");
           if (packagingConfig != null
               && AbstractUsingBundleListMojo.JAR.equals(packagingConfig.getValue())) {
             return true;
           }
         }
       }
     }
     return false;
   }
 }
Ejemplo n.º 23
0
  private void createDevProperties(
      boolean includeReactorProjects, List<ReactorProject> reactorProjects)
      throws MojoExecutionException {
    Properties dev = new Properties();

    if (includeReactorProjects) {
      // this is needed for IDE integration, where we want to use reactor project output folders
      dev.put("@ignoredot@", "true");
      for (ReactorProject otherProject : reactorProjects) {
        if ("eclipse-test-plugin".equals(otherProject.getPackaging())
            || "eclipse-plugin".equals(otherProject.getPackaging())) {
          TychoProject projectType = projectTypes.get(otherProject.getPackaging());
          dev.put(
              projectType.getArtifactKey(otherProject).getId(),
              getBuildOutputDirectories(otherProject));
        }
      }
    }

    ReactorProject reactorProject = DefaultReactorProject.adapt(project);

    TychoProject projectType = projectTypes.get(project.getPackaging());
    dev.put(
        projectType.getArtifactKey(reactorProject).getId(),
        getBuildOutputDirectories(reactorProject));

    try {
      OutputStream os = new BufferedOutputStream(new FileOutputStream(devProperties));
      try {
        dev.store(os, null);
      } finally {
        os.close();
      }
    } catch (IOException e) {
      throw new MojoExecutionException("Can't create osgi dev properties file", e);
    }
  }
 boolean isPomProject(@NotNull MavenProject project) {
   return project.getPackaging().equalsIgnoreCase("pom");
 }
  private SurefireBooter constructSurefireBooter()
      throws MojoExecutionException, MojoFailureException {
    SurefireBooter surefireBooter = new SurefireBooter();

    Artifact surefireArtifact =
        (Artifact) pluginArtifactMap.get("org.apache.maven.surefire:surefire-booter");
    if (surefireArtifact == null) {
      throw new MojoExecutionException(
          "Unable to locate surefire-booter in the list of plugin artifacts");
    }

    surefireArtifact
        .isSnapshot(); // TODO: this is ridiculous, but it fixes getBaseVersion to be -SNAPSHOT if
    // needed

    Artifact junitArtifact;
    Artifact testNgArtifact;
    try {
      addArtifact(surefireBooter, surefireArtifact);

      junitArtifact = (Artifact) projectArtifactMap.get(junitArtifactName);
      // SUREFIRE-378, junit can have an alternate artifact name
      if (junitArtifact == null && "junit:junit".equals(junitArtifactName)) {
        junitArtifact = (Artifact) projectArtifactMap.get("junit:junit-dep");
      }

      // TODO: this is pretty manual, but I'd rather not require the plugin > dependencies section
      // right now
      testNgArtifact = (Artifact) projectArtifactMap.get(testNGArtifactName);

      if (testNgArtifact != null) {
        VersionRange range = VersionRange.createFromVersionSpec("[4.7,)");
        if (!range.containsVersion(new DefaultArtifactVersion(testNgArtifact.getVersion()))) {
          throw new MojoFailureException(
              "TestNG support requires version 4.7 or above. You have declared version "
                  + testNgArtifact.getVersion());
        }

        convertTestNGParameters();

        if (this.testClassesDirectory != null) {
          properties.setProperty("testng.test.classpath", testClassesDirectory.getAbsolutePath());
        }

        addArtifact(surefireBooter, testNgArtifact);

        // The plugin uses a JDK based profile to select the right testng. We might be explicity
        // using a
        // different one since its based on the source level, not the JVM. Prune using the filter.
        addProvider(
            surefireBooter, "surefire-testng", surefireArtifact.getBaseVersion(), testNgArtifact);
      } else if (junitArtifact != null && junitArtifact.getBaseVersion().startsWith("4")) {
        addProvider(surefireBooter, "surefire-junit4", surefireArtifact.getBaseVersion(), null);
      } else {
        // add the JUnit provider as default - it doesn't require JUnit to be present,
        // since it supports POJO tests.
        addProvider(surefireBooter, "surefire-junit", surefireArtifact.getBaseVersion(), null);
      }
    } catch (ArtifactNotFoundException e) {
      throw new MojoExecutionException(
          "Unable to locate required surefire provider dependency: " + e.getMessage(), e);
    } catch (InvalidVersionSpecificationException e) {
      throw new MojoExecutionException(
          "Error determining the TestNG version requested: " + e.getMessage(), e);
    } catch (ArtifactResolutionException e) {
      throw new MojoExecutionException(
          "Error to resolving surefire provider dependency: " + e.getMessage(), e);
    }

    if (suiteXmlFiles != null && suiteXmlFiles.length > 0 && test == null) {
      if (testNgArtifact == null) {
        throw new MojoExecutionException(
            "suiteXmlFiles is configured, but there is no TestNG dependency");
      }

      // TODO: properties should be passed in here too
      surefireBooter.addTestSuite(
          "org.apache.maven.surefire.testng.TestNGXmlTestSuite",
          new Object[] {
            suiteXmlFiles,
            testSourceDirectory.getAbsolutePath(),
            testNgArtifact.getVersion(),
            testNgArtifact.getClassifier(),
            properties,
            reportsDirectory
          });
    } else {
      List includeList;
      List excludeList;

      if (test != null) {
        // Check to see if we are running a single test. The raw parameter will
        // come through if it has not been set.

        // FooTest -> **/FooTest.java

        includeList = new ArrayList();

        excludeList = new ArrayList();

        if (failIfNoTests == null) {
          failIfNoTests = Boolean.TRUE;
        }

        String[] testRegexes = StringUtils.split(test, ",");

        for (int i = 0; i < testRegexes.length; i++) {
          String testRegex = testRegexes[i];
          if (testRegex.endsWith(".java")) {
            testRegex = testRegex.substring(0, testRegex.length() - 5);
          }
          // Allow paths delimited by '.' or '/'
          testRegex = testRegex.replace('.', '/');
          includeList.add("**/" + testRegex + ".java");
        }
      } else {
        includeList = this.includes;

        excludeList = this.excludes;

        // defaults here, qdox doesn't like the end javadoc value
        // Have to wrap in an ArrayList as surefire expects an ArrayList instead of a List for some
        // reason
        if (includeList == null || includeList.size() == 0) {
          includeList =
              new ArrayList(
                  Arrays.asList(
                      new String[] {"**/Test*.java", "**/*Test.java", "**/*TestCase.java"}));
        }
        if (excludeList == null || excludeList.size() == 0) {
          excludeList = new ArrayList(Arrays.asList(new String[] {"**/*$*"}));
        }
      }

      if (testNgArtifact != null) {
        surefireBooter.addTestSuite(
            "org.apache.maven.surefire.testng.TestNGDirectoryTestSuite",
            new Object[] {
              testClassesDirectory,
              includeList,
              excludeList,
              testSourceDirectory.getAbsolutePath(),
              testNgArtifact.getVersion(),
              testNgArtifact.getClassifier(),
              properties,
              reportsDirectory
            });
      } else {
        String junitDirectoryTestSuite;
        if (junitArtifact != null
            && junitArtifact.getBaseVersion() != null
            && junitArtifact.getBaseVersion().startsWith("4")) {
          junitDirectoryTestSuite = "org.apache.maven.surefire.junit4.JUnit4DirectoryTestSuite";
        } else {
          junitDirectoryTestSuite = "org.apache.maven.surefire.junit.JUnitDirectoryTestSuite";
        }

        // fall back to JUnit, which also contains POJO support. Also it can run
        // classes compiled against JUnit since it has a dependency on JUnit itself.
        surefireBooter.addTestSuite(
            junitDirectoryTestSuite, new Object[] {testClassesDirectory, includeList, excludeList});
      }
    }

    // ----------------------------------------------------------------------
    //
    // ----------------------------------------------------------------------

    getLog().debug("Test Classpath :");

    // Check if we need to add configured classes/test classes directories here.
    // If they are configured, we should remove the default to avoid conflicts.
    if (!project.getBuild().getOutputDirectory().equals(classesDirectory.getAbsolutePath())) {
      classpathElements.remove(project.getBuild().getOutputDirectory());
      classpathElements.add(classesDirectory.getAbsolutePath());
    }
    if (!project
        .getBuild()
        .getTestOutputDirectory()
        .equals(testClassesDirectory.getAbsolutePath())) {
      classpathElements.remove(project.getBuild().getTestOutputDirectory());
      classpathElements.add(testClassesDirectory.getAbsolutePath());
    }

    for (Iterator i = classpathElements.iterator(); i.hasNext(); ) {
      String classpathElement = (String) i.next();

      getLog().debug("  " + classpathElement);

      surefireBooter.addClassPathUrl(classpathElement);
    }

    Toolchain tc = getToolchain();

    if (tc != null) {
      getLog().info("Toolchain in surefire-plugin: " + tc);
      if (ForkConfiguration.FORK_NEVER.equals(forkMode)) {
        forkMode = ForkConfiguration.FORK_ONCE;
      }
      if (jvm != null) {
        getLog().warn("Toolchains are ignored, 'executable' parameter is set to " + jvm);
      } else {
        jvm = tc.findTool("java"); // NOI18N
      }
    }

    if (additionalClasspathElements != null) {
      for (Iterator i = additionalClasspathElements.iterator(); i.hasNext(); ) {
        String classpathElement = (String) i.next();

        getLog().debug("  " + classpathElement);

        surefireBooter.addClassPathUrl(classpathElement);
      }
    }

    // ----------------------------------------------------------------------
    // Forking
    // ----------------------------------------------------------------------

    ForkConfiguration fork = new ForkConfiguration();

    // DUNS
    if (project.getPackaging().equals("nar") || (getNarArtifacts().size() > 0)) {
      forkMode = "pertest";
    }

    fork.setForkMode(forkMode);

    processSystemProperties(!fork.isForking());

    if (getLog().isDebugEnabled()) {
      showMap(systemProperties, "system property");
    }

    if (fork.isForking()) {
      useSystemClassLoader = useSystemClassLoader == null ? Boolean.TRUE : useSystemClassLoader;
      fork.setUseSystemClassLoader(useSystemClassLoader.booleanValue());
      fork.setUseManifestOnlyJar(useManifestOnlyJar);

      fork.setSystemProperties(systemProperties);

      if ("true".equals(debugForkedProcess)) {
        debugForkedProcess =
            "-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005";
      }

      fork.setDebugLine(debugForkedProcess);

      if (jvm == null || "".equals(jvm)) {
        // use the same JVM as the one used to run Maven (the "java.home" one)
        jvm = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
        getLog().debug("Using JVM: " + jvm);
      }

      fork.setJvmExecutable(jvm);

      if (workingDirectory != null) {
        fork.setWorkingDirectory(workingDirectory);
      } else {
        fork.setWorkingDirectory(basedir);
      }

      // BEGINDUNS
      if (argLine == null) {
        argLine = "";
      }

      StringBuffer javaLibraryPath = new StringBuffer();
      if (testJNIModule()) {
        // Add libraries to java.library.path for testing
        File jniLibraryPathEntry =
            getLayout()
                .getLibDirectory(
                    getTargetDirectory(),
                    getMavenProject().getArtifactId(),
                    getMavenProject().getVersion(),
                    getAOL().toString(),
                    Library.JNI);
        if (jniLibraryPathEntry.exists()) {
          getLog().debug("Adding library directory to java.library.path: " + jniLibraryPathEntry);
          if (javaLibraryPath.length() > 0) {
            javaLibraryPath.append(File.pathSeparator);
          }
          javaLibraryPath.append(jniLibraryPathEntry);
        }

        File sharedLibraryPathEntry =
            getLayout()
                .getLibDirectory(
                    getTargetDirectory(),
                    getMavenProject().getArtifactId(),
                    getMavenProject().getVersion(),
                    getAOL().toString(),
                    Library.SHARED);
        if (sharedLibraryPathEntry.exists()) {
          getLog()
              .debug("Adding library directory to java.library.path: " + sharedLibraryPathEntry);
          if (javaLibraryPath.length() > 0) {
            javaLibraryPath.append(File.pathSeparator);
          }
          javaLibraryPath.append(sharedLibraryPathEntry);
        }

        // add jar file to classpath, as one may want to read a
        // properties file for artifactId and version
        String narFile = "target/" + project.getArtifactId() + "-" + project.getVersion() + ".jar";
        getLog().debug("Adding to surefire test classpath: " + narFile);
        surefireBooter.addClassPathUrl(narFile);
      }

      List dependencies =
          getNarArtifacts(); // TODO: get seems heavy, not sure if we can push this up to before the
                             // fork to use it multiple times.
      for (Iterator i = dependencies.iterator(); i.hasNext(); ) {
        NarArtifact dependency = (NarArtifact) i.next();
        // FIXME this should be overridable
        // NarInfo info = dependency.getNarInfo();
        // String binding = info.getBinding(getAOL(), Library.STATIC);
        // NOTE: fixed to shared, jni
        String[] bindings = {Library.SHARED, Library.JNI};
        for (int j = 0; j < bindings.length; j++) {
          String binding = bindings[j];
          if (!binding.equals(Library.STATIC)) {
            File depLibPathEntry =
                getLayout()
                    .getLibDirectory(
                        getUnpackDirectory(),
                        dependency.getArtifactId(),
                        dependency.getVersion(),
                        getAOL().toString(),
                        binding);
            if (depLibPathEntry.exists()) {
              getLog()
                  .debug("Adding dependency directory to java.library.path: " + depLibPathEntry);
              if (javaLibraryPath.length() > 0) {
                javaLibraryPath.append(File.pathSeparator);
              }
              javaLibraryPath.append(depLibPathEntry);
            }
          }
        }
      }

      // add final javalibrary path
      if (javaLibraryPath.length() > 0) {
        // NOTE java.library.path only works for the jni lib itself, and
        // not for its dependent shareables.
        // NOTE: java.library.path does not work with arguments with
        // spaces as
        // SureFireBooter splits the line in parts and then quotes
        // it wrongly
        NarUtil.addLibraryPathToEnv(javaLibraryPath.toString(), environmentVariables, getOS());
      }

      // necessary to find WinSxS
      if (getOS().equals(OS.WINDOWS)) {
        environmentVariables.put(
            "SystemRoot", NarUtil.getEnv("SystemRoot", "SystemRoot", "C:\\Windows"));
      }
      // ENDDUNS

      fork.setArgLine(argLine);

      fork.setEnvironmentVariables(environmentVariables);

      if (getLog().isDebugEnabled()) {
        showMap(environmentVariables, "environment variable");

        fork.setDebug(true);
      }

      if (argLine != null) {
        List args = Arrays.asList(argLine.split(" "));
        if (args.contains("-da") || args.contains("-disableassertions")) {
          enableAssertions = false;
        }
      }
    }

    surefireBooter.setFailIfNoTests(failIfNoTests == null ? false : failIfNoTests.booleanValue());

    surefireBooter.setForkedProcessTimeoutInSeconds(forkedProcessTimeoutInSeconds);

    surefireBooter.setRedirectTestOutputToFile(redirectTestOutputToFile);

    surefireBooter.setForkConfiguration(fork);

    surefireBooter.setChildDelegation(childDelegation);

    surefireBooter.setEnableAssertions(enableAssertions);

    surefireBooter.setReportsDirectory(reportsDirectory);

    addReporters(surefireBooter, fork.isForking());

    return surefireBooter;
  }
Ejemplo n.º 26
0
  public void execute() throws MojoExecutionException, MojoFailureException {
    // http://issues.appfuse.org/browse/APF-1025
    System.setProperty("file.encoding", "UTF-8");

    // If appfuse.version is specified as a property, and not a SNAPSHOT, use it for the tag
    String appfuseVersion = project.getProperties().getProperty("appfuse.version");

    if ((appfuseVersion != null) && !appfuseVersion.endsWith("SNAPSHOT") && tag.equals("trunk/")) {
      tag = "tags/APPFUSE_" + appfuseVersion.toUpperCase().replaceAll("-", "_") + "/";
      // APF-1168: Allow milestone and release candidates
      if (tag.contains("_M")) {
        tag = tag.replace("_M", "-M");
      } else if (tag.contains("_R")) {
        tag = tag.replace("_R", "-R");
      }
    }

    String daoFramework = project.getProperties().getProperty("dao.framework");

    if (daoFramework == null) {
      log("No dao.framework property specified, defaulting to 'hibernate'");
    }

    String webFramework = project.getProperties().getProperty("web.framework");

    boolean modular = (project.getPackaging().equals("pom") && !project.hasParent());
    if (project.getPackaging().equals("jar")
        || (project.getPackaging().equals("war") && !project.hasParent())) {
      // export data-common
      log("Installing source from data-common module...");
      export("data/common/src", (modular) ? "core/src" : destinationDirectory);

      // export persistence framework
      log("Installing source from " + daoFramework + " module...");
      export("data/" + daoFramework + "/src", (modular) ? "core/src" : destinationDirectory);

      // export service module
      log("Installing source from service module...");
      export("service/src", (modular) ? "core/src" : destinationDirectory);

      // move Base*TestCase to test directory
      moveFiles(
          (modular) ? "core/src/main" : destinationDirectory + "/main",
          (modular) ? "core/src/test" : destinationDirectory + "/test",
          "**/Base*TestCase.java");

      // delete dao.framework related files from test directory
      deleteFile("test/resources/hibernate.cfg.xml");
      deleteFile("test/resources/META-INF");
      deleteFile("test/resources/sql-map-config.xml");

      // If JPA, delete hibernate.cfg.xml b/c it will cause issues when
      // using jpaconfiguration with the hibernate3-maven-plugin
      if ("jpa".equalsIgnoreCase(daoFramework)) {
        deleteFile("main/resources/hibernate.cfg.xml");
      }
    }

    // it's OK if a project created with appfuse-ws doesn't have a web framework defined
    // currently, a project with appfuse-ws can be identified by enunciate
    boolean isWebServicesProject = false;
    for (Object pluginArtifact : project.getPluginArtifacts()) {
      if (((Artifact) pluginArtifact).getArtifactId().contains("enunciate")) {
        isWebServicesProject = true;
        break;
      }
    }

    if (project.getPackaging().equalsIgnoreCase("war")) {

      if (webFramework == null && !isWebServicesProject) {
        getLog()
            .error(
                "The web.framework property is not specified - please modify your pom.xml to add "
                    + " this property. For example: <web.framework>struts</web.framework>.");
        throw new MojoExecutionException(
            "No web.framework property specified, please modify pom.xml to add it.");
      }

      if (project.hasParent()) {
        // copy jdbc.properties to core/src/test/resources
        // FileUtils.copyFileToDirectory(new File("src/main/resources/jdbc.properties"), new
        // File("../core/src/test/resources"));

        // delete hibernate, ibatis and jpa files from web project
        deleteFile("main/resources/hibernate.cfg.xml");
        deleteFile("main/resources/META-INF");
        deleteFile("main/resources/sql-map-config.xml");

        // there's a jdbc.properties in test/resources that shouldn't be there
        deleteFile("test/resources/jdbc.properties");
      } else if (!isAppFuse()) {
        // there's a jdbc.properties in test/resources that shouldn't be there
        deleteFile("test/resources/jdbc.properties");
      }
    }

    log("Source successfully exported, modifying pom.xml...");

    List dependencies = project.getOriginalModel().getDependencies();
    List<Dependency> newDependencies = new ArrayList<Dependency>();

    // remove all appfuse dependencies
    for (Object dependency : dependencies) {
      Dependency dep = (Dependency) dependency;

      if (!dep.getGroupId().equals(APPFUSE_GROUP_ID)) {
        newDependencies.add(dep);
      }
    }

    if (!project.getPackaging().equals("pom") && !project.hasParent()) {

      // add dependencies from root appfuse pom
      newDependencies = addModuleDependencies(newDependencies, "root", "");

      // Add dependencies from appfuse-data
      newDependencies = addModuleDependencies(newDependencies, "data", "data");

      // Add dependencies from appfuse-data-common
      newDependencies = addModuleDependencies(newDependencies, "data-common", "data/common");

      // Add dependencies from appfuse-${dao.framework}
      newDependencies =
          addModuleDependencies(newDependencies, daoFramework, "data/" + daoFramework);

      // Add dependencies from appfuse-service
      newDependencies = addModuleDependencies(newDependencies, "service", "service");

      if (!isWebServicesProject && project.getPackaging().equals("war")) {
        newDependencies = addWebDependencies(appfuseVersion, newDependencies, webFramework);
      }

      createFullSourcePom(newDependencies);
    } else {
      if (project.getPackaging().equals("pom")) {
        // add dependencies from root appfuse pom
        newDependencies = addModuleDependencies(newDependencies, "root", "");

        createFullSourcePom(newDependencies);
      }

      if (project.getPackaging().equals("jar")) {
        newDependencies.clear();

        // Add dependencies from appfuse-data
        newDependencies = addModuleDependencies(newDependencies, "data", "data");

        // Add dependencies from appfuse-data-common
        newDependencies = addModuleDependencies(newDependencies, "data-common", "data/common");

        // Add dependencies from appfuse-${dao.framework}
        newDependencies =
            addModuleDependencies(newDependencies, daoFramework, "data/" + daoFramework);

        // Add dependencies from appfuse-service
        newDependencies = addModuleDependencies(newDependencies, "service", "service");

        createFullSourcePom(newDependencies);
      }

      if (project.getPackaging().equals("war")) {
        newDependencies.clear();

        newDependencies = addWebDependencies(appfuseVersion, newDependencies, webFramework);

        createFullSourcePom(newDependencies);
      }
    }
  }
Ejemplo n.º 27
0
  private void createFullSourcePom(List<Dependency> newDependencies) throws MojoFailureException {
    // Change spring-test and jmock dependencies to use <optional>true</option> instead of
    // <scope>test</scope>.
    // This is necessary because Base*TestCase classes are in src/main/java. If we move these
    // classes to their
    // own test module, this will no longer be necessary. For the first version of this mojo, it
    // seems easier
    // to follow the convention used in AppFuse rather than creating a test module and changing all
    // modules to
    // depend on it.

    // create properties based on dependencies while we're at it
    Set<String> projectProperties = new TreeSet<String>();

    for (Dependency dep : newDependencies) {
      if (dep.getArtifactId().equals("spring-test")
          || dep.getArtifactId().contains("jmock")
          || dep.getArtifactId().equals("junit")
          || dep.getArtifactId().equals("shale-test")) {
        dep.setOptional(true);
        dep.setScope(null);
      }
      String version = dep.getVersion();
      // trim off ${}
      if (version.startsWith("${")) {
        version = version.substring(2);
      }

      if (version.endsWith("}")) {
        version = version.substring(0, version.length() - 1);
      }
      projectProperties.add(version);
    }

    // add core as a dependency for modular wars
    if (project.getPackaging().equals("war") && project.hasParent()) {
      Dependency core = new Dependency();
      core.setGroupId("${project.parent.groupId}");
      core.setArtifactId("core");
      core.setVersion("${project.parent.version}");
      newDependencies.add(core);

      // workaround for JSF requiring JSP 2.1 - this is a true hack
      if (project.getProperties().getProperty("web.framework").equals("jsf")) {
        Dependency jsp21 = new Dependency();
        jsp21.setGroupId("javax.servlet.jsp");
        jsp21.setArtifactId("jsp-api");
        jsp21.setVersion("${jsp.version}");
        jsp21.setScope("provided");
        newDependencies.add(jsp21);

        // replace jsp.version property as well
        project.getOriginalModel().getProperties().setProperty("jsp.version", "2.1");
      }
    }

    Collections.sort(newDependencies, new BeanComparator("groupId"));

    project.getOriginalModel().setDependencies(newDependencies);

    Properties currentProperties = project.getOriginalModel().getProperties();

    Set<String> currentKeys = new LinkedHashSet<String>();
    for (Object key : currentProperties.keySet()) {
      currentKeys.add((String) key);
    }

    StringBuffer sortedProperties = new StringBuffer();

    Properties appfuseProperties = getAppFuseProperties();

    // holder for properties - stored in ThreadLocale
    Map<String, String> propertiesForPom = new LinkedHashMap<String, String>();

    for (String key : projectProperties) {
      // don't add property if it already exists in project
      if (!currentKeys.contains(key)) {
        String value = appfuseProperties.getProperty(key);

        // this happens when the version number is hard-coded
        if (value == null) {
          continue;
        }

        // hack for Tapestry depending on commons-pool (a.k.a. commons-dbcp 1.2.2)
        if ("tapestry".equals(project.getProperties().getProperty("web.framework"))
            && key.equals("commons.dbcp.version")) {
          value = "1.2.2";
        }

        if (value.contains("&amp;")) {
          value = "<![CDATA[" + value + "]]>";
        }

        sortedProperties
            .append("        <")
            .append(key)
            .append(">")
            .append(value)
            .append("</")
            .append(key)
            .append(">" + "\n");
        propertiesForPom.put(key, value);
      }
    }

    if (project.getPackaging().equals("pom") || project.hasParent()) {
      // store sorted properties in a thread local for later retrieval
      Map<String, String> properties = new LinkedHashMap<String, String>();
      if (propertiesContextHolder.get() != null) {
        properties = (LinkedHashMap) propertiesContextHolder.get();
      }

      for (String key : propertiesForPom.keySet()) {
        if (!properties.containsKey(key)) {
          properties.put(key, propertiesForPom.get(key));
        }
      }

      propertiesContextHolder.set(properties);
    }

    StringWriter writer = new StringWriter();

    try {
      project.writeOriginalModel(writer);

      File pom = new File("pom-fullsource.xml");

      if (pom.exists()) {
        pom.delete();
      }

      FileWriter fw = new FileWriter(pom);
      fw.write(writer.toString());
      fw.flush();
      fw.close();
    } catch (IOException ex) {
      getLog().error("Unable to create pom-fullsource.xml: " + ex.getMessage(), ex);
      throw new MojoFailureException(ex.getMessage());
    }

    log("Updated dependencies in pom.xml...");

    // I tried to use regex here, but couldn't get it to work - going with the old fashioned way
    // instead
    String pomXml = writer.toString();
    int startTag = pomXml.indexOf("\n  <dependencies>");

    String dependencyXml = pomXml.substring(startTag, pomXml.indexOf("</dependencies>", startTag));
    // change 2 spaces to 4
    dependencyXml = dependencyXml.replaceAll("  ", "    ");
    dependencyXml =
        "\n    <!-- Dependencies calculated by AppFuse when running full-source plugin -->"
            + dependencyXml;

    try {
      String packaging = project.getPackaging();
      String pathToPom = "pom.xml";
      if (project.hasParent()) {
        if (packaging.equals("jar")) {
          pathToPom = "core/" + pathToPom;
        } else if (packaging.equals("war")) {
          pathToPom = "web/" + pathToPom;
        }
      }

      String originalPom = FileUtils.readFileToString(new File(pathToPom), "UTF-8");
      // replace tabs with spaces (in case user has changed their pom.xml
      originalPom = originalPom.replace("\t", "    ");
      startTag = originalPom.indexOf("\n    <dependencies>");

      StringBuffer sb = new StringBuffer();
      sb.append(originalPom.substring(0, startTag));
      sb.append(dependencyXml);
      sb.append(originalPom.substring(originalPom.indexOf("</dependencies>", startTag)));

      String adjustedPom = sb.toString();

      // Calculate properties and add them to pom if not a modular project - otherwise properties
      // are added
      // near the end of this method from a threadlocal
      if (!project.getPackaging().equals("pom") && !project.hasParent()) {
        adjustedPom = addPropertiesToPom(adjustedPom, sortedProperties);
      }

      adjustedPom = adjustLineEndingsForOS(adjustedPom);

      FileUtils.writeStringToFile(
          new File(pathToPom), adjustedPom, "UTF-8"); // was pomWithProperties
    } catch (IOException ex) {
      getLog().error("Unable to write to pom.xml: " + ex.getMessage(), ex);
      throw new MojoFailureException(ex.getMessage());
    }

    boolean renamePackages = true;
    if (System.getProperty("renamePackages") != null) {
      renamePackages = Boolean.valueOf(System.getProperty("renamePackages"));
    }

    if (renamePackages && !project.getPackaging().equals("pom")) {
      log("Renaming packages to '" + project.getGroupId() + "'...");
      RenamePackages renamePackagesTool = new RenamePackages(project.getGroupId());
      if (project.hasParent()) {
        if (project.getPackaging().equals("jar")) {
          renamePackagesTool.setBaseDir("core/src");
        } else {
          renamePackagesTool.setBaseDir("web/src");
        }
      }

      renamePackagesTool.execute();
    }

    // when performing full-source on a modular project, add the properties to the root pom.xml at
    // the end
    if (project.getPackaging().equals("war") && project.hasParent()) {
      // store sorted properties in a thread local for later retrieval
      Map properties = propertiesContextHolder.get();
      // alphabetize the properties by key
      Set<String> propertiesToAdd = new TreeSet<String>(properties.keySet());

      StringBuffer calculatedProperties = new StringBuffer();

      for (String key : propertiesToAdd) {
        // don't add property if it already exists in project
        Set<Object> keysInProject = project.getParent().getOriginalModel().getProperties().keySet();
        if (!keysInProject.contains(key)) {
          String value = getAppFuseProperties().getProperty(key);

          if (value.contains("&amp;")) {
            value = "<![CDATA[" + value + "]]>";
          }

          calculatedProperties.append("        <");
          calculatedProperties.append(key);
          calculatedProperties.append(">");
          calculatedProperties.append(value);
          calculatedProperties.append("</");
          calculatedProperties.append(key);
          calculatedProperties.append(">");
          calculatedProperties.append("\n");
        }
      }

      try {
        String originalPom = FileUtils.readFileToString(new File("pom.xml"), "UTF-8");

        // Move modules to build section.
        originalPom = originalPom.replaceAll("  <modules>", "");
        // Because I hate f*****g regex.
        originalPom = originalPom.replaceAll("    <module>.*?</module>", "");
        originalPom = originalPom.replaceAll("  </modules>", "");

        originalPom =
            originalPom.replace(
                "<repositories>",
                "<modules>\n"
                    + "        <module>core</module>\n"
                    + "        <module>web</module>\n"
                    + "    </modules>\n\n    <repositories>");

        String pomWithProperties = addPropertiesToPom(originalPom, calculatedProperties);

        FileUtils.writeStringToFile(new File("pom.xml"), pomWithProperties, "UTF-8");
      } catch (IOException ex) {
        getLog().error("Unable to read root pom.xml: " + ex.getMessage(), ex);
        throw new MojoFailureException(ex.getMessage());
      }
    }

    // cleanup so user isn't aware that files were created
    File pom = new File("pom-fullsource.xml");

    if (pom.exists()) {
      pom.delete();
    }
  }
  @Override
  public void execute() throws MojoExecutionException {

    Path warExecFile = Paths.get(buildDirectory, finalName);
    try {
      Files.deleteIfExists(warExecFile);
      Files.createDirectories(warExecFile.getParent());

      try (OutputStream os = Files.newOutputStream(warExecFile);
          ArchiveOutputStream aos =
              new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.JAR, os)) {

        // If project is a war project add the war to the project
        if ("war".equalsIgnoreCase(project.getPackaging())) {
          File projectArtifact = project.getArtifact().getFile();
          if (projectArtifact != null && Files.exists(projectArtifact.toPath())) {
            aos.putArchiveEntry(new JarArchiveEntry(projectArtifact.getName()));
            try (InputStream is = Files.newInputStream(projectArtifact.toPath())) {
              IOUtils.copy(is, aos);
            }
            aos.closeArchiveEntry();
          }
        }

        // Add extraWars into the jar
        if (extraWars != null) {
          for (Dependency extraWarDependency : extraWars) {
            ArtifactRequest request = new ArtifactRequest();
            request.setArtifact(
                new DefaultArtifact(
                    extraWarDependency.getGroupId(),
                    extraWarDependency.getArtifactId(),
                    extraWarDependency.getType(),
                    extraWarDependency.getVersion()));
            request.setRepositories(projectRepos);
            ArtifactResult result;
            try {
              result = repoSystem.resolveArtifact(repoSession, request);
            } catch (ArtifactResolutionException e) {
              throw new MojoExecutionException(e.getMessage(), e);
            }

            File extraWarFile = result.getArtifact().getFile();
            aos.putArchiveEntry(new JarArchiveEntry(extraWarFile.getName()));
            try (InputStream is = Files.newInputStream(extraWarFile.toPath())) {
              IOUtils.copy(is, aos);
            }
            aos.closeArchiveEntry();
          }
        }

        // Add extraResources into the jar. Folder /extra
        if (extraResources != null) {
          for (Resource extraResource : extraResources) {
            DirectoryScanner directoryScanner = new DirectoryScanner();
            directoryScanner.setBasedir(extraResource.getDirectory());

            directoryScanner.setExcludes(
                extraResource
                    .getExcludes()
                    .toArray(new String[extraResource.getExcludes().size()]));

            if (!extraResource.getIncludes().isEmpty()) {
              directoryScanner.setIncludes(
                  extraResource
                      .getIncludes()
                      .toArray(new String[extraResource.getIncludes().size()]));
            } else {
              // include everything by default
              directoryScanner.setIncludes(new String[] {"**"});
            }

            directoryScanner.scan();
            for (String includeFile : directoryScanner.getIncludedFiles()) {
              aos.putArchiveEntry(
                  new JarArchiveEntry(Runner.EXTRA_RESOURCES_DIR + "/" + includeFile));

              Path extraFile = Paths.get(extraResource.getDirectory(), includeFile);
              try (InputStream is = Files.newInputStream(extraFile)) {
                IOUtils.copy(is, aos);
              }
              aos.closeArchiveEntry();
            }
          }
        }

        Set<String> includeArtifacts = new HashSet<>();
        includeArtifacts.add("org.apache.tomcat:tomcat-jdbc");
        includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-core");
        includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-logging-juli");
        includeArtifacts.add("org.yaml:snakeyaml");
        includeArtifacts.add("com.beust:jcommander");

        if (includeJSPSupport) {
          includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-jasper");
          includeArtifacts.add("org.eclipse.jdt.core.compiler:ecj");
        }

        for (Artifact pluginArtifact : pluginArtifacts) {
          String artifactName = pluginArtifact.getGroupId() + ":" + pluginArtifact.getArtifactId();
          if (includeArtifacts.contains(artifactName)) {
            try (JarFile jarFile = new JarFile(pluginArtifact.getFile())) {
              extractJarToArchive(jarFile, aos);
            }
          }
        }

        if (extraDependencies != null) {
          for (Dependency dependency : extraDependencies) {

            ArtifactRequest request = new ArtifactRequest();
            request.setArtifact(
                new DefaultArtifact(
                    dependency.getGroupId(),
                    dependency.getArtifactId(),
                    dependency.getType(),
                    dependency.getVersion()));
            request.setRepositories(projectRepos);
            ArtifactResult result;
            try {
              result = repoSystem.resolveArtifact(repoSession, request);
            } catch (ArtifactResolutionException e) {
              throw new MojoExecutionException(e.getMessage(), e);
            }

            try (JarFile jarFile = new JarFile(result.getArtifact().getFile())) {
              extractJarToArchive(jarFile, aos);
            }
          }
        }

        if (includeJSPSupport) {
          addFile(aos, "/conf/web.xml", "conf/web.xml");
        } else {
          addFile(aos, "/conf/web_wo_jsp.xml", "conf/web.xml");
        }
        addFile(aos, "/conf/logging.properties", "conf/logging.properties");

        if (includeTcNativeWin32 != null) {
          aos.putArchiveEntry(new JarArchiveEntry("tcnative-1.dll.32"));
          Files.copy(Paths.get(includeTcNativeWin32), aos);
          aos.closeArchiveEntry();
        }

        if (includeTcNativeWin64 != null) {
          aos.putArchiveEntry(new JarArchiveEntry("tcnative-1.dll.64"));
          Files.copy(Paths.get(includeTcNativeWin64), aos);
          aos.closeArchiveEntry();
        }

        String[] runnerClasses = {
          "ch.rasc.embeddedtc.runner.CheckConfig$CheckConfigOptions",
          "ch.rasc.embeddedtc.runner.CheckConfig",
          "ch.rasc.embeddedtc.runner.Config",
          "ch.rasc.embeddedtc.runner.Shutdown",
          "ch.rasc.embeddedtc.runner.Context",
          "ch.rasc.embeddedtc.runner.DeleteDirectory",
          "ch.rasc.embeddedtc.runner.ObfuscateUtil$ObfuscateOptions",
          "ch.rasc.embeddedtc.runner.ObfuscateUtil",
          "ch.rasc.embeddedtc.runner.Runner$1",
          "ch.rasc.embeddedtc.runner.Runner$2",
          "ch.rasc.embeddedtc.runner.Runner$StartOptions",
          "ch.rasc.embeddedtc.runner.Runner$StopOptions",
          "ch.rasc.embeddedtc.runner.Runner$RunnerShutdownHook",
          "ch.rasc.embeddedtc.runner.Runner"
        };

        for (String rc : runnerClasses) {
          String classAsPath = rc.replace('.', '/') + ".class";

          try (InputStream is = getClass().getResourceAsStream("/" + classAsPath)) {
            aos.putArchiveEntry(new JarArchiveEntry(classAsPath));
            IOUtils.copy(is, aos);
            aos.closeArchiveEntry();
          }
        }

        Manifest manifest = new Manifest();

        Manifest.Attribute mainClassAtt = new Manifest.Attribute();
        mainClassAtt.setName("Main-Class");
        mainClassAtt.setValue(Runner.class.getName());
        manifest.addConfiguredAttribute(mainClassAtt);

        aos.putArchiveEntry(new JarArchiveEntry("META-INF/MANIFEST.MF"));
        manifest.write(aos);
        aos.closeArchiveEntry();

        aos.putArchiveEntry(new JarArchiveEntry(Runner.TIMESTAMP_FILENAME));
        aos.write(String.valueOf(System.currentTimeMillis()).getBytes(StandardCharsets.UTF_8));
        aos.closeArchiveEntry();
      }
    } catch (IOException | ArchiveException | ManifestException e) {
      throw new MojoExecutionException(e.getMessage(), e);
    }
  }
  /**
   * Entry point to this plugin. Finds the configuration files, constructs the tests, and executes
   * the tests.
   *
   * @throws MojoExecutionException
   * @throws MojoFailureException
   * @see AbstractMojo#execute()
   */
  public void execute() throws MojoExecutionException, MojoFailureException {

    MavenLogAppender.startPluginLog(this);

    try {

      final Collection<CyclicRedundancyException> rulesExceptions =
          new LinkedList<CyclicRedundancyException>();

      final Log log = getLog();

      List<Resource> testResources;
      MojoArchitectureRulesConfigurationTest test;

      for (final MavenProject project : reactorProjects) {

        if (log.isDebugEnabled()) {

          log.debug("process " + project);
        }

        /**
         * Skip the project resources, if the project is the parent project and the parent project
         * should be skipped.
         */
        final boolean isAggregated =
            !project.getModules().isEmpty() || "pom".equals(project.getPackaging());

        if ((isAggregated && skipRoot) || (!isAggregated && skip)) {

          if (log.isDebugEnabled()) {

            log.debug("aggregated = " + isAggregated + "; skip " + project);
          }

          continue;
        }

        testResources = project.getTestResources();
        includeConfigurationFile(testResources);

        File configFile;

        try {

          configFile = findConfigurationFile(testResources, log);
        } catch (FileNotFoundException e1) {

          log.warn(e1.getMessage());
          log.warn("fallback to use default config");

          configFile = new File(ConfigurationFactory.DEFAULT_CONFIGURATION_FILE_NAME);
        }

        test = new MojoArchitectureRulesConfigurationTest(configFile);
        test.addSourcesFromThisProject(project, log);

        try {

          test.testArchitecture();
        } catch (CyclicRedundancyException e) {

          rulesExceptions.add(e);
        }
      }

      if (!rulesExceptions.isEmpty()) {

        if (isFailOnError()) {

          throw new MojoExecutionException(rulesExceptions, "", "");
        } else {

          getLog().warn(new ArchitectureException(rulesExceptions.toString()));
        }
      }
    } finally {

      MavenLogAppender.endPluginLog(this);
    }
  }
  public TargetPlatformConfiguration getTargetPlatformConfiguration(
      MavenSession session, MavenProject project) {
    TargetPlatformConfiguration result = new TargetPlatformConfiguration();

    // Use org.eclipse.tycho:target-platform-configuration/configuration/environment, if provided
    Plugin plugin = project.getPlugin("org.eclipse.tycho:target-platform-configuration");

    if (plugin != null) {
      Xpp3Dom configuration = (Xpp3Dom) plugin.getConfiguration();
      if (configuration != null) {
        if (logger.isDebugEnabled()) {
          logger.debug(
              "target-platform-configuration for "
                  + project.toString()
                  + ":\n"
                  + configuration.toString());
        }

        addTargetEnvironments(result, project, configuration);

        setTargetPlatformResolver(result, configuration);

        setTarget(result, session, project, configuration);

        setPomDependencies(result, configuration);

        setAllowConflictingDependencies(result, configuration);

        setDisableP2Mirrors(result, configuration);

        setExecutionEnvironment(result, configuration);

        readFilters(result, configuration);

        readExtraRequirements(result, configuration);

        setOptionalDependencies(result, configuration);

        setIncludePackedArtifacts(result, configuration);
      }
    }

    if (result.getEnvironments().isEmpty()) {
      TychoProject projectType = projectTypes.get(project.getPackaging());
      if (projectType != null) {
        TargetEnvironment env = projectType.getImplicitTargetEnvironment(project);
        if (env != null) {
          if (logger.isDebugEnabled()) {
            logger.debug(
                "Implicit target environment for " + project.toString() + ": " + env.toString());
          }

          result.addEnvironment(env);
        }
      }
    }

    if (result.getEnvironments().isEmpty()) {
      // applying defaults
      logger.warn(
          "No explicit target runtime environment configuration. Build is platform dependent.");

      // Otherwise, use project or execution properties, if provided
      Properties properties =
          (Properties) project.getContextValue(TychoConstants.CTX_MERGED_PROPERTIES);

      // Otherwise, use current system os/ws/nl/arch
      String os = PlatformPropertiesUtils.getOS(properties);
      String ws = PlatformPropertiesUtils.getWS(properties);
      String arch = PlatformPropertiesUtils.getArch(properties);

      result.addEnvironment(new TargetEnvironment(os, ws, arch));

      result.setImplicitTargetEnvironment(true);
    } else {
      result.setImplicitTargetEnvironment(false);
    }

    return result;
  }