Example #1
0
 private void checkRevision(ModuleRevisionId systemMrid) {
   // check revision
   int index = systemMrid.getRevision().indexOf("@");
   if (index != -1 && !systemMrid.getRevision().substring(index + 1).equals(workspaceName)) {
     throw new UnresolvedDependencyException(
         "\t" + getName() + ": unhandled revision => " + systemMrid.getRevision());
   }
 }
Example #2
0
 private static File getSubdir(File rootDir, ModuleRevisionId mr) {
   return new File(
       rootDir,
       mr.getOrganisation()
           + File.separatorChar
           + mr.getName()
           + File.separatorChar
           + mr.getRevision());
 }
Example #3
0
 private File downloadTimestampedVersion(Artifact artifact, String timestampedVersion)
     throws IOException {
   final ModuleRevisionId artifactModuleRevisionId = artifact.getModuleRevisionId();
   final ModuleRevisionId moduleRevisionId =
       ModuleRevisionId.newInstance(
           artifactModuleRevisionId.getOrganisation(),
           artifactModuleRevisionId.getName(),
           artifactModuleRevisionId.getRevision(),
           WrapUtil.toMap("timestamp", timestampedVersion));
   final Artifact artifactWithResolvedModuleRevisionId =
       DefaultArtifact.cloneWithAnotherMrid(artifact, moduleRevisionId);
   return download(artifactWithResolvedModuleRevisionId);
 }
Example #4
0
 private DependencyDescriptor enrichDependencyDescriptorWithSnapshotVersionInfo(
     DependencyDescriptor dd,
     ModuleRevisionId dependencyRevisionId,
     String uniqueSnapshotVersion) {
   Map<String, String> extraAttributes = new HashMap<String, String>(1);
   extraAttributes.put("timestamp", uniqueSnapshotVersion);
   final ModuleRevisionId newModuleRevisionId =
       ModuleRevisionId.newInstance(
           dependencyRevisionId.getOrganisation(),
           dependencyRevisionId.getName(),
           dependencyRevisionId.getRevision(),
           extraAttributes);
   return dd.clone(newModuleRevisionId);
 }
Example #5
0
 private void resolveAndCheckRevision(
     ModuleDescriptor systemMd,
     ModuleRevisionId dependencyConstraint,
     ResolvedResource ivyRef,
     boolean isDynamic) {
   // we get the resolved module revision id from the descriptor: it may contain extra
   // attributes that were not included in the dependency constraint
   ModuleRevisionId resolvedMrid = systemMd.getResolvedModuleRevisionId();
   if (resolvedMrid.getRevision() == null
       || resolvedMrid.getRevision().length() == 0
       || resolvedMrid.getRevision().startsWith("working@")) {
     if (!isDynamic) {
       resolvedMrid =
           ModuleRevisionId.newInstance(resolvedMrid, dependencyConstraint.getRevision());
     } else if (ivyRef == null) {
       resolvedMrid = systemMd.getMetadataArtifact().getModuleRevisionId();
     } else if (ivyRef.getRevision() == null || ivyRef.getRevision().length() == 0) {
       resolvedMrid = ModuleRevisionId.newInstance(resolvedMrid, "working@" + getName());
     } else {
       resolvedMrid = ModuleRevisionId.newInstance(resolvedMrid, ivyRef.getRevision());
     }
   }
   if (isDynamic) {
     Message.verbose(
         "\t\t["
             + toSystem(resolvedMrid).getRevision()
             + "] "
             + dependencyConstraint.getModuleId());
   }
   systemMd.setResolvedModuleRevisionId(resolvedMrid);
   checkModuleDescriptorRevision(systemMd, dependencyConstraint);
 }
Example #6
0
  protected ResolvedArtifact findIvyFileRef(DependencyDescriptor dd) {
    if (isUsepoms()) {
      ModuleRevisionId moduleRevisionId = dd.getDependencyRevisionId();
      ArtifactRevisionId artifactRevisionId =
          ArtifactRevisionId.newInstance(
              moduleRevisionId,
              moduleRevisionId.getName(),
              "pom",
              "pom",
              moduleRevisionId.getExtraAttributes());
      Artifact pomArtifact = new DefaultArtifact(artifactRevisionId, null, null, true);
      return findResourceUsingPatterns(moduleRevisionId, getIvyPatterns(), pomArtifact, true);
    }

    return null;
  }
 public void resolve(DependencyMetaData dependency, BuildableModuleVersionResolveResult result) {
   DependencyDescriptor descriptor = dependency.getDescriptor();
   if (descriptor instanceof ProjectDependencyDescriptor) {
     ProjectDependencyDescriptor desc = (ProjectDependencyDescriptor) descriptor;
     ModuleDescriptor moduleDescriptor = projectModuleRegistry.findProject(desc);
     final ModuleRevisionId moduleRevisionId = moduleDescriptor.getModuleRevisionId();
     final DefaultModuleVersionIdentifier moduleVersionIdentifier =
         new DefaultModuleVersionIdentifier(
             moduleRevisionId.getOrganisation(),
             moduleRevisionId.getName(),
             moduleRevisionId.getRevision());
     result.resolved(moduleVersionIdentifier, moduleDescriptor, artifactResolver);
   } else {
     resolver.resolve(dependency, result);
   }
 }
 private ResolvedModuleRevision resolveModule(
     IvySettings settings, FileSystemResolver resolver, String module) throws ParseException {
   return resolver.getDependency(
       new DefaultDependencyDescriptor(ModuleRevisionId.parse(module), false),
       new ResolveData(
           new ResolveEngine(settings, new EventManager(), new SortEngine(settings)),
           new ResolveOptions()));
 }
  public void doExecute() throws BuildException {
    if (organisation == null) {
      throw new BuildException("no organisation provided for ivy listmodules task");
    }
    if (module == null) {
      throw new BuildException("no module name provided for ivy listmodules task");
    }
    if (revision == null) {
      throw new BuildException("no revision provided for ivy listmodules task");
    }
    if (property == null) {
      throw new BuildException("no property provided for ivy listmodules task");
    }
    if (value == null) {
      throw new BuildException("no value provided for ivy listmodules task");
    }

    Ivy ivy = getIvyInstance();
    IvySettings settings = ivy.getSettings();

    SearchEngine searcher = new SearchEngine(settings);
    PatternMatcher patternMatcher = settings.getMatcher(matcher);

    ModuleRevisionId[] mrids;
    if (resolver == null) {
      mrids =
          searcher.listModules(
              ModuleRevisionId.newInstance(organisation, module, branch, revision), patternMatcher);
    } else {
      DependencyResolver depResolver = settings.getResolver(resolver);
      if (depResolver == null) {
        throw new BuildException("Unknown resolver: " + resolver);
      }
      mrids =
          searcher.listModules(
              depResolver,
              ModuleRevisionId.newInstance(organisation, module, branch, revision),
              patternMatcher);
    }

    for (int i = 0; i < mrids.length; i++) {
      String name = IvyPatternHelper.substitute(settings.substitute(property), mrids[i]);
      String value = IvyPatternHelper.substitute(settings.substitute(this.value), mrids[i]);
      getProject().setProperty(name, value);
    }
  }
