public List<Artifact> getIncludedArtifacts() throws MojoExecutionException {

    if (inlcudedArtifacts == null) {
      inlcudedArtifacts = new ArrayList<Artifact>();

      Set<Artifact> artifacts = project.getArtifacts();

      if (includes != null) {
        if (exclusions != null) {
          throw new MojoExecutionException("Both inlcudes and exclusions are specified");
        }
        Set<String> inclusionKeys = getArtifactKeys(includes);

        for (Artifact a : artifacts) {
          if (inclusionKeys.contains(
              getArtifactKey(a.getGroupId(), a.getArtifactId(), a.getClassifier()))) {
            inlcudedArtifacts.add(a);
          }
        }
      } else {
        Set<String> exclusionKeys = new HashSet<String>(getArtifactKeys(exclusions));
        exclusionKeys.addAll(getImportedArtifactKeys());
        for (Artifact a : artifacts) {
          if (!exclusionKeys.contains(
              getArtifactKey(a.getGroupId(), a.getArtifactId(), a.getClassifier()))) {
            inlcudedArtifacts.add(a);
          }
        }
      }
    }

    return inlcudedArtifacts;
  }
  // used by "initialize", "dist" and "war" mojos
  protected Artifact findFrameworkArtifact(boolean minVersionWins) {
    Artifact result = null;

    Set<?> artifacts = project.getArtifacts();
    for (Iterator<?> iter = artifacts.iterator(); iter.hasNext(); ) {
      Artifact artifact = (Artifact) iter.next();
      if ("zip".equals(artifact.getType())) {
        if ("framework".equals(artifact.getClassifier())) {
          result = artifact;
          if (!minVersionWins) {
            break;
          }
          // System.out.println( "added framework: " + artifact.getGroupId() + ":" +
          // artifact.getArtifactId()
          // );
          // don't break, maybe there is "framework-min" artifact too
        }
        // "module-min" overrides "module" (if present)
        else if ("framework-min".equals(artifact.getClassifier())) {
          result = artifact;
          // System.out.println( "added framework-min: " + artifact.getGroupId() + ":"
          // + artifact.getArtifactId() );
          if (minVersionWins) {
            break;
          }
        }
      }
    }
    return result;
  }
  private boolean match(Dependency dependency, Artifact artifact) {
    boolean match =
        dependency.getGroupId().equals(artifact.getGroupId())
            && dependency.getArtifactId().equals(artifact.getArtifactId())
            && dependency.getVersion().equals(artifact.getVersion());

    if (match) {
      if (dependency.getClassifier() == null) {
        match = artifact.getClassifier() == null;
      } else {
        match = dependency.getClassifier().equals(artifact.getClassifier());
      }
    }

    if (match) {
      String type = artifact.getType();
      if (dependency.getType() == null) {
        match = type == null || type.equals("jar");
      } else {
        match = dependency.getType().equals(type);
      }
    }

    return match;
  }
  /**
   * Builds the string to be entered in the href attribute of the jar resource element in the
   * generated JNLP file. This will be equal to the artifact file name with the version number
   * stripped out.
   *
   * @param artifact The underlying artifact of the jar resource.
   * @return The href string for the given artifact, never null.
   */
  private String buildHrefValue(Artifact artifact) {
    StringBuffer sbuf = new StringBuffer();
    sbuf.append(artifact.getArtifactId());

    if (StringUtils.isNotEmpty(artifact.getClassifier())) {
      sbuf.append("-").append(artifact.getClassifier());
    }

    sbuf.append(".").append(artifact.getArtifactHandler().getExtension());

    return sbuf.toString();
  }
 protected Artifact getArtifact(String groupId, String artifactId, String classifier) {
   for (Artifact artifact : pluginArtifacts) {
     if (groupId.equals(artifact.getGroupId()) && artifactId.equals(artifact.getArtifactId())) {
       if (classifier != null && classifier.equals(artifact.getClassifier())) {
         return artifact;
       }
       if (classifier == null && artifact.getClassifier() == null) {
         return artifact;
       }
     }
   }
   getLog().error("Failed to retrieve " + groupId + ":" + artifactId + ":" + classifier);
   return null;
 }
  String getBundleClasspath() throws MojoExecutionException {
    StringBuffer sb = new StringBuffer();

    File outputDirectory = new File(project.getBuild().getOutputDirectory());
    if (outputDirectory.exists()) {
      if (classifier != null) {
        for (Iterator i = project.getAttachedArtifacts().iterator(); i.hasNext(); ) {
          Artifact a = (Artifact) i.next();
          if (classifier.equals(a.getClassifier())) {
            sb.append(jars + "/" + a.getFile().getName());
          }
        }
      } else if (projectJar != null) {
        sb.append(jars + "/" + projectJar);
      }
    }

    if (bundleClasspath != null) {
      for (int i = 0; i < bundleClasspath.length; i++) {
        if (sb.length() > 0) sb.append(',');
        sb.append(bundleClasspath[i]);
      }
    }
    for (Iterator i = getIncludedArtifacts().iterator(); i.hasNext(); ) {
      Artifact a = (Artifact) i.next();
      if (sb.length() > 0) sb.append(',');
      sb.append(jars + "/" + a.getFile().getName());
    }
    return sb.toString();
  }
Ejemplo n.º 7
0
 @Before
 public void setUp() {
   artifact = Mockito.mock(Artifact.class);
   Mockito.when(artifact.getArtifactId()).thenReturn(ArtifactConstants.ARTIFACTID);
   Mockito.when(artifact.getGroupId()).thenReturn(ArtifactConstants.GROUPID);
   Mockito.when(artifact.getVersion()).thenReturn(ArtifactConstants.VERSION);
   Mockito.when(artifact.getClassifier()).thenReturn(ArtifactConstants.CLASSIFIER);
   Mockito.when(artifact.getType()).thenReturn(ArtifactConstants.JAR_TYPE);
 }
