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

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

    try {

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

    return classpath;
  }
  protected File[] getGwtUserJar() throws MojoExecutionException {
    checkGwtUserVersion();
    Artifact gwtUserArtifact = getArtifact("com.google.gwt", "gwt-user");

    Set<Artifact> artifacts = new HashSet<Artifact>();
    ArtifactResolutionResult result = null;
    try {
      result =
          resolver.resolveTransitively(
              artifacts,
              gwtUserArtifact,
              remoteRepositories,
              localRepository,
              artifactMetadataSource);
    } catch (ArtifactResolutionException e) {
      throw new MojoExecutionException("Failed to resolve artifact", e);
    } catch (ArtifactNotFoundException e) {
      throw new MojoExecutionException("Failed to resolve artifact", e);
    }

    Collection<Artifact> resolved = result.getArtifacts();
    int i = 0;
    // FIXME gwt 2.3.0 don't declare dependency on javax.validation, should be fix in next release
    File[] files = new File[resolved.size() + 1 + 2];
    files[i++] = gwtUserArtifact.getFile();
    for (Artifact artifact : resolved) {
      files[i++] = artifact.getFile();
    }

    files[i++] = getArtifact("javax.validation", "validation-api").getFile();
    files[i++] = getArtifact("javax.validation", "validation-api", "sources").getFile();
    return files;
  }
  // 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;
  }
Exemplo n.º 4
0
  public static File getSdk(
      MavenProject project,
      RepositorySystem repoSystem,
      RepositorySystemSession repoSession,
      List<RemoteRepository>... repos)
      throws MojoExecutionException {
    Artifact artifact =
        (Artifact)
            find(
                project.getPluginArtifacts(),
                new Predicate<Artifact>() {
                  @Override
                  public boolean apply(Artifact artifact1) {
                    return artifact1.getArtifactId().equals("gcloud-maven-plugin");
                  }
                });

    String version = artifact.getVersion();

    if (version.endsWith("-SNAPSHOT")) {
      String newestVersion = determineNewestVersion(repoSystem, repoSession, repos);
      return getSdk(newestVersion, repoSystem, repoSession, repos);
    }

    return getSdk("1.9.30", repoSystem, repoSession, repos);
  }
  /** Finds and lists dependency plugins. */
  private String findDependencyPlugins() throws IOException, MojoExecutionException {
    StringBuilder buf = new StringBuilder();
    for (MavenArtifact a : getDirectDependencyArtfacts()) {
      if (a.isPlugin() && scopeFilter.include(a.artifact) && !a.hasSameGAAs(project)) {
        if (buf.length() > 0) buf.append(',');
        buf.append(a.getArtifactId());
        buf.append(':');
        buf.append(a.getVersion());
        if (a.isOptional()) {
          buf.append(";resolution:=optional");
        }
      }
    }

    // check any "provided" scope plugin dependencies that are probably not what the user intended.
    // see
    // http://www.nabble.com/Classloading-problem-when-referencing-classes-from-another-plugin-during-the-initialization-phase-of-a-plugin-%28ClassicPluginStrategy%29-td25426117.html
    for (Artifact a : (Collection<Artifact>) project.getDependencyArtifacts())
      if ("provided".equals(a.getScope()) && wrap(a).isPlugin())
        throw new MojoExecutionException(
            a.getId()
                + " is marked as 'provided' scope dependency, but it should be the 'compile' scope.");

    return buf.toString();
  }
  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();
  }
 private void generateApkLibRs() throws MojoExecutionException {
   getLog().debug("Generating Rs for apklib deps of project " + project.getArtifact());
   for (final Artifact artifact : getTransitiveDependencyArtifacts(APKLIB)) {
     getLog().debug("Generating apklib R.java for " + artifact.getArtifactId() + "...");
     generateRForApkLibDependency(artifact);
   }
 }
 @SuppressWarnings("unchecked")
 private Set<Artifact> getAllArtifacts() throws MojoExecutionException {
   Set<Artifact> artifacts = new LinkedHashSet<Artifact>();
   for (Dependency dep : (List<Dependency>) project.getDependencies()) {
     VersionRange versionRange;
     try {
       versionRange = VersionRange.createFromVersionSpec(dep.getVersion());
     } catch (InvalidVersionSpecificationException e) {
       throw new MojoExecutionException(
           String.format(
               "%1s: unable to parse version '%2s' for dependency '%3s': %4s",
               dep.getArtifactId(), dep.getVersion(), dep.getManagementKey(), e.getMessage()),
           e);
     }
     String type = dep.getType() == null ? "jar" : dep.getType();
     boolean optional = dep.isOptional();
     String scope = dep.getScope() == null ? Artifact.SCOPE_COMPILE : dep.getScope();
     Artifact artifact =
         artifactFactory.createDependencyArtifact(
             dep.getGroupId(),
             dep.getArtifactId(),
             versionRange,
             type,
             dep.getClassifier(),
             scope,
             optional);
     if (scope.equalsIgnoreCase(Artifact.SCOPE_SYSTEM)) {
       artifact.setFile(new File(dep.getSystemPath()));
     }
     handleExclusions(artifact, dep);
     artifacts.add(artifact);
   }
   return artifacts;
 }