Example #10
0
  private ModuleRevisionId getRevision(
      ResolvedResource ivyRef, ModuleRevisionId askedMrid, ModuleDescriptor md)
      throws ParseException {
    Map allAttributes = new HashMap();
    allAttributes.putAll(md.getQualifiedExtraAttributes());
    allAttributes.putAll(askedMrid.getQualifiedExtraAttributes());

    String revision = ivyRef.getRevision();
    if (revision == null) {
      Message.debug("no revision found in reference for " + askedMrid);
      if (getSettings().getVersionMatcher().isDynamic(askedMrid)) {
        if (md.getModuleRevisionId().getRevision() == null) {
          revision = "working@" + getName();
        } else {
          Message.debug("using " + askedMrid);
          revision = askedMrid.getRevision();
        }
      } else {
        Message.debug("using " + askedMrid);
        revision = askedMrid.getRevision();
      }
    }

    return ModuleRevisionId.newInstance(
        askedMrid.getOrganisation(),
        askedMrid.getName(),
        askedMrid.getBranch(),
        revision,
        allAttributes);
  }
Example #11
0
 private String getResourceURL() {
   String baseURL =
       IvyPatternHelper.substitute(
           resourceURL,
           mr.getOrganisation(),
           mr.getName(),
           mr.getRevision(),
           null,
           null,
           null,
           null,
           mr.getQualifiedExtraAttributes(),
           null);
   int slash = baseURL.lastIndexOf('/');
   if (slash != -1) {
     baseURL = baseURL.substring(0, slash + 1);
   }
   return baseURL;
 }
 public ModuleDescriptor createModuleDescriptor(
     ModuleRevisionId moduleRevisionId, Set<ModuleDependency> dependencies) {
   DefaultModuleDescriptor moduleDescriptor =
       new DefaultModuleDescriptor(moduleRevisionId, "release", null);
   moduleDescriptor.addConfiguration(new Configuration(Dependency.DEFAULT_CONFIGURATION));
   addDependencyDescriptors(moduleDescriptor, dependencies, dependencyDescriptorFactory);
   moduleDescriptor.addArtifact(
       Dependency.DEFAULT_CONFIGURATION,
       new DefaultArtifact(moduleRevisionId, null, moduleRevisionId.getName(), "jar", "jar"));
   return moduleDescriptor;
 }
  public void testUpdate() throws Exception {
    /*
     * For updated file to be equals to updated.xml, we have to fix the line separator to the
     * one used in updated.xml, in order for this test to works in all platforms (default line
     * separator used in updater being platform dependent
     */
    XmlModuleDescriptorUpdater.LINE_SEPARATOR = "\n";
    File dest = new File("build/updated-test.xml");
    dest.deleteOnExit();
    Map resolvedRevisions = new HashMap();
    resolvedRevisions.put(
        ModuleRevisionId.newInstance("yourorg", "yourmodule2", "branch1", "2+"), "2.5");
    resolvedRevisions.put(
        ModuleRevisionId.newInstance("yourorg", "yourmodule6", "trunk", "latest.integration"),
        "6.3");

    Map resolvedBranches = new HashMap();
    resolvedBranches.put(ModuleRevisionId.newInstance("yourorg", "yourmodule3", "3.1"), "branch1");
    resolvedBranches.put(
        ModuleRevisionId.newInstance("yourorg", "yourmodule2", "branch1", "2+"), null);

    GregorianCalendar cal = new GregorianCalendar();
    cal.set(2005, 2, 22, 14, 32, 54);

    Ivy ivy = Ivy.newInstance();
    ivy.setVariable("myvar", "myconf1");
    XmlModuleDescriptorUpdater.update(
        XmlModuleUpdaterTest.class.getResource("test-update.xml"),
        dest,
        getUpdateOptions(ivy.getSettings(), resolvedRevisions, "release", "mynewrev", cal.getTime())
            .setResolvedBranches(resolvedBranches));

    assertTrue(dest.exists());
    String expected =
        FileUtil.readEntirely(
            new BufferedReader(
                new InputStreamReader(
                    XmlModuleUpdaterTest.class.getResourceAsStream("updated.xml"))));
    String updated = FileUtil.readEntirely(new BufferedReader(new FileReader(dest)));
    assertEquals(expected, updated);
  }
Example #14
0
 protected void checkModuleDescriptorRevision(
     ModuleDescriptor systemMd, ModuleRevisionId systemMrid) {
   if (!getSettings().getVersionMatcher().accept(systemMrid, systemMd)) {
     throw new UnresolvedDependencyException(
         "\t"
             + getName()
             + ": unacceptable revision => was="
             + systemMd.getResolvedModuleRevisionId().getRevision()
             + " required="
             + systemMrid.getRevision());
   }
 }
Example #15
0
  private String findUniqueSnapshotVersion(ModuleRevisionId moduleRevisionId) {
    Artifact pomArtifact = DefaultArtifact.newPomArtifact(moduleRevisionId, new Date());
    String metadataLocation =
        toResourcePattern(getWholePattern()).toModuleVersionPath(pomArtifact)
            + "/maven-metadata.xml";
    MavenMetadata mavenMetadata = parseMavenMetadata(metadataLocation);

    if (mavenMetadata.timestamp != null) {
      // we have found a timestamp, so this is a snapshot unique version
      String rev = moduleRevisionId.getRevision();
      rev = rev.substring(0, rev.length() - "SNAPSHOT".length());
      rev = rev + mavenMetadata.timestamp + "-" + mavenMetadata.buildNumber;
      return rev;
    }
    return null;
  }