Ejemplo n.º 8
0
  /**
   * @param o
   * @param a
   * @return
   */
  protected boolean overlayMatchesArtifact(OverlayConfig o, Artifact a) {
    if (((o.getGroupId() == null && a.getGroupId() == null)
            || (o.getGroupId() != null && o.getGroupId().equals(a.getGroupId())))
        && ((o.getArtifactId() == null && a.getArtifactId() == null)
            || (o.getArtifactId() != null && o.getArtifactId().equals(a.getArtifactId())))
        && ((o.getClassifier() == null) || (o.getClassifier().equals(a.getClassifier()))))
      return true;

    return false;
  }
Ejemplo n.º 9
0
  @SuppressWarnings("unchecked")
  private Collection<Artifact> getNonTransitivePlugins(Set<Artifact> projectArtifacts)
      throws MojoExecutionException {
    Collection<Artifact> deps = new LinkedHashSet<Artifact>();

    for (Artifact artifact : projectArtifacts) {
      Artifact pomArtifact =
          artifactFactory.createArtifact(
              artifact.getGroupId(),
              artifact.getArtifactId(),
              artifact.getVersion(),
              artifact.getClassifier(),
              "pom");
      Set<Artifact> result;
      try {
        MavenProject pomProject =
            mavenProjectBuilder.buildFromRepository(
                pomArtifact, remoteRepositories, localRepository);

        Set<Artifact> artifacts = pomProject.createArtifacts(artifactFactory, null, null);
        artifacts = filterOutSystemDependencies(artifacts);
        ArtifactResolutionResult arr =
            resolver.resolveTransitively(
                artifacts,
                pomArtifact,
                localRepository,
                remoteRepositories,
                artifactMetadataSource,
                null);
        result = arr.getArtifacts();
      } catch (Exception e) {
        throw new MojoExecutionException(
            "Failed to resolve non-transitive deps " + e.getMessage(), e);
      }

      LinkedHashSet<Artifact> plugins = new LinkedHashSet<Artifact>();
      plugins.addAll(filtterArtifacts(result, getFilters(null, null, "nexus-plugin", null)));
      plugins.addAll(filtterArtifacts(result, getFilters(null, null, "zip", "bundle")));

      plugins.addAll(getNonTransitivePlugins(plugins));

      if (!plugins.isEmpty()) {
        getLog()
            .debug(
                "Adding non-transitive dependencies for: "
                    + artifact
                    + " -\n"
                    + plugins.toString().replace(',', '\n'));
      }

      deps.addAll(plugins);
    }

    return deps;
  }
Ejemplo n.º 10
0
 /**
  * Returns a map from classifiers to artifact files of the given project. The classifier <code>
  * null</code> is mapped to the project's main artifact.
  */
 private static Map<String, File> getAllProjectArtifacts(MavenProject project) {
   Map<String, File> artifacts = new HashMap<String, File>();
   Artifact mainArtifact = project.getArtifact();
   if (mainArtifact != null) {
     artifacts.put(null, mainArtifact.getFile());
   }
   for (Artifact attachedArtifact : project.getAttachedArtifacts()) {
     artifacts.put(attachedArtifact.getClassifier(), attachedArtifact.getFile());
   }
   return artifacts;
 }
 public String mapFileName(Artifact artifact) {
   StringBuilder fileName = new StringBuilder(artifact.getArtifactId());
   String classifier = artifact.getClassifier();
   if (classifier != null) {
     fileName.append("-").append(classifier);
   }
   if (!isRemoveDependencyVersions()) {
     fileName.append("-").append(artifact.getVersion());
   }
   fileName.append(".").append(artifact.getArtifactHandler().getExtension());
   return fileName.toString();
 }
Ejemplo n.º 12
0
  private String getHardwareArchitectureFor(Artifact resolvedArtifact) {
    if (StringUtils.isNotBlank(nativeLibrariesDependenciesHardwareArchitectureOverride)) {
      return nativeLibrariesDependenciesHardwareArchitectureOverride;
    }

    final String classifier = resolvedArtifact.getClassifier();
    if (StringUtils.isNotBlank(classifier)) {
      return classifier;
    }

    return nativeLibrariesDependenciesHardwareArchitectureDefault;
  }
Ejemplo n.º 13
0
  /**
   * Returns the final name of the specified artifact.
   *
   * <p>If the <tt>outputFileNameMapping</tt> is set, it is used, otherwise the standard naming
   * scheme is used.
   *
   * @param context the packaging context
   * @param artifact the artifact
   * @return the converted filename of the artifact
   */
  protected String getArtifactFinalName(AmpPackagingContext context, Artifact artifact) {
    if (context.getOutputFileNameMapping() != null) {
      return MappingUtils.evaluateFileNameMapping(context.getOutputFileNameMapping(), artifact);
    }

    String classifier = artifact.getClassifier();
    if ((classifier != null) && !("".equals(classifier.trim()))) {
      return MappingUtils.evaluateFileNameMapping(
          AbstractAmpMojo.DEFAULT_FILE_NAME_MAPPING_CLASSIFIER, artifact);
    } else {
      return MappingUtils.evaluateFileNameMapping(
          AbstractAmpMojo.DEFAULT_FILE_NAME_MAPPING, artifact);
    }
  }
Ejemplo n.º 14
0
  protected Map<String, Artifact> findAllModuleArtifacts(boolean minVersionWins) {
    Map<String, Artifact> result = new HashMap<String, Artifact>();

    Set<?> artifacts = project.getArtifacts();
    for (Iterator<?> iter = artifacts.iterator(); iter.hasNext(); ) {
      Artifact artifact = (Artifact) iter.next();
      if ("zip".equals(artifact.getType())) {
        if ("module".equals(artifact.getClassifier())
            || "module-min".equals(artifact.getClassifier())) {
          String moduleName = artifact.getArtifactId();
          if (moduleName.startsWith("play-")) {
            moduleName = moduleName.substring("play-".length());
          }

          if ("module".equals(artifact.getClassifier())) {
            if (!minVersionWins || result.get(moduleName) == null) {
              result.put(moduleName, artifact);
              // System.out.println("added module: " + artifact.getGroupId() + ":" +
              // artifact.getArtifactId());
            }
          } else
          // "module-min"
          {
            if (minVersionWins || result.get(moduleName) == null) {
              result.put(moduleName, artifact);
              // System.out.println("added module-min: " + artifact.getGroupId() + ":" +
              // artifact.getArtifactId());
            }
          }
        }
      } else if ("play".equals(artifact.getType())) {
        String moduleName = artifact.getArtifactId();
        result.put(moduleName, artifact);
      }
    }
    return result;
  }