Exemplo n.º 9
0
  private void copyNativeLibraryArtifactFileToDirectory(
      Artifact artifact, File destinationDirectory, String ndkArchitecture)
      throws MojoExecutionException {

    final File artifactFile = getArtifactResolverHelper().resolveArtifactToFile(artifact);
    try {
      final String artifactId = artifact.getArtifactId();
      String filename =
          artifactId.startsWith("lib") ? artifactId + ".so" : "lib" + artifactId + ".so";
      if (ndkFinalLibraryName != null
          && artifact.getFile().getName().startsWith("lib" + ndkFinalLibraryName)) {
        // The artifact looks like one we built with the NDK in this module
        // preserve the name from the NDK build
        filename = artifact.getFile().getName();
      }

      final File finalDestinationDirectory =
          getFinalDestinationDirectoryFor(artifact, destinationDirectory, ndkArchitecture);
      final File file = new File(finalDestinationDirectory, filename);
      getLog()
          .debug(
              "Copying native dependency "
                  + artifactId
                  + " ("
                  + artifact.getGroupId()
                  + ") to "
                  + file);
      FileUtils.copyFile(artifactFile, file);
    } catch (Exception e) {
      throw new MojoExecutionException("Could not copy native dependency.", e);
    }
  }
Exemplo n.º 10
0
  /**
   * Get the set of artifacts that are provided by Synapse at runtime.
   *
   * @return
   * @throws MojoExecutionException
   */
  private Set<Artifact> getSynapseRuntimeArtifacts() throws MojoExecutionException {
    Log log = getLog();
    log.debug("Looking for synapse-core artifact in XAR project dependencies ...");
    Artifact synapseCore = null;
    for (Iterator<?> it = project.getDependencyArtifacts().iterator(); it.hasNext(); ) {
      Artifact artifact = (Artifact) it.next();
      if (artifact.getGroupId().equals("org.apache.synapse")
          && artifact.getArtifactId().equals("synapse-core")) {
        synapseCore = artifact;
        break;
      }
    }
    if (synapseCore == null) {
      throw new MojoExecutionException("Could not locate dependency on synapse-core");
    }

    log.debug("Loading project data for " + synapseCore + " ...");
    MavenProject synapseCoreProject;
    try {
      synapseCoreProject =
          projectBuilder.buildFromRepository(
              synapseCore, remoteArtifactRepositories, localRepository);
    } catch (ProjectBuildingException e) {
      throw new MojoExecutionException(
          "Unable to retrieve project information for " + synapseCore, e);
    }
    Set<Artifact> synapseRuntimeDeps;
    try {
      synapseRuntimeDeps =
          synapseCoreProject.createArtifacts(
              artifactFactory, Artifact.SCOPE_RUNTIME, new TypeArtifactFilter("jar"));
    } catch (InvalidDependencyVersionException e) {
      throw new MojoExecutionException("Unable to get project dependencies for " + synapseCore, e);
    }
    log.debug("Direct runtime dependencies for " + synapseCore + " :");
    logArtifacts(synapseRuntimeDeps);

    log.debug("Resolving transitive dependencies for " + synapseCore + " ...");
    try {
      synapseRuntimeDeps =
          artifactCollector
              .collect(
                  synapseRuntimeDeps,
                  synapseCoreProject.getArtifact(),
                  synapseCoreProject.getManagedVersionMap(),
                  localRepository,
                  remoteArtifactRepositories,
                  artifactMetadataSource,
                  null,
                  Collections.singletonList(new DebugResolutionListener(logger)))
              .getArtifacts();
    } catch (ArtifactResolutionException e) {
      throw new MojoExecutionException(
          "Unable to resolve transitive dependencies for " + synapseCore);
    }
    log.debug("All runtime dependencies for " + synapseCore + " :");
    logArtifacts(synapseRuntimeDeps);

    return synapseRuntimeDeps;
  }