Example #16
0
  public ResolvedModuleRevision parse(
      final ResolvedResource mdRef, DependencyDescriptor dd, ResolveData data)
      throws ParseException {

    DependencyDescriptor nsDd = dd;
    dd = toSystem(nsDd);

    ModuleRevisionId mrid = dd.getDependencyRevisionId();
    ModuleDescriptorParser parser =
        ModuleDescriptorParserRegistry.getInstance().getParser(mdRef.getResource());
    if (parser == null) {
      Message.warn("no module descriptor parser available for " + mdRef.getResource());
      return null;
    }
    Message.verbose("\t" + getName() + ": found md file for " + mrid);
    Message.verbose("\t\t=> " + mdRef);
    Message.debug("\tparser = " + parser);

    ModuleRevisionId resolvedMrid = mrid;

    // first check if this dependency has not yet been resolved
    if (getSettings().getVersionMatcher().isDynamic(mrid)) {
      resolvedMrid = ModuleRevisionId.newInstance(mrid, mdRef.getRevision());
      IvyNode node = data.getNode(resolvedMrid);
      if (node != null && node.getModuleRevision() != null) {
        // this revision has already be resolved : return it
        if (node.getDescriptor() != null && node.getDescriptor().isDefault()) {
          Message.verbose(
              "\t"
                  + getName()
                  + ": found already resolved revision: "
                  + resolvedMrid
                  + ": but it's a default one, maybe we can find a better one");
        } else {
          Message.verbose("\t" + getName() + ": revision already resolved: " + resolvedMrid);
          node.getModuleRevision().getReport().setSearched(true);
          return node.getModuleRevision();
        }
      }
    }

    Artifact moduleArtifact = parser.getMetadataArtifact(resolvedMrid, mdRef.getResource());
    return getRepositoryCacheManager()
        .cacheModuleDescriptor(this, mdRef, dd, moduleArtifact, downloader, getCacheOptions(data));
  }
Example #17
0
  public void testTarResourceInclusion() throws Exception {
    Locale oldLocale = Locale.getDefault();

    try {
      // set the locale to UK as workaround for SUN bug 6240963
      Locale.setDefault(Locale.UK);

      // Create and configure resolver
      PackagerResolver resolver = new PackagerResolver();
      resolver.setSettings(settings);
      String repoRoot =
          new File("test/repositories/IVY-1179/repo").toURI().toURL().toExternalForm();
      resolver.addIvyPattern(repoRoot + "[organisation]/[module]/[revision]/ivy.xml");
      resolver.setPackagerPattern(repoRoot + "[organisation]/[module]/[revision]/packager.xml");
      resolver.setBuildRoot(builddir);
      resolver.setResourceCache(cachedir);
      resolver.setPreserveBuildDirectories(true);
      resolver.setVerbose(true);

      resolver.setProperty(
          "packager.website.url",
          new File("test/repositories/IVY-1179/website").toURI().toURL().toExternalForm());

      resolver.setName("packager");

      // Get module descriptor
      ModuleRevisionId mrid = ModuleRevisionId.newInstance("org", "B", "1.0");
      ResolvedModuleRevision rmr =
          resolver.getDependency(new DefaultDependencyDescriptor(mrid, false), data);

      // Download artifact
      Artifact artifact = new DefaultArtifact(mrid, rmr.getPublicationDate(), "B", "jar", "jar");
      resolver.download(new Artifact[] {artifact}, downloadOptions());

      // assert that the file B.jar is extracted from the archive
      File jar = new File(builddir, "org/B/1.0/artifacts/jars/B.jar");
      assertTrue(jar.exists());

      // assert that the file README is not extracted from the archive
      File readme = new File(builddir, "org/B/1.0/extract/B-1.0/README");
      assertFalse(readme.exists());
    } finally {
      Locale.setDefault(oldLocale);
    }
  }
Example #18
0
  private void cacheModuleDescriptor(
      ModuleDescriptor systemMd,
      ModuleRevisionId systemMrid,
      ResolvedResource ivyRef,
      ResolvedModuleRevision rmr) {
    RepositoryCacheManager cacheManager = getRepositoryCacheManager();

    final ModuleDescriptorParser parser = systemMd.getParser();

    // the metadata artifact which was used to cache the original metadata file
    Artifact requestedMetadataArtifact =
        ivyRef == null
            ? systemMd.getMetadataArtifact()
            : parser.getMetadataArtifact(
                ModuleRevisionId.newInstance(systemMrid, ivyRef.getRevision()),
                ivyRef.getResource());

    cacheManager.originalToCachedModuleDescriptor(
        this,
        ivyRef,
        requestedMetadataArtifact,
        rmr,
        new ModuleDescriptorWriter() {
          public void write(
              ResolvedResource originalMdResource, ModuleDescriptor md, File src, File dest)
              throws IOException, ParseException {
            if (originalMdResource == null) {
              // a basic ivy file is written containing default data
              XmlModuleDescriptorWriter.write(md, dest);
            } else {
              // copy and update ivy file from source to cache
              parser.toIvyFile(
                  new FileInputStream(src), originalMdResource.getResource(), dest, md);
              long repLastModified = originalMdResource.getLastModified();
              if (repLastModified > 0) {
                dest.setLastModified(repLastModified);
              }
            }
          }
        });
  }
 private Artifact createTestArtifact(String name) {
   return new DefaultArtifact(
       ModuleRevisionId.newInstance("org", name, "1.0"), null, name, "jar", "jar");
 }