Ejemplo n.º 15
0
  /**
   * Allow the script to work with every JAR dependency of both the project and plugin, including
   * optional and provided dependencies. Runtime classpath elements are loaded first, so that legacy
   * behavior is not modified. Additional elements are added first in the order of project
   * artifacts, then in the order of plugin artifacts.
   */
  protected List getProjectClasspathElements() throws DependencyResolutionRequiredException {
    Set results = new LinkedHashSet();

    for (Iterator i = project.getRuntimeClasspathElements().iterator(); i.hasNext(); ) {
      String cpe = (String) i.next();
      try {
        results.add(new File(cpe).getCanonicalPath());
      } catch (IOException e) {
        throw new RuntimeException("Classpath element not found: " + cpe, e);
      }
    }

    for (Iterator i = project.getArtifacts().iterator(); i.hasNext(); ) {
      Artifact artifact = (Artifact) i.next();
      if (artifact.getType().equals("jar") && artifact.getClassifier() == null) {
        try {
          results.add(artifact.getFile().getCanonicalPath());
        } catch (IOException e) {
          throw new RuntimeException("Maven artifact file not found: " + artifact.toString(), e);
        }
      }
    }

    for (Iterator i = pluginArtifacts.iterator(); i.hasNext(); ) {
      Artifact artifact = (Artifact) i.next();
      if (artifact.getType().equals("jar") && artifact.getClassifier() == null) {
        try {
          results.add(artifact.getFile().getCanonicalPath());
        } catch (IOException e) {
          throw new RuntimeException(
              "Maven plugin-artifact file not found: " + artifact.toString(), e);
        }
      }
    }
    return new ArrayList(results);
  }
Ejemplo n.º 16
0
  /** artifacts provided by bundles this project depends on */
  private Set<String> getImportedArtifactKeys() throws MojoExecutionException {
    HashSet<String> keys = new HashSet<String>();

    if (requireBundles != null) {
      for (int i = 0; i < requireBundles.length; i++) {
        MavenArtifactRef a = requireBundles[i];

        ArtifactResolutionResult result = resolve(a, true);

        for (Artifact b : result.getArtifacts()) {
          keys.add(getArtifactKey(b.getGroupId(), b.getArtifactId(), b.getClassifier()));
        }
      }
    }
    return keys;
  }
Ejemplo n.º 17
0
  private String artifactToMvn(Artifact artifact) throws MojoExecutionException {
    String uri;

    String groupId = artifact.getGroupId();
    String artifactId = artifact.getArtifactId();
    String version = artifact.getBaseVersion();
    String type = artifact.getArtifactHandler().getExtension();
    String classifier = artifact.getClassifier();

    if (MavenUtil.isEmpty(classifier)) {
      if ("jar".equals(type)) {
        uri = String.format("mvn:%s/%s/%s", groupId, artifactId, version);
      } else {
        uri = String.format("mvn:%s/%s/%s/%s", groupId, artifactId, version, type);
      }
    } else {
      uri = String.format("mvn:%s/%s/%s/%s/%s", groupId, artifactId, version, type, classifier);
    }
    return uri;
  }
Ejemplo n.º 18
0
  /**
   * Removes any Grails plugin artifacts from the supplied list of dependencies. A Grails plugin is
   * any artifact whose type is equal to "grails-plugin" or "zip"
   *
   * @param artifact The list of artifacts to be cleansed.
   * @return list of plugins
   */
  private Set<Artifact> removePluginArtifacts(final Set<Artifact> artifact) {
    final Set<Artifact> pluginArtifacts = new HashSet<Artifact>();

    if (artifact != null) {
      for (final Iterator<Artifact> iter = artifact.iterator(); iter.hasNext(); ) {
        final Artifact dep = iter.next();
        if (dep.getType() != null
            && (dep.getType().equals("grails-plugin")
                || dep.getType().equals("zip")
                || (dep.getType().equals("grails-plugin2")
                    && "plugin".equals(dep.getClassifier())))) {
          pluginArtifacts.add(dep);
          //          System.out.println("removing " + dep.toString());
          iter.remove();
        }
      }
    }

    return pluginArtifacts;
  }
Ejemplo n.º 19
0
  /**
   * Extracts, if embedded correctly, the artifacts architecture from its classifier. The format of
   * the classifier, if including the architecture is &lt;architecture&gt;-&lt;classifier&gt;. If no
   * architecture is embedded in the classifier, 'armeabi' will be returned.
   *
   * @param artifact The artifact to retrieve the classifier from.
   * @param defaultArchitecture The architecture to return if can't be resolved from the classifier
   * @return The retrieved architecture, or <code>defaulArchitecture</code> if not resolveable
   */
  public static String extractArchitectureFromArtifact(
      Artifact artifact, final String defaultArchitecture) {
    String classifier = artifact.getClassifier();
    if (classifier != null) {
      //
      // We loop backwards to catch the case where the classifier is
      // potentially armeabi-v7a - this collides with armeabi if looping
      // through this loop in the other direction
      //

      for (int i = AndroidNdk.NDK_ARCHITECTURES.length - 1; i >= 0; i--) {
        String ndkArchitecture = AndroidNdk.NDK_ARCHITECTURES[i];
        if (classifier.startsWith(ndkArchitecture)) {
          return ndkArchitecture;
        }
      }
    }
    // Default case is to return the default architecture
    return defaultArchitecture;
  }
Ejemplo n.º 20
0
  protected Collection<Artifact> getNexusPlugins() throws MojoExecutionException {

    Set<Artifact> projectArtifacts = new LinkedHashSet<Artifact>();
    projectArtifacts.addAll(getFilteredArtifacts(null, null, "zip", "bundle"));
    projectArtifacts.addAll(getFilteredArtifacts(null, null, "nexus-plugin", null));
    projectArtifacts.addAll(getNonTransitivePlugins(projectArtifacts));

    List<Artifact> resolvedArtifacts = new ArrayList<Artifact>();

    for (Artifact artifact : projectArtifacts) {
      Artifact ra =
          artifactFactory.createArtifactWithClassifier(
              artifact.getGroupId(),
              artifact.getArtifactId(),
              artifact.getVersion(),
              artifact.getType(),
              artifact.getClassifier());

      resolvedArtifacts.add(resolve(ra));
    }

    return resolvedArtifacts;
  }