Exemplo n.º 11
0
 /**
  * Build a filter that excludes all artifacts that are provided by Synapse at runtime.
  *
  * @return
  * @throws MojoExecutionException
  */
 private ArtifactFilter buildSynapseRuntimeArtifactFilter() throws MojoExecutionException {
   final Map<String, Artifact> artifacts = new HashMap<String, Artifact>();
   for (Artifact artifact : getSynapseRuntimeArtifacts()) {
     artifacts.put(artifact.getDependencyConflictId(), artifact);
   }
   final Set<String> defaultExclusionSet =
       new HashSet<String>(Arrays.asList(defaultRuntimeExcludes));
   return new ArtifactFilter() {
     public boolean include(Artifact artifact) {
       Artifact runtimeArtifact = artifacts.get(artifact.getDependencyConflictId());
       if (runtimeArtifact == null) {
         return !defaultExclusionSet.contains(artifact.getDependencyConflictId());
       } else {
         if (!runtimeArtifact.getVersion().equals(artifact.getVersion())) {
           getLog()
               .warn(
                   "Possible runtime version conflict for "
                       + artifact.getArtifactId()
                       + ": XAR depends on "
                       + artifact.getVersion()
                       + ", Synapse runtime provides "
                       + runtimeArtifact.getVersion());
         }
         return false;
       }
     }
   };
 }
  /**
   * Creates a string containing the classpath for running this Cassandra node as a CassandraDaemon
   * in a separate JVM process.
   *
   * <p>Uses the dependencies for the plugin to form the classpath, since the plugin is dependent
   * upon Cassandra.
   *
   * @return the classpath, as a colon-separated String.
   */
  private String getClasspath() {
    // Copied mostly from the Codehaus Cassandra plugin.

    StringBuilder cp = new StringBuilder();
    try {
      // We can't use StringUtils.join here since we need to add a '/' to
      // the end of directory entries - otherwise the jvm will ignore them.
      cp.append(new URL(mConfDir.toURI().toASCIIString()).toExternalForm());
      cp.append(CLASSPATH_SEPARATOR);

      for (Artifact artifact : mCassandraConfiguration.getPluginDependencies()) {
        getLog()
            .debug(
                "Adding plugin dependency artifact: "
                    + ArtifactUtils.versionlessKey(artifact)
                    + " to the classpath");
        // NOTE: if File points to a directory, this entry MUST end in '/'.
        cp.append(new URL(artifact.getFile().toURI().toASCIIString()).toExternalForm());
        cp.append(CLASSPATH_SEPARATOR);
      }
    } catch (MalformedURLException mue) {
      getLog().error("Could not create URL for conf dir " + mConfDir + "?!");
    }
    return cp.toString();
  }
 private boolean isKnownJsf2BasedArtifact(Artifact artifact) {
   return (artifact.getGroupId().startsWith("org.jboss.seam.") // $NON-NLS-1$
           && artifact.getArtifactId().startsWith("seam-faces") // $NON-NLS-1$
           && artifact.getVersion().startsWith("3."))
       || ("org.apache.deltaspike.modules".equals(artifact.getGroupId()) // $NON-NLS-1$
           && artifact.getArtifactId().startsWith("deltaspike-jsf-module")); // $NON-NLS-1$		
 }