Example #20
0
  public ResolvedModuleRevision getDependency(DependencyDescriptor dd, ResolveData data)
      throws ParseException {
    IvyContext context = IvyContext.pushNewCopyContext();
    try {
      ResolvedModuleRevision mr = data.getCurrentResolvedModuleRevision();
      if (mr != null) {
        if (shouldReturnResolvedModule(dd, mr)) {
          return mr;
        }
      }

      if (isForce()) {
        dd =
            dd.clone(
                ModuleRevisionId.newInstance(dd.getDependencyRevisionId(), "latest.integration"));
      }
      DependencyDescriptor systemDd = dd;
      DependencyDescriptor nsDd = fromSystem(dd);
      context.setDependencyDescriptor(systemDd);
      context.setResolveData(data);

      clearIvyAttempts();
      clearArtifactAttempts();
      ModuleRevisionId systemMrid = systemDd.getDependencyRevisionId();
      ModuleRevisionId nsMrid = nsDd.getDependencyRevisionId();

      checkRevision(systemMrid);

      boolean isDynamic = getAndCheckIsDynamic(systemMrid);

      // we first search for the dependency in cache
      ResolvedModuleRevision rmr = null;
      rmr = findModuleInCache(systemDd, data);
      if (rmr != null) {
        if (rmr.getDescriptor().isDefault() && rmr.getResolver() != this) {
          Message.verbose(
              "\t"
                  + getName()
                  + ": found revision in cache: "
                  + systemMrid
                  + " (resolved by "
                  + rmr.getResolver().getName()
                  + "): but it's a default one, maybe we can find a better one");
        } else if (isForce() && rmr.getResolver() != this) {
          Message.verbose(
              "\t"
                  + getName()
                  + ": found revision in cache: "
                  + systemMrid
                  + " (resolved by "
                  + rmr.getResolver().getName()
                  + "): but we are in force mode, let's try to find one ourself");
        } else {
          Message.verbose("\t" + getName() + ": revision in cache: " + systemMrid);
          return checkLatest(systemDd, checkForcedResolvedModuleRevision(rmr), data);
        }
      }
      if (data.getOptions().isUseCacheOnly()) {
        throw new UnresolvedDependencyException(
            "\t" + getName() + " (useCacheOnly) : no ivy file found for " + systemMrid, false);
      }

      checkInterrupted();

      ResolvedResource ivyRef = findIvyFileRef(nsDd, data);
      checkInterrupted();

      // get module descriptor
      ModuleDescriptor nsMd;
      ModuleDescriptor systemMd = null;
      if (ivyRef == null) {
        if (!isAllownomd()) {
          throw new UnresolvedDependencyException(
              "\t" + getName() + ": no ivy file found for " + systemMrid, false);
        }
        nsMd = DefaultModuleDescriptor.newDefaultInstance(nsMrid, nsDd.getAllDependencyArtifacts());
        ResolvedResource artifactRef = findFirstArtifactRef(nsMd, nsDd, data);
        checkInterrupted();
        if (artifactRef == null) {
          throw new UnresolvedDependencyException(
              "\t" + getName() + ": no ivy file nor artifact found for " + systemMrid, false);
        } else {
          long lastModified = artifactRef.getLastModified();
          if (lastModified != 0 && nsMd instanceof DefaultModuleDescriptor) {
            ((DefaultModuleDescriptor) nsMd).setLastModified(lastModified);
          }
          Message.verbose(
              "\t" + getName() + ": no ivy file found for " + systemMrid + ": using default data");
          if (isDynamic) {
            nsMd.setResolvedModuleRevisionId(
                ModuleRevisionId.newInstance(nsMrid, artifactRef.getRevision()));
          }
          systemMd = toSystem(nsMd);
          MetadataArtifactDownloadReport madr =
              new MetadataArtifactDownloadReport(systemMd.getMetadataArtifact());
          madr.setDownloadStatus(DownloadStatus.NO);
          madr.setSearched(true);
          rmr = new ResolvedModuleRevision(this, this, systemMd, madr, isForce());
          getRepositoryCacheManager()
              .cacheModuleDescriptor(
                  this,
                  artifactRef,
                  toSystem(dd),
                  systemMd.getAllArtifacts()[0],
                  null,
                  getCacheOptions(data));
        }
      } else {
        if (ivyRef instanceof MDResolvedResource) {
          rmr = ((MDResolvedResource) ivyRef).getResolvedModuleRevision();
        }
        if (rmr == null) {
          rmr = parse(ivyRef, systemDd, data);
          if (rmr == null) {
            throw new UnresolvedDependencyException();
          }
        }
        if (!rmr.getReport().isDownloaded() && rmr.getReport().getLocalFile() != null) {
          return checkLatest(systemDd, checkForcedResolvedModuleRevision(rmr), data);
        } else {
          nsMd = rmr.getDescriptor();

          // check descriptor data is in sync with resource revision and names
          systemMd = toSystem(nsMd);
          if (isCheckconsistency()) {
            checkDescriptorConsistency(systemMrid, systemMd, ivyRef);
            checkDescriptorConsistency(nsMrid, nsMd, ivyRef);
          } else {
            if (systemMd instanceof DefaultModuleDescriptor) {
              DefaultModuleDescriptor defaultMd = (DefaultModuleDescriptor) systemMd;
              ModuleRevisionId revision = getRevision(ivyRef, systemMrid, systemMd);
              defaultMd.setModuleRevisionId(revision);
              defaultMd.setResolvedModuleRevisionId(revision);
            } else {
              Message.warn(
                  "consistency disabled with instance of non DefaultModuleDescriptor..."
                      + " module info can't be updated, so consistency check will be done");
              checkDescriptorConsistency(nsMrid, nsMd, ivyRef);
              checkDescriptorConsistency(systemMrid, systemMd, ivyRef);
            }
          }
          rmr =
              new ResolvedModuleRevision(
                  this, this, systemMd, toSystem(rmr.getReport()), isForce());
        }
      }

      resolveAndCheckRevision(systemMd, systemMrid, ivyRef, isDynamic);
      resolveAndCheckPublicationDate(systemDd, systemMd, systemMrid, data);
      checkNotConvertedExclusionRule(systemMd, ivyRef, data);

      if (ivyRef == null || ivyRef.getResource() != null) {
        cacheModuleDescriptor(systemMd, systemMrid, ivyRef, rmr);
      }

      return checkLatest(systemDd, checkForcedResolvedModuleRevision(rmr), data);
    } catch (UnresolvedDependencyException ex) {
      if (ex.getMessage().length() > 0) {
        if (ex.isError()) {
          Message.error(ex.getMessage());
        } else {
          Message.verbose(ex.getMessage());
        }
      }
      return data.getCurrentResolvedModuleRevision();
    } finally {
      IvyContext.popContext();
    }
  }
  public void testVariableReplacement() throws Exception {
    /*
     * For updated file to be equals to updated.xml, we have to fix the line separator to the
     * one used in updated.xml, in order for this test to works in all platforms (default line
     * separator used in updater being platform dependent
     */
    XmlModuleDescriptorUpdater.LINE_SEPARATOR = "\n";
    File dest = new File("build/updated-test2.xml");
    dest.deleteOnExit();
    Map resolvedRevisions = new HashMap();
    resolvedRevisions.put(
        ModuleRevisionId.newInstance("yourorg", "yourmodule2", "branch1", "2+"), "2.5");
    resolvedRevisions.put(
        ModuleRevisionId.newInstance("yourorg", "yourmodule6", "trunk", "latest.integration"),
        "6.3");

    Map resolvedBranches = new HashMap();
    resolvedBranches.put(ModuleRevisionId.newInstance("yourorg", "yourmodule3", "3.1"), "branch1");
    resolvedBranches.put(
        ModuleRevisionId.newInstance("yourorg", "yourmodule2", "branch1", "2+"), null);

    GregorianCalendar cal = new GregorianCalendar();
    cal.set(2005, 2, 22, 14, 32, 54);

    Ivy ivy = Ivy.newInstance();
    ivy.setVariable("myorg", "myorg");
    ivy.setVariable("mymodule", "mymodule");
    ivy.setVariable("myrev", "myrev");
    ivy.setVariable("mystatus", "integration");
    ivy.setVariable("mypubdate", "20050322143254");
    ivy.setVariable("mylicense", "MyLicense");
    ivy.setVariable("mylicenseurl", "http://www.my.org/mymodule/mylicense.html");
    ivy.setVariable("myorgurl", "http://www.myorg.org/");
    ivy.setVariable("ivyrep", "ivyrep");
    ivy.setVariable("ivyrepurl", "http://www.jayasoft.fr/org/ivyrep/");
    ivy.setVariable("ivyreppattern", "[organisation]/[module]/ivy-[revision].xml");
    ivy.setVariable("ivys", "true");
    ivy.setVariable("artifacts", "false");
    ivy.setVariable("homepage", "http://www.my.org/mymodule/");
    ivy.setVariable("includefile", "imported-configurations-with-mapping.xml");
    ivy.setVariable("mydesc", "desc 1");
    ivy.setVariable("visibility", "public");
    ivy.setVariable("myvar", "myconf1");
    ivy.setVariable("deprecated", "20050115");
    ivy.setVariable("myartifact1", "myartifact1");
    ivy.setVariable("mytype", "jar");
    ivy.setVariable("mymodule2", "mymodule2");
    ivy.setVariable("mymodule2rev", "2.0");
    ivy.setVariable("changing", "true");
    ivy.setVariable("transitive", "false");
    ivy.setVariable("targetconf", "yourconf1");
    ivy.setVariable("art9-1", "yourartifact9-1");
    ivy.setVariable("conf3", "myconf3");
    ivy.setVariable("includename", "your.*");
    ivy.setVariable("includeext", "xml");
    ivy.setVariable("excludename", "toexclude");
    ivy.setVariable("excludemodule", "*servlet*");
    ivy.setVariable("excludematcher", "glob");
    ivy.setVariable("excludeorg", "acme");
    ivy.setVariable("excludeartifact", "test");
    ivy.setVariable("excludetype", "source");
    ivy.setVariable("yourorg", "yourorg");
    ivy.setVariable("yourmodule", ".*");
    ivy.setVariable("all", "all");
    ivy.setVariable("regexp", "regexp");
    ivy.setVariable("theirrev", "1.0, 1.1");

    XmlModuleDescriptorUpdater.update(
        XmlModuleUpdaterTest.class.getResource("test-update-withvar.xml"),
        dest,
        getUpdateOptions(ivy.getSettings(), resolvedRevisions, "release", "mynewrev", cal.getTime())
            .setResolvedBranches(resolvedBranches));

    assertTrue(dest.exists());
    String expected =
        FileUtil.readEntirely(
            new BufferedReader(
                new InputStreamReader(
                    XmlModuleUpdaterTest.class.getResourceAsStream("updated.xml"))));
    String updated = FileUtil.readEntirely(new BufferedReader(new FileReader(dest)));
    assertEquals(expected, updated);
  }
 public ModuleIdentifier getId() {
   return new DefaultResolvedModuleId(
       moduleRevisionId.getOrganisation(),
       moduleRevisionId.getName(),
       moduleRevisionId.getRevision());
 }