Ejemplo n.º 21
0
  public void execute() throws MojoExecutionException, MojoFailureException {
    for (Artifact artifact : (Set<Artifact>) project.getDependencyArtifacts()) {
      String type = artifact.getType();
      if ("android:po".equals(type)) {
        String classifier = artifact.getClassifier();
        if (classifier == null) {
          throw new MojoExecutionException("android:po artifacts must have a classifier");
        }
        boolean isClassifier = defaultResources.contains(classifier);
        File valuesDir =
            (isClassifier)
                ? new File(resourceDirectory, "values")
                : new File(resourceDirectory, "values-" + classifier);
        if (!valuesDir.exists()) {
          valuesDir.mkdirs();
        }

        List<Resource> resources = project.getBuild().getResources();
        String resourceDir = (resources.isEmpty()) ? "res" : resources.get(0).getDirectory();

        ZipFile zip = null;
        try {
          zip = new ZipFile(artifact.getFile());
          Enumeration<? extends ZipEntry> en = zip.entries();
          while (en.hasMoreElements()) {
            ZipEntry entry = en.nextElement();
            if (entry.getName().endsWith(".po")) {
              writeWithCorrectEncoding(
                  artifact.getFile(), entry.getName(), valuesDir, resourceDir, isClassifier);
            }
          }
        } catch (IOException e) {
          throw new MojoExecutionException("", e);
        }
      }
    }
  }
  /** Iterate through dependencies, find those specified in the whitelist */
  private Set<Artifact> findThriftDependencies(Set<String> whitelist) throws IOException {
    Set<Artifact> thriftDependencies = new HashSet<Artifact>();

    Set<Artifact> deps = new HashSet<Artifact>();
    deps.addAll(project.getArtifacts());
    deps.addAll(project.getDependencyArtifacts());

    Map<String, Artifact> depsMap = new HashMap<String, Artifact>();
    for (Artifact dep : deps) {
      depsMap.put(dep.getId(), dep);
    }

    for (Artifact artifact : deps) {
      // This artifact is on the whitelist directly.
      if (whitelist.contains(artifact.getArtifactId())) {
        thriftDependencies.add(artifact);

        // Check if this artifact is being pulled in by an idl jar that's been whitelisted
      } else {
        List<String> depTrail = artifact.getDependencyTrail();
        // depTrail can be null sometimes, which seems like a maven bug
        if (depTrail != null) {
          for (String name : depTrail) {
            Artifact dep = depsMap.get(name);
            if (dep != null
                && "idl".equals(dep.getClassifier())
                && whitelist.contains(dep.getArtifactId())) {
              thriftDependencies.add(artifact);
              break;
            }
          }
        }
      }
    }
    return thriftDependencies;
  }