Exemplo n.º 14
0
  /** Check gwt-user dependency matches plugin version */
  private void checkGwtUserVersion() throws MojoExecutionException {
    InputStream inputStream =
        Thread.currentThread()
            .getContextClassLoader()
            .getResourceAsStream("org/codehaus/mojo/gwt/mojoGwtVersion.properties");
    Properties properties = new Properties();
    try {
      properties.load(inputStream);

    } catch (IOException e) {
      throw new MojoExecutionException("Failed to load plugin properties", e);
    } finally {
      IOUtils.closeQuietly(inputStream);
    }
    for (Iterator iterator = getProject().getCompileArtifacts().iterator(); iterator.hasNext(); ) {
      Artifact artifact = (Artifact) iterator.next();
      if (GWT_GROUP_ID.equals(artifact.getGroupId())
          && "gwt-user".equals(artifact.getArtifactId())) {
        String mojoGwtVersion = properties.getProperty("gwt.version");
        // ComparableVersion with an up2date maven version
        ArtifactVersion mojoGwtArtifactVersion = new DefaultArtifactVersion(mojoGwtVersion);
        ArtifactVersion userGwtArtifactVersion = new DefaultArtifactVersion(artifact.getVersion());
        if (userGwtArtifactVersion.compareTo(mojoGwtArtifactVersion) < 0) {
          getLog()
              .warn(
                  "You're project declares dependency on gwt-user "
                      + artifact.getVersion()
                      + ". This plugin is designed for at least gwt version "
                      + mojoGwtVersion);
        }
        break;
      }
    }
  }
Exemplo n.º 15
0
 private String getDefaultFinalName(final Artifact artifact) {
   return artifact.getArtifactId()
       + "-"
       + artifact.getVersion()
       + "."
       + artifact.getArtifactHandler().getExtension();
 }
  private void addDependencies(final MavenProject project, final JettyWebAppContext webAppConfig)
      throws Exception {
    List<File> dependencyFiles = new ArrayList<File>();
    List<Resource> overlays = new ArrayList<Resource>();

    for (Artifact artifact : project.getArtifacts()) {
      if (artifact.getType().equals("war")) {
        overlays.add(Resource.newResource("jar:" + artifact.getFile().toURL().toString() + "!/"));
      } else if ((!Artifact.SCOPE_PROVIDED.equals(artifact.getScope()))
          && (!Artifact.SCOPE_TEST.equals(artifact.getScope()))) {
        File dependencyFile = artifact.getFile();

        if (dependencyFile == null || !dependencyFile.exists()) {
          String coordinates =
              String.format(
                  "%s:%s:%s",
                  artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion());

          LOG.log(
              Level.WARNING,
              "Dependency '" + coordinates + "' does not exist in repository. Skipping!");
          continue;
        }

        dependencyFiles.add(artifact.getFile());
      }
    }

    webAppConfig.setOverlays(overlays);
    webAppConfig.setWebInfLib(dependencyFiles);
  }