/** @author Hans Dockter */
public abstract class AbstractMavenResolverTest {
  public static final String TEST_NAME = "name";
  private static final Artifact TEST_IVY_ARTIFACT =
      DefaultArtifact.newIvyArtifact(ModuleRevisionId.newInstance("org", TEST_NAME, "1.0"), null);
  private static final File TEST_IVY_FILE = new File("somepom.xml");
  private static final File TEST_JAR_FILE = new File("somejar.jar");
  private static final Artifact TEST_ARTIFACT =
      new DefaultArtifact(
          ModuleRevisionId.newInstance("org", TEST_NAME, "1.0"), null, TEST_NAME, "jar", "jar");
  protected ArtifactPomContainer artifactPomContainerMock;
  protected PomFilterContainer pomFilterContainerMock;
  protected LoggingManagerInternal loggingManagerMock;

  protected JUnit4GroovyMockery context =
      new JUnit4GroovyMockery() {
        {
          setImposteriser(ClassImposteriser.INSTANCE);
        }
      };
  protected MavenPom pomMock;

  protected Settings mavenSettingsMock;

  protected abstract AbstractMavenResolver getMavenResolver();

  protected abstract InstallDeployTaskSupport getInstallDeployTask();

  protected abstract PomFilterContainer createPomFilterContainerMock();

  @Before
  public void setUp() {
    pomFilterContainerMock = createPomFilterContainerMock();
    artifactPomContainerMock = context.mock(ArtifactPomContainer.class);
    pomMock = context.mock(MavenPom.class);
    mavenSettingsMock = context.mock(Settings.class);
    loggingManagerMock = context.mock(LoggingManagerInternal.class);
  }