Ejemplo n.º 23
0
  @Override
  public ArtifactResult resolveArtifact(RepositorySystemSession session, ArtifactRequest request)
      throws ArtifactResolutionException {

    debugf("resolveArtifact %s", request);
    validateSession(session);

    // delegate has been wired up to come back to us, so this must be a real
    // implementation

    ArtifactResolutionException originalException = null;
    final Artifact artifact = request.getArtifact();

    // try FOSS local repo
    {
      try {
        final ArtifactRequest alternateRequest =
            new ArtifactRequest(
                    request.getArtifact(),
                    singletonList(fossRepository),
                    request.getRequestContext())
                .setDependencyNode(request.getDependencyNode())
                .setTrace(request.getTrace());

        final ArtifactResult result = artifactResolver.resolveArtifact(session, alternateRequest);

        // A successful result can contain exceptions
        // if (result.getExceptions().isEmpty()) {
        return result;
        // }
      } catch (ArtifactResolutionException e) {
        originalException = e;
      }
    }

    // try FOSS local repo with LATEST
    if (!artifact.getVersion().equals(LATEST_VERSION))
    //            throw new IllegalStateException("NYI: LATEST should not appear " +
    //                    "during resolveArtifact, should it?");
    {
      try {
        final Artifact alternateArtifact =
            new DefaultArtifact(
                artifact.getGroupId(),
                artifact.getArtifactId(),
                artifact.getClassifier(),
                artifact.getExtension(),
                LATEST_VERSION,
                artifact.getProperties(),
                artifact.getFile());

        final ArtifactRequest alternateRequest =
            new ArtifactRequest(
                    alternateArtifact,
                    Collections.singletonList(fossRepository),
                    request.getRequestContext())
                .setDependencyNode(request.getDependencyNode())
                .setTrace(request.getTrace());

        // setDependencyNode will override the artifact
        alternateRequest.setArtifact(alternateArtifact);

        final ArtifactResult result = artifactResolver.resolveArtifact(session, alternateRequest);

        // A successful result can contain exceptions
        // if (result.getExceptions().isEmpty()) {
        logger.warn(
            "Could not find artifact " + artifact + ", using LATEST " + result.getArtifact());
        return result;
        // }
      } catch (ArtifactResolutionException e) {
        logger.debug("LATEST resolution of " + artifact + " failed", e);
        if (originalException == null) {
          originalException = e;
        }
      }
    }

    // try JPP local repo
    if (useJpp) {
      // use maven as much as possible
      final RepositorySystemSession alternateSession = openJpp(session);
      try {
        final ArtifactRequest alternateRequest =
            new ArtifactRequest(
                    request.getArtifact(),
                    singletonList(fossRepository),
                    request.getRequestContext())
                .setDependencyNode(request.getDependencyNode())
                .setTrace(request.getTrace());

        final ArtifactResult result =
            artifactResolver.resolveArtifact(alternateSession, alternateRequest);

        // A successful result can contain exceptions
        // if (result.getExceptions().isEmpty()) {
        logger.warn(
            "Could not find artifact "
                + artifact
                + " in "
                + fossRepository
                + ", using JPP "
                + result.getArtifact());
        return result;
        // }
      } catch (ArtifactResolutionException e) {
        logger.debug("JPP resolution of " + artifact + " failed", e);
        if (originalException == null) {
          originalException = e;
        }
      }
    }

    if (originalException != null) {
      throw originalException;
    }

    throw new RuntimeException(
        "NYI: org.fedoraproject.maven.repository.internal."
            + "FossRepositorySystem.resolveArtifact");
  }
  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;
  }
  /**
   * Format the given artifact as a bundle string with the appropriate syntax used by the karaf
   * features.xml file. For example:
   *
   * <p>mvn:commons-configuration/commons-configuration/1.6
   *
   * @param artifact
   */
  protected String formatArtifactAsBundle(Artifact artifact) throws Exception {
    StringBuilder builder = new StringBuilder();
    // If it's a bundle already, awesome.  If not, we need to wrap it
    // and include some useful meta-data.
    if (isBundle(artifact)) {
      // Example:  mvn:commons-configuration/commons-configuration/1.6
      builder.append("mvn:"); // $NON-NLS-1$
      builder.append(artifact.getGroupId());
      builder.append("/"); // $NON-NLS-1$
      builder.append(artifact.getArtifactId());
      builder.append("/"); // $NON-NLS-1$
      builder.append(artifact.getBaseVersion());
      String classifier = artifact.getClassifier();
      if (classifier != null && classifier.trim().length() == 0) {
        classifier = null;
      }
      if (!"jar".equalsIgnoreCase(artifact.getType()) || classifier != null) { // $NON-NLS-1$
        builder.append("/"); // $NON-NLS-1$
        builder.append(artifact.getType());
      }
      if (classifier != null) {
        builder.append("/"); // $NON-NLS-1$
        builder.append(classifier);
      }
    } else {
      // Example:
      // wrap:mvn:log4j/log4j/1.2.14$Bundle-SymbolicName=log4j.log4j&amp;Bundle-Version=1.2.14&amp;Bundle-Name=Log4j
      builder.append("wrap:mvn:"); // $NON-NLS-1$
      builder.append(artifact.getGroupId());
      builder.append("/"); // $NON-NLS-1$
      builder.append(artifact.getArtifactId());
      builder.append("/"); // $NON-NLS-1$
      builder.append(artifact.getBaseVersion());
      String classifier = artifact.getClassifier();
      if (classifier != null && classifier.trim().length() == 0) {
        classifier = null;
      }
      if (!"jar".equalsIgnoreCase(artifact.getType()) || classifier != null) { // $NON-NLS-1$
        builder.append("/"); // $NON-NLS-1$
        builder.append(artifact.getType());
      }
      if (classifier != null) {
        builder.append("/"); // $NON-NLS-1$
        builder.append(classifier);
      }

      MavenProject project = resolveProject(artifact);
      builder.append("$Bundle-SymbolicName="); // $NON-NLS-1$
      builder.append(artifact.getGroupId());
      builder.append("."); // $NON-NLS-1$
      builder.append(artifact.getArtifactId());
      builder.append("&Bundle-Version="); // $NON-NLS-1$
      builder.append(sanitizeVersionForOsgi(artifact.getBaseVersion()));
      // Under certain circumstances, the project name may include unresolved variables.  If so,
      // skip Bundle-Name
      if (project.getName() != null
          && project.getName().trim().length() > 0
          && !project.getName().contains("${")) { // $NON-NLS-1$
        builder.append("&Bundle-Name="); // $NON-NLS-1$
        builder.append(project.getName());
      }
    }
    return builder.toString();
  }