Exemplo n.º 17
0
 private void createClasspathJarFile(File lib) throws Exception {
   getLog().info("[WarSync] Create warsync-classpath.jar in " + lib.getAbsolutePath());
   List<String> jarFiles = new ArrayList<String>();
   if (artifacts != null && !artifacts.isEmpty()) {
     for (Artifact artifact : artifacts) {
       if (getLog().isDebugEnabled()) {
         getLog().debug("[WarSync] Found dependency: " + artifact.getId());
       }
       if (isLib(artifact)) {
         if (getLog().isDebugEnabled()) {
           getLog()
               .debug(
                   "[WarSync] Add "
                       + artifact.getFile().toURI().getPath()
                       + " to Class-Path entry of MANIFEST.MF");
         }
         jarFiles.add(artifact.getFile().toURI().getPath());
       }
     }
   }
   JarArchiver jar = new JarArchiver();
   jar.setDestFile(new File(lib, "warsync-classpath.jar"));
   Manifest manifest = Manifest.getDefaultManifest();
   manifest.addConfiguredAttribute(new Manifest.Attribute("Created-By", "maven-warsync-plugin"));
   manifest.addConfiguredAttribute(
       new Manifest.Attribute("Built-By", System.getProperty("user.name")));
   manifest.addConfiguredAttribute(
       new Manifest.Attribute("Build-Jdk", System.getProperty("java.version")));
   if (!jarFiles.isEmpty()) {
     manifest.addConfiguredAttribute(
         new Manifest.Attribute("Class-Path", StringUtils.join(jarFiles.iterator(), " ")));
   }
   jar.addConfiguredManifest(manifest);
   jar.createArchive();
 }
  /**
   * Returns <code>true</code> if the update should be applied.
   *
   * @param artifact The artifact.
   * @param currentVersion The current version of the artifact.
   * @param updateVersion The proposed new version of the artifact.
   * @return <code>true</code> if the update should be applied.
   * @since 1.0-alpha-1
   */
  protected boolean shouldApplyUpdate(
      Artifact artifact, String currentVersion, ArtifactVersion updateVersion) {
    getLog().debug("Proposal is to update from " + currentVersion + " to " + updateVersion);

    if (updateVersion == null) {
      getLog().warn("Not updating version: could not resolve any versions");
      return false;
    }

    artifact.setVersion(updateVersion.toString());
    try {
      resolver.resolveAlways(artifact, remoteArtifactRepositories, localRepository);
    } catch (ArtifactResolutionException e) {
      getLog().warn("Not updating version: could not resolve " + artifact.toString(), e);
      return false;
    } catch (ArtifactNotFoundException e) {
      getLog().warn("Not updating version: could not find " + artifact.toString(), e);
      return false;
    }

    if (currentVersion.equals(updateVersion.toString())) {
      getLog().info("Current version of " + artifact.toString() + " is the latest.");
      return false;
    }
    return true;
  }
  /**
   * Checks packages in AndroidManifest.xml file of project and all dependent libraries for
   * duplicates.
   *
   * <p>Generate warning if duplicates presents.
   *
   * <p>(in case of packages similarity R.java and BuildConfig files will be overridden)
   *
   * @throws MojoExecutionException
   */
  private void checkPackagesForDuplicates() throws MojoExecutionException {
    Set<Artifact> dependencyArtifacts = getTransitiveDependencyArtifacts(AAR, APKLIB);

    if (dependencyArtifacts.isEmpty()) {
      // if no AAR or APKLIB dependencies presents than only one package presents
      return;
    }

    Map<String, Set<Artifact>> packageCompareMap = getPackageCompareMap(dependencyArtifacts);

    List<String> messageList = new ArrayList<String>();
    for (Map.Entry<String, Set<Artifact>> entry : packageCompareMap.entrySet()) {
      Set<Artifact> artifacts = entry.getValue();
      if (artifacts != null && artifacts.size() > 1) {
        StringBuilder messageBuilder = new StringBuilder();
        for (Artifact item : artifacts) {
          if (messageBuilder.length() > 0) {
            messageBuilder.append(", ");
          }
          messageBuilder.append(item.getArtifactId());
        }
        messageBuilder.append(" have similar package: '").append(entry.getKey()).append("'");
        messageList.add(messageBuilder.toString());
      }
    }
    if (messageList.size() > 0) {
      getLog()
          .warn("Duplicate packages detected in AndroidManifest.xml file for the next artifacts:");
      for (String messageLine : messageList) {
        getLog().warn(messageLine);
      }
    }
  }