  @Test
  public void deployOrInstall() throws IOException, PlexusContainerException {
    getMavenResolver().mavenSettingsSupplier = context.mock(MavenSettingsSupplier.class);

    PublishArtifact classifierArtifact = artifact(new File("classifier.jar"));
    final DefaultMavenDeployment deployment1 =
        new DefaultMavenDeployment(
            artifact(new File("pom1.pom")),
            artifact(new File("artifact1.jar")),
            Collections.<PublishArtifact>emptySet());
    final DefaultMavenDeployment deployment2 =
        new DefaultMavenDeployment(
            artifact(new File("pom2.pom")),
            artifact(new File("artifact2.jar")),
            WrapUtil.toSet(classifierArtifact));
    final Set<DefaultMavenDeployment> testDefaultMavenDeployments =
        WrapUtil.toSet(deployment1, deployment2);
    final AttachedArtifact attachedArtifact = new AttachedArtifact();
    @SuppressWarnings("unchecked")
    final Action<MavenDeployment> action = context.mock(Action.class);

    context.checking(
        new Expectations() {
          {
            allowing((CustomInstallDeployTaskSupport) getInstallDeployTask())
                .clearAttachedArtifactsList();
            allowing((CustomInstallDeployTaskSupport) getInstallDeployTask()).getSettings();
            will(returnValue(mavenSettingsMock));
            allowing((CustomInstallDeployTaskSupport) getInstallDeployTask()).getProject();
            will(returnValue(AntUtil.createProject()));
            allowing((CustomInstallDeployTaskSupport) getInstallDeployTask()).createAttach();
            will(returnValue(attachedArtifact));
            one(artifactPomContainerMock).addArtifact(TEST_ARTIFACT, TEST_JAR_FILE);
            allowing(artifactPomContainerMock).createDeployableFilesInfos();
            will(returnValue(testDefaultMavenDeployments));
            one(action).execute(deployment1);
            one(action).execute(deployment2);
          }
        });

    getMavenResolver().beforeDeployment(action);
    getMavenResolver().publish(TEST_IVY_ARTIFACT, TEST_IVY_FILE, true);
    getMavenResolver().publish(TEST_ARTIFACT, TEST_JAR_FILE, true);
    checkTransaction(testDefaultMavenDeployments, attachedArtifact, classifierArtifact);
    assertSame(mavenSettingsMock, getMavenResolver().getSettings());
  }

  private PublishArtifact artifact(File file) {
    return new DefaultPublishArtifact("name", "ext", "type", null, null, file);
  }

  protected void checkTransaction(
      final Set<DefaultMavenDeployment> defaultMavenDeployments,
      final AttachedArtifact attachedArtifact,
      PublishArtifact classifierArtifact)
      throws IOException, PlexusContainerException {
    context.checking(
        new Expectations() {
          {
            one(getInstallDeployTask()).setProject(with(any(Project.class)));
            for (DefaultMavenDeployment defaultMavenDeployment : defaultMavenDeployments) {
              one(getInstallDeployTask())
                  .setFile(defaultMavenDeployment.getMainArtifact().getFile());
              one(getInstallDeployTask())
                  .addPom(
                      with(
                          pomMatcher(
                              defaultMavenDeployment.getPomArtifact().getFile(),
                              getInstallDeployTask().getProject())));
              one(loggingManagerMock).captureStandardOutput(LogLevel.INFO);
              will(returnValue(loggingManagerMock));
              one(loggingManagerMock).start();
              one(getInstallDeployTask()).execute();
              one(loggingManagerMock).stop();
              will(returnValue(loggingManagerMock));
            }
            one(getMavenResolver().mavenSettingsSupplier).supply(getInstallDeployTask());
            one(getMavenResolver().mavenSettingsSupplier).done();
          }
        });
    getMavenResolver().commitPublishTransaction();
    assertThat(attachedArtifact.getFile(), equalTo(classifierArtifact.getFile()));
    assertThat(attachedArtifact.getType(), equalTo(classifierArtifact.getType()));
    assertThat(attachedArtifact.getClassifier(), equalTo(classifierArtifact.getClassifier()));
  }

  private static Matcher<Pom> pomMatcher(
      final File expectedPomFile, final Project expectedAntProject) {
    return new BaseMatcher<Pom>() {
      public void describeTo(Description description) {
        description.appendText("matching pom");
      }

      public boolean matches(Object actual) {
        Pom actualPom = (Pom) actual;
        return actualPom.getFile().equals(expectedPomFile)
            && actualPom.getProject().equals(expectedAntProject);
      }
    };
  }

  @Test
  public void setFilter() {
    final PublishFilter publishFilterMock = context.mock(PublishFilter.class);
    context.checking(
        new Expectations() {
          {
            one(pomFilterContainerMock).setFilter(publishFilterMock);
          }
        });
    getMavenResolver().setFilter(publishFilterMock);
  }

  @Test
  public void getFilter() {
    final PublishFilter publishFilterMock = context.mock(PublishFilter.class);
    context.checking(
        new Expectations() {
          {
            allowing(pomFilterContainerMock).getFilter();
            will(returnValue(publishFilterMock));
          }
        });
    assertSame(publishFilterMock, getMavenResolver().getFilter());
  }

  @Test
  public void setPom() {
    context.checking(
        new Expectations() {
          {
            one(pomFilterContainerMock).setPom(pomMock);
          }
        });
    getMavenResolver().setPom(pomMock);
  }

  @Test
  public void getPom() {
    context.checking(
        new Expectations() {
          {
            allowing(pomFilterContainerMock).getPom();
            will(returnValue(pomMock));
          }
        });
    assertSame(pomMock, getMavenResolver().getPom());
  }

  @Test
  public void addFilter() {
    final String testName = "somename";
    final PublishFilter publishFilterMock = context.mock(PublishFilter.class);
    context.checking(
        new Expectations() {
          {
            one(pomFilterContainerMock).addFilter(testName, publishFilterMock);
          }
        });
    getMavenResolver().addFilter(testName, publishFilterMock);
  }