Ejemplo n.º 26
0
  protected void generateAggregatedZip(
      MavenProject rootProject,
      List<MavenProject> reactorProjects,
      Set<MavenProject> pomZipProjects)
      throws IOException, MojoExecutionException {
    File projectBaseDir = rootProject.getBasedir();
    String rootProjectGroupId = rootProject.getGroupId();
    String rootProjectArtifactId = rootProject.getArtifactId();
    String rootProjectVersion = rootProject.getVersion();

    String aggregatedZipFileName =
        "target/" + rootProjectArtifactId + "-" + rootProjectVersion + "-app.zip";
    File projectOutputFile = new File(projectBaseDir, aggregatedZipFileName);
    getLog()
        .info(
            "Generating "
                + projectOutputFile.getAbsolutePath()
                + " from root project "
                + rootProjectArtifactId);
    File projectBuildDir = new File(projectBaseDir, reactorProjectOutputPath);

    if (projectOutputFile.exists()) {
      projectOutputFile.delete();
    }
    createAggregatedZip(
        projectBaseDir,
        projectBuildDir,
        reactorProjectOutputPath,
        projectOutputFile,
        includeReadMe,
        pomZipProjects);
    if (rootProject.getAttachedArtifacts() != null) {
      // need to remove existing as otherwise we get a WARN
      Artifact found = null;
      for (Artifact artifact : rootProject.getAttachedArtifacts()) {
        if (artifactClassifier != null
            && artifact.hasClassifier()
            && artifact.getClassifier().equals(artifactClassifier)) {
          found = artifact;
          break;
        }
      }
      if (found != null) {
        rootProject.getAttachedArtifacts().remove(found);
      }
    }

    getLog()
        .info(
            "Attaching aggregated zip "
                + projectOutputFile
                + " to root project "
                + rootProject.getArtifactId());
    projectHelper.attachArtifact(rootProject, artifactType, artifactClassifier, projectOutputFile);

    // if we are doing an install goal, then also install the aggregated zip manually
    // as maven will install the root project first, and then build the reactor projects, and at
    // this point
    // it does not help to attach artifact to root project, as those artifacts will not be installed
    // so we need to install manually
    List<String> activeProfileIds = new ArrayList<>();
    List<Profile> activeProfiles = rootProject.getActiveProfiles();
    if (activeProfiles != null) {
      for (Profile profile : activeProfiles) {
        String id = profile.getId();
        if (Strings.isNotBlank(id)) {
          activeProfileIds.add(id);
        }
      }
    }
    if (rootProject.hasLifecyclePhase("install")) {
      getLog().info("Installing aggregated zip " + projectOutputFile);
      InvocationRequest request = new DefaultInvocationRequest();
      request.setBaseDirectory(rootProject.getBasedir());
      request.setPomFile(new File("./pom.xml"));
      request.setGoals(Collections.singletonList("install:install-file"));
      request.setRecursive(false);
      request.setInteractive(false);
      request.setProfiles(activeProfileIds);

      Properties props = new Properties();
      props.setProperty("file", aggregatedZipFileName);
      props.setProperty("groupId", rootProjectGroupId);
      props.setProperty("artifactId", rootProjectArtifactId);
      props.setProperty("version", rootProjectVersion);
      props.setProperty("classifier", "app");
      props.setProperty("packaging", "zip");
      props.setProperty("generatePom", "false");
      request.setProperties(props);

      getLog()
          .info(
              "Installing aggregated zip using: mvn install:install-file"
                  + serializeMvnProperties(props));
      Invoker invoker = new DefaultInvoker();
      try {
        InvocationResult result = invoker.execute(request);
        if (result.getExitCode() != 0) {
          throw new IllegalStateException("Error invoking Maven goal install:install-file");
        }
      } catch (MavenInvocationException e) {
        throw new MojoExecutionException("Error invoking Maven goal install:install-file", e);
      }
    }

    if (rootProject.hasLifecyclePhase("deploy")) {

      if (deploymentRepository == null && Strings.isNullOrBlank(altDeploymentRepository)) {
        String msg =
            "Cannot run deploy phase as Maven project has no <distributionManagement> with the maven url to use for deploying the aggregated zip file, neither an altDeploymentRepository property.";
        getLog().warn(msg);
        throw new MojoExecutionException(msg);
      }

      getLog()
          .info(
              "Deploying aggregated zip "
                  + projectOutputFile
                  + " to root project "
                  + rootProject.getArtifactId());
      getLog()
          .info(
              "Using deploy goal: "
                  + deployFileGoal
                  + " with active profiles: "
                  + activeProfileIds);

      InvocationRequest request = new DefaultInvocationRequest();
      request.setBaseDirectory(rootProject.getBasedir());
      request.setPomFile(new File("./pom.xml"));
      request.setGoals(Collections.singletonList(deployFileGoal));
      request.setRecursive(false);
      request.setInteractive(false);
      request.setProfiles(activeProfileIds);
      request.setProperties(getProject().getProperties());

      Properties props = new Properties();
      props.setProperty("file", aggregatedZipFileName);
      props.setProperty("groupId", rootProjectGroupId);
      props.setProperty("artifactId", rootProjectArtifactId);
      props.setProperty("version", rootProjectVersion);
      props.setProperty("classifier", "app");
      props.setProperty("packaging", "zip");
      String deployUrl = null;

      if (!Strings.isNullOrBlank(deployFileUrl)) {
        deployUrl = deployFileUrl;
      } else if (altDeploymentRepository != null && altDeploymentRepository.contains("::")) {
        deployUrl =
            altDeploymentRepository.substring(altDeploymentRepository.lastIndexOf("::") + 2);
      } else {
        deployUrl = deploymentRepository.getUrl();
      }

      props.setProperty("url", deployUrl);
      props.setProperty("repositoryId", deploymentRepository.getId());
      props.setProperty("generatePom", "false");
      request.setProperties(props);

      getLog()
          .info(
              "Deploying aggregated zip using: mvn deploy:deploy-file"
                  + serializeMvnProperties(props));
      Invoker invoker = new DefaultInvoker();
      try {
        InvocationResult result = invoker.execute(request);
        if (result.getExitCode() != 0) {
          throw new IllegalStateException("Error invoking Maven goal deploy:deploy-file");
        }
      } catch (MavenInvocationException e) {
        throw new MojoExecutionException("Error invoking Maven goal deploy:deploy-file", e);
      }
    }
  }