Exemplo n.º 20
0
 /**
  * Get the artifact which refers to the POM of the executable artifact.
  *
  * @param executableArtifact this artifact refers to the actual assembly.
  * @return an artifact which refers to the POM of the executable artifact.
  */
 private Artifact getExecutablePomArtifact(Artifact executableArtifact) {
   return this.artifactFactory.createBuildArtifact(
       executableArtifact.getGroupId(),
       executableArtifact.getArtifactId(),
       executableArtifact.getVersion(),
       "pom");
 }
Exemplo n.º 21
0
  public void execute() throws MojoExecutionException {
    try {
      File out = new File(project.getBasedir(), jars);
      for (Iterator i = getIncludedArtifacts().iterator(); i.hasNext(); ) {
        Artifact a = (Artifact) i.next();
        FileUtils.copyFileToDirectory(a.getFile(), out);
      }

      if (packageSources) {
        packageSources(getIncludedArtifacts());
      }

      Manifest manifest = getManifest();
      File metaInf = new File(project.getBasedir(), "META-INF");
      metaInf.mkdirs();
      BufferedOutputStream os =
          new BufferedOutputStream(new FileOutputStream(new File(metaInf, "MANIFEST.MF")));
      manifest.write(os);
      os.close();

      //			packageBundle();
    } catch (Exception e) {
      throw new MojoExecutionException(e.getMessage(), e);
    }
  }
Exemplo n.º 22
0
  /**
   * Set up the execution classpath for Jasper.
   *
   * <p>Put everything in the classesDirectory and all of the dependencies on the classpath.
   *
   * @returns a list of the urls of the dependencies
   * @throws Exception
   */
  private List<URL> setUpWebAppClassPath() throws Exception {
    // add any classes from the webapp
    List<URL> urls = new ArrayList<URL>();
    String classesDir = classesDirectory.getCanonicalPath();
    classesDir = classesDir + (classesDir.endsWith(File.pathSeparator) ? "" : File.separator);
    urls.add(Resource.toURL(new File(classesDir)));

    if (getLog().isDebugEnabled()) getLog().debug("Adding to classpath classes dir: " + classesDir);

    // add the dependencies of the webapp (which will form WEB-INF/lib)
    for (Iterator<Artifact> iter = project.getArtifacts().iterator(); iter.hasNext(); ) {
      Artifact artifact = (Artifact) iter.next();

      // Include runtime and compile time libraries
      if (!Artifact.SCOPE_TEST.equals(artifact.getScope())
          && !Artifact.SCOPE_PROVIDED.equals(artifact.getScope())) {
        String filePath = artifact.getFile().getCanonicalPath();
        if (getLog().isDebugEnabled())
          getLog().debug("Adding to classpath dependency file: " + filePath);

        urls.add(Resource.toURL(artifact.getFile()));
      }
    }
    return urls;
  }
 /*
  * Resolve an artifact, downloading it from remote repositories when necessary
  */
 private Object resolve(String bundle) throws Exception, ArtifactNotFoundException {
   if (!isMavenProtocol(bundle)) {
     return bundle;
   }
   Artifact artifact = getArtifact(bundle);
   if (bundle.indexOf(MVN_REPO_SEPARATOR) >= 0) {
     if (bundle.startsWith(MVN_URI_PREFIX)) {
       bundle = bundle.substring(MVN_URI_PREFIX.length());
     }
     String repo = bundle.substring(0, bundle.indexOf(MVN_REPO_SEPARATOR));
     ArtifactRepository repository =
         new DefaultArtifactRepository(
             artifact.getArtifactId() + "-repo", repo, new DefaultRepositoryLayout());
     List<ArtifactRepository> repos = new LinkedList<ArtifactRepository>();
     repos.add(repository);
     resolver.resolve(artifact, repos, localRepo);
   } else {
     resolver.resolve(artifact, remoteRepos, localRepo);
   }
   if (artifact == null) {
     throw new Exception("Unable to resolve artifact for uri " + bundle);
   } else {
     return artifact;
   }
 }
  static String getDependenciesText(AbstractJnlpMojo config) {
    String dependenciesText = "";
    List artifacts = config.getPackagedJnlpArtifacts();
    if (artifacts.size() != 0) {
      StringBuffer buffer = new StringBuffer(100 * artifacts.size());
      buffer.append("\n");

      String jarLibPath = null;
      if (config.getLibPath() != null) {
        jarLibPath = config.getLibPath();
        jarLibPath =
            (jarLibPath != null && jarLibPath.trim().length() != 0) ? jarLibPath.trim() : null;
      }

      for (int i = 0; i < artifacts.size(); i++) {
        Artifact artifact = (Artifact) artifacts.get(i);
        buffer.append("<jar href=\"");
        if (jarLibPath != null) {
          buffer.append(jarLibPath).append("/");
        }
        buffer.append(artifact.getFile().getName()).append("\"");

        if (config.isOutputJarVersions()) {
          buffer.append(" version=\"").append(artifact.getVersion()).append("\"");
        }

        if (config.isArtifactWithMainClass(artifact)) {
          buffer.append(" main=\"true\"");
        }
        buffer.append("/>\n");
      }
      dependenciesText = buffer.toString();
    }
    return dependenciesText;
  }