  @Test
  public void filter() {
    final String testName = "somename";
    final PublishFilter publishFilterMock = context.mock(PublishFilter.class);
    context.checking(
        new Expectations() {
          {
            one(pomFilterContainerMock).filter(testName);
            will(returnValue(publishFilterMock));
          }
        });
    assertSame(publishFilterMock, getMavenResolver().filter(testName));
  }

  @Test
  public void pom() {
    final String testName = "somename";
    context.checking(
        new Expectations() {
          {
            one(pomFilterContainerMock).pom(testName);
            will(returnValue(pomMock));
          }
        });
    assertSame(pomMock, getMavenResolver().pom(testName));
  }
}
 private ModuleDescriptor createAnonymousModuleDescriptor() {
   return DefaultModuleDescriptor.newDefaultInstance(
       ModuleRevisionId.newInstance("org", "name", "1.0", new HashMap()));
 }
Example #25
0
  /**
   * When the resolver has many choices, this function helps choosing one
   *
   * @param rress the list of resolved resource which the resolver found to fit the requirement
   * @param rmdparser the parser of module descriptor
   * @param mrid the module being resolved
   * @param date the current date
   * @return the selected resource
   */
  public ResolvedResource findResource(
      ResolvedResource[] rress, ResourceMDParser rmdparser, ModuleRevisionId mrid, Date date) {
    String name = getName();
    VersionMatcher versionMatcher = getSettings().getVersionMatcher();

    ResolvedResource found = null;
    List sorted = getLatestStrategy().sort(rress);
    List rejected = new ArrayList();
    List foundBlacklisted = new ArrayList();
    IvyContext context = IvyContext.getContext();

    for (ListIterator iter = sorted.listIterator(sorted.size()); iter.hasPrevious(); ) {
      ResolvedResource rres = (ResolvedResource) iter.previous();
      // we start by filtering based on information already available,
      // even though we don't even know if the resource actually exist.
      // But checking for existence is most of the time more costly than checking
      // name, blacklisting and first level version matching
      if (filterNames(new ArrayList(Collections.singleton(rres.getRevision()))).isEmpty()) {
        Message.debug("\t" + name + ": filtered by name: " + rres);
        continue;
      }
      ModuleRevisionId foundMrid = ModuleRevisionId.newInstance(mrid, rres.getRevision());

      ResolveData data = context.getResolveData();
      if (data != null
          && data.getReport() != null
          && data.isBlacklisted(data.getReport().getConfiguration(), foundMrid)) {
        Message.debug("\t" + name + ": blacklisted: " + rres);
        rejected.add(rres.getRevision() + " (blacklisted)");
        foundBlacklisted.add(foundMrid);
        continue;
      }

      if (!versionMatcher.accept(mrid, foundMrid)) {
        Message.debug("\t" + name + ": rejected by version matcher: " + rres);
        rejected.add(rres.getRevision());
        continue;
      }
      if (rres.getResource() != null && !rres.getResource().exists()) {
        Message.debug("\t" + name + ": unreachable: " + rres + "; res=" + rres.getResource());
        rejected.add(rres.getRevision() + " (unreachable)");
        continue;
      }
      if ((date != null && rres.getLastModified() > date.getTime())) {
        Message.verbose("\t" + name + ": too young: " + rres);
        rejected.add(rres.getRevision() + " (" + rres.getLastModified() + ")");
        continue;
      }
      if (versionMatcher.needModuleDescriptor(mrid, foundMrid)) {
        ResolvedResource r = rmdparser.parse(rres.getResource(), rres.getRevision());
        if (r == null) {
          Message.debug("\t" + name + ": impossible to get module descriptor resource: " + rres);
          rejected.add(rres.getRevision() + " (no or bad MD)");
          continue;
        }
        ModuleDescriptor md = ((MDResolvedResource) r).getResolvedModuleRevision().getDescriptor();
        if (md.isDefault()) {
          Message.debug(
              "\t"
                  + name
                  + ": default md rejected by version matcher"
                  + "requiring module descriptor: "
                  + rres);
          rejected.add(rres.getRevision() + " (MD)");
          continue;
        } else if (!versionMatcher.accept(mrid, md)) {
          Message.debug("\t" + name + ": md rejected by version matcher: " + rres);
          rejected.add(rres.getRevision() + " (MD)");
          continue;
        } else {
          found = r;
        }
      } else {
        found = rres;
      }

      if (found != null) {
        break;
      }
    }
    if (found == null && !rejected.isEmpty()) {
      logAttempt(rejected.toString());
    }
    if (found == null && !foundBlacklisted.isEmpty()) {
      // all acceptable versions have been blacklisted, this means that an unsolvable conflict
      // has been found
      DependencyDescriptor dd = context.getDependencyDescriptor();
      IvyNode parentNode = context.getResolveData().getNode(dd.getParentRevisionId());
      ConflictManager cm = parentNode.getConflictManager(mrid.getModuleId());
      cm.handleAllBlacklistedRevisions(dd, foundBlacklisted);
    }

    return found;
  }