Ejemplo n.º 27
0
  protected void doExecute() throws Exception {
    startupRepositories = nonNullList(startupRepositories);
    bootRepositories = nonNullList(bootRepositories);
    installedRepositories = nonNullList(installedRepositories);
    startupBundles = nonNullList(startupBundles);
    bootBundles = nonNullList(bootBundles);
    installedBundles = nonNullList(installedBundles);
    blacklistedBundles = nonNullList(blacklistedBundles);
    startupFeatures = nonNullList(startupFeatures);
    bootFeatures = nonNullList(bootFeatures);
    installedFeatures = nonNullList(installedFeatures);
    blacklistedFeatures = nonNullList(blacklistedFeatures);
    startupProfiles = nonNullList(startupProfiles);
    bootProfiles = nonNullList(bootProfiles);
    installedProfiles = nonNullList(installedProfiles);
    blacklistedProfiles = nonNullList(blacklistedProfiles);

    if (!startupProfiles.isEmpty() || !bootProfiles.isEmpty() || !installedProfiles.isEmpty()) {
      if (profilesUri == null) {
        throw new IllegalArgumentException("profilesDirectory must be specified");
      }
    }

    if (featureRepositories != null && !featureRepositories.isEmpty()) {
      getLog()
          .warn(
              "Use of featureRepositories is deprecated, use startupRepositories, bootRepositories or installedRepositories instead");
      startupRepositories.addAll(featureRepositories);
      bootRepositories.addAll(featureRepositories);
      installedRepositories.addAll(featureRepositories);
    }

    StringBuilder remote = new StringBuilder();
    for (Object obj : project.getRemoteProjectRepositories()) {
      if (remote.length() > 0) {
        remote.append(",");
      }
      remote.append(invoke(obj, "getUrl"));
      remote.append("@id=").append(invoke(obj, "getId"));
      if (!((Boolean) invoke(getPolicy(obj, false), "isEnabled"))) {
        remote.append("@noreleases");
      }
      if ((Boolean) invoke(getPolicy(obj, true), "isEnabled")) {
        remote.append("@snapshots");
      }
    }
    getLog().info("Using repositories: " + remote.toString());

    Builder builder = Builder.newInstance();
    builder.offline(mavenSession.isOffline());
    builder.localRepository(localRepo.getBasedir());
    builder.mavenRepositories(remote.toString());
    builder.javase(javase);

    // Set up blacklisted items
    builder.blacklistBundles(blacklistedBundles);
    builder.blacklistFeatures(blacklistedFeatures);
    builder.blacklistProfiles(blacklistedProfiles);
    builder.blacklistPolicy(blacklistPolicy);

    if (propertyFileEdits != null) {
      File file = new File(propertyFileEdits);
      if (file.exists()) {
        KarafPropertyEdits edits;
        try (InputStream editsStream = new FileInputStream(propertyFileEdits)) {
          KarafPropertyInstructionsModelStaxReader kipmsr =
              new KarafPropertyInstructionsModelStaxReader();
          edits = kipmsr.read(editsStream, true);
        }
        builder.propertyEdits(edits);
      }
    }

    Map<String, String> urls = new HashMap<>();
    List<Artifact> artifacts = new ArrayList<>(project.getAttachedArtifacts());
    artifacts.add(project.getArtifact());
    for (Artifact artifact : artifacts) {
      if (artifact.getFile() != null && artifact.getFile().exists()) {
        String mvnUrl =
            "mvn:"
                + artifact.getGroupId()
                + "/"
                + artifact.getArtifactId()
                + "/"
                + artifact.getVersion();
        String type = artifact.getType();
        if ("bundle".equals(type)) {
          type = "jar";
        }
        if (!"jar".equals(type) || artifact.getClassifier() != null) {
          mvnUrl += "/" + type;
          if (artifact.getClassifier() != null) {
            mvnUrl += "/" + artifact.getClassifier();
          }
        }
        urls.put(mvnUrl, artifact.getFile().toURI().toString());
      }
    }
    if (translatedUrls != null) {
      urls.putAll(translatedUrls);
    }
    builder.translatedUrls(urls);

    // creating system directory
    getLog().info("Creating work directory");
    builder.homeDirectory(workDirectory.toPath());
    IoUtils.deleteRecursive(workDirectory);
    workDirectory.mkdirs();

    List<String> startupKars = new ArrayList<>();
    List<String> bootKars = new ArrayList<>();
    List<String> installedKars = new ArrayList<>();

    // Loading kars and features repositories
    getLog().info("Loading kar and features repositories dependencies");
    for (Artifact artifact : project.getDependencyArtifacts()) {
      Builder.Stage stage;
      switch (artifact.getScope()) {
        case "compile":
          stage = Builder.Stage.Startup;
          break;
        case "runtime":
          stage = Builder.Stage.Boot;
          break;
        case "provided":
          stage = Builder.Stage.Installed;
          break;
        default:
          continue;
      }
      if ("kar".equals(artifact.getType())) {
        String uri = artifactToMvn(artifact);
        switch (stage) {
          case Startup:
            startupKars.add(uri);
            break;
          case Boot:
            bootKars.add(uri);
            break;
          case Installed:
            installedKars.add(uri);
            break;
        }
      } else if ("features".equals(artifact.getClassifier())) {
        String uri = artifactToMvn(artifact);
        switch (stage) {
          case Startup:
            startupRepositories.add(uri);
            break;
          case Boot:
            bootRepositories.add(uri);
            break;
          case Installed:
            installedRepositories.add(uri);
            break;
        }
      } else if ("jar".equals(artifact.getType()) || "bundle".equals(artifact.getType())) {
        String uri = artifactToMvn(artifact);
        switch (stage) {
          case Startup:
            startupBundles.add(uri);
            break;
          case Boot:
            bootBundles.add(uri);
            break;
          case Installed:
            installedBundles.add(uri);
            break;
        }
      }
    }

    builder
        .karafVersion(karafVersion)
        .useReferenceUrls(useReferenceUrls)
        .defaultAddAll(installAllFeaturesByDefault)
        .ignoreDependencyFlag(ignoreDependencyFlag);
    if (profilesUri != null) {
      builder.profilesUris(profilesUri);
    }
    if (libraries != null) {
      builder.libraries(libraries.toArray(new String[libraries.size()]));
    }
    // Startup
    builder
        .defaultStage(Builder.Stage.Startup)
        .kars(toArray(startupKars))
        .repositories(
            startupFeatures.isEmpty() && startupProfiles.isEmpty() && installAllFeaturesByDefault,
            toArray(startupRepositories))
        .features(toArray(startupFeatures))
        .bundles(toArray(startupBundles))
        .profiles(toArray(startupProfiles));
    // Boot
    builder
        .defaultStage(Builder.Stage.Boot)
        .kars(toArray(bootKars))
        .repositories(
            bootFeatures.isEmpty() && bootProfiles.isEmpty() && installAllFeaturesByDefault,
            toArray(bootRepositories))
        .features(toArray(bootFeatures))
        .bundles(toArray(bootBundles))
        .profiles(toArray(bootProfiles));
    // Installed
    builder
        .defaultStage(Builder.Stage.Installed)
        .kars(toArray(installedKars))
        .repositories(
            installedFeatures.isEmpty()
                && installedProfiles.isEmpty()
                && installAllFeaturesByDefault,
            toArray(installedRepositories))
        .features(toArray(installedFeatures))
        .bundles(toArray(installedBundles))
        .profiles(toArray(installedProfiles));

    // Generate the assembly
    builder.generateAssembly();

    // Include project classes content
    if (includeBuildOutputDirectory)
      IoUtils.copyDirectory(new File(project.getBuild().getOutputDirectory()), workDirectory);

    // Overwrite assembly dir contents
    if (sourceDirectory.exists()) IoUtils.copyDirectory(sourceDirectory, workDirectory);

    // Chmod the bin/* scripts
    File[] files = new File(workDirectory, "bin").listFiles();
    if (files != null) {
      for (File file : files) {
        if (!file.getName().endsWith(".bat")) {
          try {
            Files.setPosixFilePermissions(
                file.toPath(), PosixFilePermissions.fromString("rwxr-xr-x"));
          } catch (Throwable ignore) {
            // we tried our best, perhaps the OS does not support posix file perms.
          }
        }
      }
    }
  }
  private void addFilteredUnpackedArtifact(
      final DependencySet dependencySet,
      final Artifact depArtifact,
      final MavenProject depProject,
      final Archiver archiver,
      final AssemblerConfigurationSource configSource)
      throws ArchiveCreationException, AssemblyFormattingException {
    logger.debug(
        "Adding dependency artifact "
            + depArtifact.getId()
            + " after filtering the unpacked contents.");

    final StringBuilder sb =
        new StringBuilder()
            .append(depArtifact.getGroupId())
            .append("_")
            .append(depArtifact.getArtifactId())
            .append("_")
            .append(depArtifact.getVersion());

    final String classifier = depArtifact.getClassifier();
    if (classifier != null) {
      sb.append("_").append(classifier);
    }

    sb.append(".").append(depArtifact.getType());

    final File dir = new File(configSource.getWorkingDirectory(), sb.toString());
    if (dir.exists()) {
      logger.debug(
          "NOT unpacking: "
              + depArtifact.getId()
              + ". Directory already exists in workdir:\n\t"
              + dir.getAbsolutePath());
    } else {
      dir.mkdirs();

      UnArchiver unarchiver;
      try {
        unarchiver = archiverManager.getUnArchiver(depArtifact.getFile());
      } catch (final NoSuchArchiverException e) {
        throw new ArchiveCreationException(
            "Failed to retrieve un-archiver for: "
                + depArtifact.getId()
                + ". Dependency filtering cannot proceed.",
            e);
      }

      unarchiver.setDestDirectory(dir);
      unarchiver.setOverwrite(true);
      unarchiver.setSourceFile(depArtifact.getFile());
      unarchiver.setIgnorePermissions(configSource.isIgnorePermissions());

      try {
        unarchiver.extract();
      } catch (final ArchiverException e) {
        throw new ArchiveCreationException(
            "Failed to unpack dependency archive: "
                + depArtifact.getId()
                + ". Dependency filtering cannot proceed.",
            e);
      }
    }

    final UnpackOptions opts = dependencySet.getUnpackOptions();

    final FileSet fs = new FileSet();
    fs.setDirectory(dir.getAbsolutePath());
    fs.setDirectoryMode(dependencySet.getDirectoryMode());
    fs.setExcludes(opts.getExcludes());
    fs.setFileMode(dependencySet.getFileMode());
    fs.setFiltered(opts.isFiltered());
    fs.setIncludes(opts.getIncludes());

    String outDir = dependencySet.getOutputDirectory();
    if (outDir == null) {
      outDir = defaultOutputDirectory;
    }

    String filenameMapping = dependencySet.getOutputFileNameMapping();
    if (filenameMapping == null) {
      filenameMapping = defaultOutputFileNameMapping;
    }

    filenameMapping =
        AssemblyFormatUtils.evaluateFileNameMapping(
            filenameMapping,
            depArtifact,
            configSource.getProject(),
            moduleProject,
            moduleArtifact,
            depProject,
            configSource);

    final String outputLocation = new File(outDir, filenameMapping).getPath();

    fs.setOutputDirectory(outputLocation);

    fs.setLineEnding(opts.getLineEnding());
    fs.setUseDefaultExcludes(opts.isUseDefaultExcludes());

    final AddFileSetsTask task = new AddFileSetsTask(fs);
    task.setProject(depProject);
    task.setModuleProject(moduleProject);
    task.setLogger(logger);

    task.execute(archiver, configSource);
  }
  private void resolveOld(
      Artifact artifact,
      List<ArtifactRepository> remoteRepositories,
      RepositorySystemSession session)
      throws ArtifactResolutionException, ArtifactNotFoundException {
    if (artifact == null) {
      return;
    }

    if (Artifact.SCOPE_SYSTEM.equals(artifact.getScope())) {
      File systemFile = artifact.getFile();

      if (systemFile == null) {
        throw new ArtifactNotFoundException(
            "System artifact: " + artifact + " has no file attached", artifact);
      }

      if (!systemFile.exists()) {
        throw new ArtifactNotFoundException(
            "System artifact: " + artifact + " not found in path: " + systemFile, artifact);
      }

      if (!systemFile.isFile()) {
        throw new ArtifactNotFoundException(
            "System artifact: " + artifact + " is not a file: " + systemFile, artifact);
      }

      artifact.setResolved(true);

      return;
    }

    if (!artifact.isResolved()) {
      ArtifactResult result;

      try {
        ArtifactRequest artifactRequest = new ArtifactRequest();
        artifactRequest.setArtifact(RepositoryUtils.toArtifact(artifact));
        artifactRequest.setRepositories(RepositoryUtils.toRepos(remoteRepositories));

        // Maven 2.x quirk: an artifact always points at the local repo, regardless whether resolved
        // or not
        LocalRepositoryManager lrm = session.getLocalRepositoryManager();
        String path = lrm.getPathForLocalArtifact(artifactRequest.getArtifact());
        artifact.setFile(new File(lrm.getRepository().getBasedir(), path));

        result = repoSystem.resolveArtifact(session, artifactRequest);
      } catch (org.eclipse.aether.resolution.ArtifactResolutionException e) {
        if (e.getCause() instanceof org.eclipse.aether.transfer.ArtifactNotFoundException) {
          throw new ArtifactNotFoundException(
              e.getMessage(),
              artifact.getGroupId(),
              artifact.getArtifactId(),
              artifact.getVersion(),
              artifact.getType(),
              artifact.getClassifier(),
              remoteRepositories,
              artifact.getDownloadUrl(),
              artifact.getDependencyTrail(),
              e);
        } else {
          throw new ArtifactResolutionException(e.getMessage(), artifact, remoteRepositories, e);
        }
      }

      artifact.selectVersion(result.getArtifact().getVersion());
      artifact.setFile(result.getArtifact().getFile());
      artifact.setResolved(true);

      if (artifact.isSnapshot()) {
        Matcher matcher = Artifact.VERSION_FILE_PATTERN.matcher(artifact.getVersion());
        if (matcher.matches()) {
          Snapshot snapshot = new Snapshot();
          snapshot.setTimestamp(matcher.group(2));
          try {
            snapshot.setBuildNumber(Integer.parseInt(matcher.group(3)));
            artifact.addMetadata(new SnapshotArtifactRepositoryMetadata(artifact, snapshot));
          } catch (NumberFormatException e) {
            logger.warn(
                "Invalid artifact version " + artifact.getVersion() + ": " + e.getMessage());
          }
        }
      }
    }
  }
Ejemplo n.º 30
0
 private String artifactToKey(Artifact artifact) {
   return artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getClassifier();
 }