Exemplo n.º 25
0
  private List<ResourceDirectory> arrangeAsDependency(
      File overlayDirectory, File[] artifactIdDirs) {
    Set dependencyArtifacts = getMavenProject().getDependencyArtifacts();
    final Iterator it = dependencyArtifacts.iterator();

    final List<ResourceDirectory> result = new ArrayList<ResourceDirectory>();
    while (it.hasNext()) {
      ResourceDirectory resourceDirectory = null;
      Artifact artifact = (Artifact) it.next();
      if ("js".equals(artifact.getType())) {
        File resource = getJsArtifactAsResource(overlayDirectory, artifact);
        resourceDirectory =
            new ResourceDirectory(
                resource, ResourceDirectory.DEFAULT_INCLUDES, ResourceDirectory.DEFAULT_EXCLUDES);
      } else {
        resourceDirectory = getArtifactAsResource(artifact, artifactIdDirs);
      }

      if (resourceDirectory != null) {
        result.add(resourceDirectory);
      }
    }

    return result;
  }
Exemplo n.º 26
0
  /**
   * Merge WsdlOptions that point to the same file by adding the extraargs to the first option and
   * deleting the second from the options list
   *
   * @param options
   */
  @SuppressWarnings("unchecked")
  private Artifact resolveRemoteWsdlArtifact(List<?> remoteRepos, Artifact artifact)
      throws MojoExecutionException {

    /**
     * First try to find the artifact in the reactor projects of the maven session. So an artifact
     * that is not yet built can be resolved
     */
    List<MavenProject> rProjects = mavenSession.getSortedProjects();
    for (MavenProject rProject : rProjects) {
      if (artifact.getGroupId().equals(rProject.getGroupId())
          && artifact.getArtifactId().equals(rProject.getArtifactId())
          && artifact.getVersion().equals(rProject.getVersion())) {
        Set<Artifact> artifacts = rProject.getArtifacts();
        for (Artifact pArtifact : artifacts) {
          if ("wadl".equals(pArtifact.getType())) {
            return pArtifact;
          }
        }
      }
    }

    /** If this did not work resolve the artifact using the artifactResolver */
    try {
      artifactResolver.resolve(artifact, remoteRepos, localRepository);
    } catch (ArtifactResolutionException e) {
      throw new MojoExecutionException("Error downloading wsdl artifact.", e);
    } catch (ArtifactNotFoundException e) {
      throw new MojoExecutionException("Resource can not be found.", e);
    }

    return artifact;
  }
  @Override
  protected void renderBody() {
    sink.section1();
    sink.sectionTitle1();
    sink.text("Overview");
    sink.sectionTitle1_();
    sink.section1_();

    sink.text(
        "This is the result of the screenshots compare of the current version '"
            + currentArtifact.getVersion()
            + "' and the latest version '"
            + previousArtifact.getVersion()
            + "'.");

    ImmutableListMultimap<String, VisualDiffMeta> perTest =
        VisualDiffMetaGrouper.byTestClass(diffs);
    VisualDiffReportUtil.renderTable(sink, Depth.CLASS, "Test Classes Overview", perTest);

    for (String testClass : perTest.keySet()) {
      ImmutableListMultimap<String, VisualDiffMeta> perMethod =
          VisualDiffMetaGrouper.byTestMethod(perTest.get(testClass));
      VisualDiffReportUtil.renderTable(sink, Depth.METHOD, "Test " + testClass, perMethod);
    }
  }