Example #26
0
 // private boolean isResolved(ResolveData data, ModuleRevisionId mrid) {
 // IvyNode node = getSystemNode(data, mrid);
 // return node != null && node.getModuleRevision() != null;
 // }
 //
 private void checkDescriptorConsistency(
     ModuleRevisionId mrid, ModuleDescriptor md, ResolvedResource ivyRef) throws ParseException {
   boolean ok = true;
   StringBuffer errors = new StringBuffer();
   if (!mrid.getOrganisation().equals(md.getModuleRevisionId().getOrganisation())) {
     Message.error(
         "\t"
             + getName()
             + ": bad organisation found in "
             + ivyRef.getResource()
             + ": expected='"
             + mrid.getOrganisation()
             + "' found='"
             + md.getModuleRevisionId().getOrganisation()
             + "'");
     errors.append(
         "bad organisation: expected='"
             + mrid.getOrganisation()
             + "' found='"
             + md.getModuleRevisionId().getOrganisation()
             + "'; ");
     ok = false;
   }
   if (!mrid.getName().equals(md.getModuleRevisionId().getName())) {
     Message.error(
         "\t"
             + getName()
             + ": bad module name found in "
             + ivyRef.getResource()
             + ": expected='"
             + mrid.getName()
             + " found='"
             + md.getModuleRevisionId().getName()
             + "'");
     errors.append(
         "bad module name: expected='"
             + mrid.getName()
             + "' found='"
             + md.getModuleRevisionId().getName()
             + "'; ");
     ok = false;
   }
   if (mrid.getBranch() != null
       && !mrid.getBranch().equals(md.getModuleRevisionId().getBranch())) {
     Message.error(
         "\t"
             + getName()
             + ": bad branch name found in "
             + ivyRef.getResource()
             + ": expected='"
             + mrid.getBranch()
             + " found='"
             + md.getModuleRevisionId().getBranch()
             + "'");
     errors.append(
         "bad branch name: expected='"
             + mrid.getBranch()
             + "' found='"
             + md.getModuleRevisionId().getBranch()
             + "'; ");
     ok = false;
   }
   if (ivyRef.getRevision() != null && !ivyRef.getRevision().startsWith("working@")) {
     ModuleRevisionId expectedMrid = ModuleRevisionId.newInstance(mrid, ivyRef.getRevision());
     if (!getSettings().getVersionMatcher().accept(expectedMrid, md)) {
       Message.error(
           "\t"
               + getName()
               + ": bad revision found in "
               + ivyRef.getResource()
               + ": expected='"
               + ivyRef.getRevision()
               + " found='"
               + md.getModuleRevisionId().getRevision()
               + "'");
       errors.append(
           "bad revision: expected='"
               + ivyRef.getRevision()
               + "' found='"
               + md.getModuleRevisionId().getRevision()
               + "'; ");
       ok = false;
     }
   }
   if (!getSettings().getStatusManager().isStatus(md.getStatus())) {
     Message.error(
         "\t"
             + getName()
             + ": bad status found in "
             + ivyRef.getResource()
             + ": '"
             + md.getStatus()
             + "'");
     errors.append("bad status: '" + md.getStatus() + "'; ");
     ok = false;
   }
   for (Iterator it = mrid.getExtraAttributes().entrySet().iterator(); it.hasNext(); ) {
     Entry extra = (Entry) it.next();
     if (extra.getValue() != null
         && !extra.getValue().equals(md.getExtraAttribute((String) extra.getKey()))) {
       String errorMsg =
           "bad "
               + extra.getKey()
               + " found in "
               + ivyRef.getResource()
               + ": expected='"
               + extra.getValue()
               + "' found='"
               + md.getExtraAttribute((String) extra.getKey())
               + "'";
       Message.error("\t" + getName() + ": " + errorMsg);
       errors.append(errorMsg + ";");
       ok = false;
     }
   }
   if (!ok) {
     throw new ParseException(
         "inconsistent module descriptor file found in '" + ivyRef.getResource() + "': " + errors,
         0);
   }
 }
Example #27
0
  public void testFile() throws Exception {
    Locale oldLocale = Locale.getDefault();

    try {
      // set the locale to UK as workaround for SUN bug 6240963
      Locale.setDefault(Locale.UK);

      // Create and configure resolver
      PackagerResolver resolver = new PackagerResolver();
      resolver.setSettings(settings);
      String repoRoot =
          new File("test/repositories/packager/repo").toURI().toURL().toExternalForm();
      resolver.addIvyPattern(repoRoot + "[organisation]/[module]/[revision]/ivy.xml");
      resolver.setPackagerPattern(repoRoot + "[organisation]/[module]/[revision]/packager.xml");
      resolver.setBuildRoot(builddir);
      resolver.setResourceCache(cachedir);
      resolver.setPreserveBuildDirectories(true);
      resolver.setVerbose(true);

      resolver.setProperty(
          "packager.website.url",
          new File("test/repositories/packager/website").toURI().toURL().toExternalForm());

      resolver.setName("packager");
      assertEquals("packager", resolver.getName());

      // Get module descriptor
      ModuleRevisionId mrid = ModuleRevisionId.newInstance("org", "mod", "1.0");
      ResolvedModuleRevision rmr =
          resolver.getDependency(new DefaultDependencyDescriptor(mrid, false), data);
      assertNotNull(rmr);

      assertEquals(mrid, rmr.getId());
      Date pubdate = new GregorianCalendar(2004, 10, 1, 11, 0, 0).getTime();
      assertEquals(pubdate, rmr.getPublicationDate());

      // Download artifact
      Artifact artifact = new DefaultArtifact(mrid, pubdate, "mod", "jar", "jar");
      DownloadReport report = resolver.download(new Artifact[] {artifact}, downloadOptions());
      assertNotNull(report);

      assertEquals(1, report.getArtifactsReports().length);

      ArtifactDownloadReport ar = report.getArtifactReport(artifact);
      System.out.println("downloaddetails: " + ar.getDownloadDetails());
      assertNotNull(ar);

      assertEquals(artifact, ar.getArtifact());
      assertEquals(DownloadStatus.SUCCESSFUL, ar.getDownloadStatus());

      // Verify resource cache now contains the distribution archive
      assertTrue(new File(cachedir, "mod-1.0.tar.gz").exists());

      // Download again, should use Ivy cache this time
      report = resolver.download(new Artifact[] {artifact}, downloadOptions());
      assertNotNull(report);

      assertEquals(1, report.getArtifactsReports().length);

      ar = report.getArtifactReport(artifact);
      assertNotNull(ar);

      assertEquals(artifact, ar.getArtifact());
      assertEquals(DownloadStatus.NO, ar.getDownloadStatus());

      // Now download the maven2 artifact
      artifact = DefaultArtifact.cloneWithAnotherName(artifact, "foobar-janfu");
      report = resolver.download(new Artifact[] {artifact}, downloadOptions());
      assertNotNull(report);

      assertEquals(1, report.getArtifactsReports().length);

      ar = report.getArtifactReport(artifact);
      assertNotNull(ar);

      assertEquals(artifact, ar.getArtifact());
      assertEquals(DownloadStatus.SUCCESSFUL, ar.getDownloadStatus());
    } finally {
      Locale.setDefault(oldLocale);
    }
  }
 ModuleResolutionCacheEntry(ModuleRevisionId revisionId, TimeProvider timeProvider) {
   this.encodedRevisionId = revisionId == null ? null : revisionId.encodeToString();
   this.createTimestamp = timeProvider.getCurrentTime();
 }