Exemplo n.º 28
0
  protected void downloadRemoteDocs(List<WadlOption> effectiveOptions)
      throws MojoExecutionException {
    List<?> remoteRepos;
    try {
      remoteRepos =
          ProjectUtils.buildArtifactRepositories(
              repositories, artifactRepositoryFactory, mavenSession.getContainer());
    } catch (InvalidRepositoryException e) {
      throw new MojoExecutionException("Error build repositories for remote wsdls", e);
    }

    for (WadlOption option : effectiveOptions) {
      DocumentArtifact wsdlA = option.getWadlArtifact();
      if (wsdlA == null) {
        return;
      }
      Artifact wsdlArtifact =
          artifactFactory.createArtifact(
              wsdlA.getGroupId(),
              wsdlA.getArtifactId(),
              wsdlA.getVersion(),
              Artifact.SCOPE_COMPILE,
              wsdlA.getType());
      wsdlArtifact = resolveRemoteWsdlArtifact(remoteRepos, wsdlArtifact);
      if (wsdlArtifact != null) {
        String path = wsdlArtifact.getFile().getAbsolutePath();
        getLog().info("Resolved WSDL artifact to file " + path);
        option.setWadl(path);
      }
    }
  }
 private void checkRequiredApi() throws MojoExecutionException {
   Artifact api = getNullablePluginApiArtifact();
   if (api == null || !Artifact.SCOPE_PROVIDED.equals(api.getScope())) {
     throw new MojoExecutionException(
         SONAR_PLUGIN_API_ARTIFACTID + " must be declared in dependencies with scope <provided>");
   }
 }
  protected void setUp() throws Exception {
    // prepare plexus environment
    super.setUp();

    ajcMojo.project = project;
    String temp = new File(".").getAbsolutePath();
    basedir = temp.substring(0, temp.length() - 2) + "/src/test/projects/" + getProjectName() + "/";
    project.getBuild().setDirectory(basedir + "/target");
    project.getBuild().setOutputDirectory(basedir + "/target/classes");
    project.getBuild().setTestOutputDirectory(basedir + "/target/test-classes");
    project.getBuild().setSourceDirectory(basedir + "/src/main/java");
    project.getBuild().setTestSourceDirectory(basedir + "/src/test/java");
    project.addCompileSourceRoot(project.getBuild().getSourceDirectory());
    project.addTestCompileSourceRoot(project.getBuild().getTestSourceDirectory());
    ajcMojo.basedir = new File(basedir);

    setVariableValueToObject(
        ajcMojo, "outputDirectory", new File(project.getBuild().getOutputDirectory()));

    ArtifactHandler artifactHandler = new MockArtifactHandler();
    Artifact artifact = new MockArtifact("dill", "dall");
    artifact.setArtifactHandler(artifactHandler);
    project.setArtifact(artifact);
    project.setDependencyArtifacts(Collections.EMPTY_SET);
  }