public static DependencyId newInstance(Artifact artifact) { return new DependencyId( artifact.getGroupId(), artifact.getArtifactId(), artifact.getClassifier(), artifact.getExtension()); }
@Override public DependencyMetadata resolveDependencyMetadata( Dependency query, final List<DependencyRepository> repositories) { try { if (Strings.isNullOrEmpty(query.getVersion())) { query = DependencyBuilder.create(query).setVersion("[,)"); } RepositorySystem system = container.lookup(RepositorySystem.class); MavenRepositorySystemSession session = setupRepoSession(system); DefaultArtifact artifact = new DefaultArtifact(query.toCoordinates()); ArtifactDescriptorRequest ar = new ArtifactDescriptorRequest(artifact, convertToMavenRepos(repositories), null); ArtifactDescriptorResult results = system.readArtifactDescriptor(session, ar); Artifact a = results.getArtifact(); Dependency d = DependencyBuilder.create() .setArtifactId(a.getArtifactId()) .setGroupId(a.getGroupId()) .setVersion(a.getVersion()); return new DependencyMetadataImpl(d, results); } catch (Exception e) { throw new ProjectModelException( "Unable to resolve any artifacts for query [" + query + "]", e); } }
@Test public void testLookup() throws ArtifactDescriptorException { StubArtifact art = new StubArtifact("gid:aid:ext:ver"); ArtifactDescriptorRequest request = new ArtifactDescriptorRequest(art, null, ""); ArtifactDescriptorResult description = reader.readArtifactDescriptor(session, request); assertEquals(request, description.getRequest()); assertEquals(art, description.getArtifact()); assertEquals(1, description.getRelocations().size()); Artifact artifact = description.getRelocations().get(0); assertEquals("gid", artifact.getGroupId()); assertEquals("aid", artifact.getArtifactId()); assertEquals("ver", artifact.getVersion()); assertEquals("ext", artifact.getExtension()); assertEquals(1, description.getRepositories().size()); RemoteRepository repo = description.getRepositories().get(0); assertEquals("id", repo.getId()); assertEquals("type", repo.getContentType()); assertEquals("protocol://some/url?for=testing", repo.getUrl()); assertDependencies(description.getDependencies()); assertDependencies(description.getManagedDependencies()); }
public void upload( String groupId, String artifactId, String version, String extension, Generator writer) throws Exception { File file = File.createTempFile( String.format("%s-%s-%s", groupId, artifactId, version), "." + extension); try { FileOutputStream out = new FileOutputStream(file); try { writer.write(out); } finally { out.close(); } Artifact artifact = new DefaultArtifact(groupId, artifactId, extension, version).setFile(file); // Install the artifact locally repositorySystem.install(session, new InstallRequest().addArtifact(artifact)); // Deploy the artifact remotely DeployRequest deployRequest = new DeployRequest().addArtifact(artifact); if (artifact.isSnapshot()) { Preconditions.checkNotNull(snapshotsRepository, "snapshots repository uri is null"); deployRequest.setRepository(snapshotsRepository); } else { Preconditions.checkNotNull(releasesRepository, "releases repository uri is null"); deployRequest.setRepository(releasesRepository); } repositorySystem.deploy(session, deployRequest); } finally { file.delete(); } }
public synchronized String getArtifactVersion(ReleaseId releaseId) { if (!releaseId.isSnapshot()) { return releaseId.getVersion(); } Artifact artifact = getArtifactResolver().resolveArtifact(releaseId); return artifact != null ? artifact.getVersion() : null; }
/** * Converts an Aether artifact to a Maven model dependency. * * @param artifact the Aether artifact to be converted * @return a Maven dependency with the same coordinates */ private Dependency artifactToDependency(Artifact artifact) { final Dependency dependency = new Dependency(); dependency.setGroupId(artifact.getGroupId()); dependency.setArtifactId(artifact.getArtifactId()); dependency.setVersion(artifact.getVersion()); dependency.setType(artifact.getExtension()); return dependency; }
private static String getId(Artifact artifact) { return getId( artifact.getGroupId(), artifact.getArtifactId(), artifact.getExtension(), artifact.getClassifier(), artifact.getBaseVersion()); }
/** * Fetch all files found (JAR, ZIP, directories, etc). * * @return Set of files * @throws DependencyResolutionException If can't resolve */ @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") private Set<File> fetch() throws DependencyResolutionException { final Set<File> files = new LinkedHashSet<File>(0); for (String path : this.elements()) { files.add(new File(path)); } for (Artifact artifact : this.artifacts()) { files.add(artifact.getFile()); } return files; }
@Test public void testImmutability() { String coords = "gid:aid:ext:cls:ver"; HashMap<String, String> map = new HashMap<String, String>(); map.put("someProperty", "someValue"); Artifact a = new DefaultArtifact(coords); assertNotSame(a, a.setFile(new File("file"))); assertNotSame(a, a.setVersion("otherVersion")); assertNotSame(a, a.setProperties(map)); }
/** * Resolves an artifact given its Maven coordinates. * * @param coordinates Maven artifact coordinates * @return resolved artifact file */ public File resolveArtifact(final String coordinates) throws RuntimeException { try { Artifact artifact = artifactResolver.resolveArtifact(request().artifact(coordinates)); if (artifact == null || artifact.getFile() == null || !artifact.getFile().exists()) { throw new RuntimeException(String.format("Artifact %s could not be resolved", coordinates)); } return artifact.getFile(); } catch (ArtifactResolutionException e) { throw new RuntimeException(e.getMessage(), e); } }
private void updateKieModule(DependencyDescriptor oldDependency, Artifact artifact) { ReleaseId newReleaseId = new DependencyDescriptor(artifact).getReleaseId(); ZipKieModule kieModule = createZipKieModule(newReleaseId, artifact.getFile()); if (kieModule != null) { ResultsImpl messages = build(kieModule); if (messages.filterMessages(Message.Level.ERROR).isEmpty()) { ((InternalKieContainer) kieContainer) .updateDependencyToVersion(oldDependency.getArtifactReleaseId(), newReleaseId); oldDependency.setArtifactVersion(artifact.getVersion()); } } }
private void indexAtifacts() { Collection<DependencyDescriptor> deps = getArtifactResolver().getAllDependecies(); for (DependencyDescriptor dep : deps) { if (!dep.isFixedVersion()) { Artifact artifact = getArtifactResolver().resolveArtifact(dep.getReleaseId()); log.debug(artifact + " resolved to " + artifact.getFile()); if (isKJar(artifact.getFile())) { usedDependencies.put(dep.getReleaseId(), new DependencyDescriptor(artifact)); } } } }
private InternalKieModule buildArtifact(Artifact artifact, ArtifactResolver resolver) { DependencyDescriptor dependencyDescriptor = new DependencyDescriptor(artifact); ReleaseId releaseId = dependencyDescriptor.getReleaseId(); if (releaseId.isSnapshot()) { ((ReleaseIdImpl) releaseId).setSnapshotVersion(artifact.getVersion()); } ZipKieModule kieModule = createZipKieModule(releaseId, artifact.getFile()); if (kieModule != null) { addDependencies( kieModule, resolver, resolver.getArtifactDependecies(dependencyDescriptor.toString())); build(kieModule); } return kieModule; }
private void addDependencies( InternalKieModule kieModule, ArtifactResolver resolver, List<DependencyDescriptor> dependencies) { for (DependencyDescriptor dep : dependencies) { Artifact depArtifact = resolver.resolveArtifact(dep.getReleaseId()); if (depArtifact != null && isKJar(depArtifact.getFile())) { ReleaseId depReleaseId = new DependencyDescriptor(depArtifact).getReleaseId(); ZipKieModule zipKieModule = createZipKieModule(depReleaseId, depArtifact.getFile()); if (zipKieModule != null) { kieModule.addKieDependency(zipKieModule); } } } }
/** * Resolve maven URI into maven project. * * <p>Provides only model and artifact. */ public static MavenProject newProject(String mavenURI) throws Exception { final Artifact artifact = newArtifact(mavenURI); final File input = artifact.getFile(); final ModelReader reader = new DefaultModelReader(); final Model model = reader.read(input, null); final MavenProject project = new MavenProject(model); project.setArtifact(RepositoryUtils.toArtifact(artifact)); return project; }
private Set<Artifact> processTransientDependencies(Dependency dependency, boolean sharedLibraries) throws MojoExecutionException { try { final Set<Artifact> artifacts = new LinkedHashSet<Artifact>(); final CollectRequest collectRequest = new CollectRequest(); collectRequest.setRoot(dependency); collectRequest.setRepositories(projectRepos); final DependencyNode node = repoSystem.collectDependencies(repoSession, collectRequest).getRoot(); final DependencyRequest dependencyRequest = new DependencyRequest( node, new AndDependencyFilter( new ScopeDependencyFilter( Arrays.asList("compile", "runtime"), Arrays.asList("test")), // Also exclude any optional dependencies new DependencyFilter() { @Override public boolean accept( DependencyNode dependencyNode, List<DependencyNode> dependencyNodes) { return !dependencyNode.getDependency().isOptional(); } })); repoSystem.resolveDependencies(repoSession, dependencyRequest); PreorderNodeListGenerator nlg = new PreorderNodeListGenerator(); node.accept(nlg); final List<Dependency> dependencies = nlg.getDependencies(false); for (Dependency dep : dependencies) { final org.sonatype.aether.artifact.Artifact depAetherArtifact = dep.getArtifact(); if (isNativeLibrary(sharedLibraries, depAetherArtifact.getExtension())) { final Artifact mavenArtifact = artifactFactory.createDependencyArtifact( depAetherArtifact.getGroupId(), depAetherArtifact.getArtifactId(), VersionRange.createFromVersion(depAetherArtifact.getVersion()), depAetherArtifact.getExtension(), depAetherArtifact.getClassifier(), dep.getScope()); mavenArtifact.setFile(depAetherArtifact.getFile()); artifacts.add(mavenArtifact); } } return artifacts; } catch (Exception e) { throw new MojoExecutionException("Error while processing transient dependencies", e); } }
public boolean isMarkerOlder(Artifact artifact1) throws MojoExecutionException { File marker = getMarkerFile(); if (marker.exists()) { return artifact1.getFile().lastModified() > marker.lastModified(); } else { // if the marker doesn't exist, we want to copy so assume it is // infinately older return true; } }
/** * Artifact exists in collection? * * @param artifact The artifact * @param artifacts Collection of them * @return TRUE if it is already there */ private static boolean contains(final Artifact artifact, final Collection<Artifact> artifacts) { boolean contains = false; for (Artifact exists : artifacts) { if (artifact.getArtifactId().equals(exists.getArtifactId()) && artifact.getGroupId().equals(exists.getGroupId()) && artifact.getClassifier().equals(exists.getClassifier())) { contains = true; break; } } return contains; }
public File findArtifact(Artifact artifact) { MavenJPackageDepmap.debug( "=============JAVADIRREADER-FIND_ARTIFACT: " + artifact.getArtifactId()); StringBuffer path = new StringBuffer(); String artifactId = artifact.getArtifactId(); String groupId = artifact.getGroupId(); String version = artifact.getVersion(); MavenJPackageDepmap.debug("Wanted GROUPID=" + groupId); MavenJPackageDepmap.debug("Wanted ARTIFACTID=" + artifactId); if (!groupId.startsWith("JPP")) { MavenJPackageDepmap map = MavenJPackageDepmap.getInstance(); Hashtable<String, String> newInfo = map.getMappedInfo(groupId, artifactId, version); groupId = (String) newInfo.get("group"); artifactId = (String) newInfo.get("artifact"); } MavenJPackageDepmap.debug("Resolved GROUPID=" + groupId); MavenJPackageDepmap.debug("Resolved ARTIFACTID=" + artifactId); if (artifact.getExtension().equals("pom")) { path = getPOMPath(groupId, artifactId); } else if (artifact.getExtension().equals("signature")) { path.append("/usr/share/maven/repository/"); path.append(groupId).append('/'); path.append(artifactId).append(".signature"); } else if (artifact.getExtension().equals("zip")) { path.append("/usr/share/maven/repository/"); path.append(groupId).append('/'); path.append(artifactId).append(".zip"); } else { path.append("/usr/share/maven/repository/"); path.append(groupId).append('/'); path.append(artifactId).append(".jar"); } MavenJPackageDepmap.debug("Returning " + path.toString()); File ret = new File(path.toString()); // if file doesn't exist return null to delegate to other // resolvers (reactor/local repo) if (ret.isFile()) { MavenJPackageDepmap.debug("Returning " + path.toString()); return ret; } else { MavenJPackageDepmap.debug("Returning null for gid:aid =>" + groupId + ":" + artifactId); return null; } }
public String getClassidier() { return artifact.getClassifier(); }
private void assertDependencies(List<Dependency> deps) { assertEquals(4, deps.size()); Dependency dep = deps.get(0); assertEquals("scope", dep.getScope()); assertEquals(false, dep.isOptional()); assertEquals(2, dep.getExclusions().size()); Iterator<Exclusion> it = dep.getExclusions().iterator(); Exclusion excl = it.next(); assertEquals("gid3", excl.getGroupId()); assertEquals("aid", excl.getArtifactId()); excl = it.next(); assertEquals("gid2", excl.getGroupId()); assertEquals("aid2", excl.getArtifactId()); Artifact art = dep.getArtifact(); assertEquals("gid", art.getGroupId()); assertEquals("aid", art.getArtifactId()); assertEquals("ver", art.getVersion()); assertEquals("ext", art.getExtension()); dep = deps.get(1); assertEquals("scope", dep.getScope()); assertEquals(true, dep.isOptional()); assertEquals(0, dep.getExclusions().size()); art = dep.getArtifact(); assertEquals("gid", art.getGroupId()); assertEquals("aid2", art.getArtifactId()); assertEquals("ver", art.getVersion()); assertEquals("ext", art.getExtension()); dep = deps.get(2); assertEquals("scope", dep.getScope()); assertEquals(true, dep.isOptional()); assertEquals(0, dep.getExclusions().size()); art = dep.getArtifact(); assertEquals("gid", art.getGroupId()); assertEquals("aid", art.getArtifactId()); assertEquals("ver3", art.getVersion()); assertEquals("ext", art.getExtension()); dep = deps.get(3); assertEquals("scope5", dep.getScope()); assertEquals(true, dep.isOptional()); assertEquals(0, dep.getExclusions().size()); art = dep.getArtifact(); assertEquals("gid1", art.getGroupId()); assertEquals("aid", art.getArtifactId()); assertEquals("ver", art.getVersion()); assertEquals("ext", art.getExtension()); }
public File getLocation() { return artifact.getFile(); }
public String getVersion() { return artifact.getVersion(); }
@Test public void testDefaultArtifactString() { Artifact a; a = new DefaultArtifact("gid:aid:ver"); assertEquals("gid", a.getGroupId()); assertEquals("aid", a.getArtifactId()); assertEquals("ver", a.getVersion()); assertEquals("jar", a.getExtension()); assertEquals("", a.getClassifier()); a = new DefaultArtifact("gid:aid:ext:ver"); assertEquals("gid", a.getGroupId()); assertEquals("aid", a.getArtifactId()); assertEquals("ver", a.getVersion()); assertEquals("ext", a.getExtension()); assertEquals("", a.getClassifier()); a = new DefaultArtifact("gid:aid:ext:cls:ver"); assertEquals("gid", a.getGroupId()); assertEquals("aid", a.getArtifactId()); assertEquals("ver", a.getVersion()); assertEquals("ext", a.getExtension()); assertEquals("cls", a.getClassifier()); a = new DefaultArtifact("gid:aid::cls:ver"); assertEquals("gid", a.getGroupId()); assertEquals("aid", a.getArtifactId()); assertEquals("ver", a.getVersion()); assertEquals("jar", a.getExtension()); assertEquals("cls", a.getClassifier()); a = new DefaultArtifact(new DefaultArtifact("gid:aid:ext:cls:ver").toString()); assertEquals("gid", a.getGroupId()); assertEquals("aid", a.getArtifactId()); assertEquals("ver", a.getVersion()); assertEquals("ext", a.getExtension()); assertEquals("cls", a.getClassifier()); }
/** * Creates a new class realm with the specified parent and imports. * * @param baseRealmId The base id to use for the new realm, must not be {@code null}. * @param type The type of the class realm, must not be {@code null}. * @param parent The parent realm for the new realm, may be {@code null} to use the Maven core * realm. * @param imports The packages/types to import from the parent realm, may be {@code null}. * @param artifacts The artifacts to add to the realm, may be {@code null}. Unresolved artifacts * (i.e. with a missing file) will automatically be excluded from the realm. * @return The created class realm, never {@code null}. */ private ClassRealm createRealm( String baseRealmId, RealmType type, ClassLoader parent, List<String> imports, boolean importXpp3Dom, List<Artifact> artifacts) { Set<String> artifactIds = new LinkedHashSet<String>(); List<ClassRealmConstituent> constituents = new ArrayList<ClassRealmConstituent>(); if (artifacts != null) { for (Artifact artifact : artifacts) { artifactIds.add(getId(artifact)); if (artifact.getFile() != null) { constituents.add(new ArtifactClassRealmConstituent(artifact)); } } } if (imports != null) { imports = new ArrayList<String>(imports); } else { imports = new ArrayList<String>(); } ClassRealm classRealm = newRealm(baseRealmId); if (parent != null) { classRealm.setParentClassLoader(parent); } else { classRealm.setParentRealm(getMavenRealm()); } List<ClassRealmManagerDelegate> delegates = getDelegates(); if (!delegates.isEmpty()) { ClassRealmRequest request = new DefaultClassRealmRequest(type, parent, imports, constituents); for (ClassRealmManagerDelegate delegate : delegates) { delegate.setupRealm(classRealm, request); } } if (importXpp3Dom) { importXpp3Dom(classRealm); } if (!imports.isEmpty()) { ClassLoader importedRealm = classRealm.getParentClassLoader(); if (logger.isDebugEnabled()) { logger.debug("Importing packages into class realm " + classRealm.getId()); } for (String imp : imports) { if (logger.isDebugEnabled()) { logger.debug(" Imported: " + imp); } classRealm.importFrom(importedRealm, imp); } } Set<String> includedIds = populateRealm(classRealm, constituents); if (logger.isDebugEnabled()) { artifactIds.removeAll(includedIds); for (String id : artifactIds) { logger.debug(" Excluded: " + id); } } return classRealm; }
public void execute() throws MojoExecutionException, MojoFailureException { // set up derived paths forgeDir = new File(outputDir, "forge"); jarsDir = new File(forgeDir, "mcp/jars"); // check whether the artifact is already installed if (reinstall) { getLog().info("reinstall flag set; skipping availability check"); } else { getLog().info("attempting to resolve Forge artifacts"); if (null != resolveApiArtifact() && null != resolveToolsArtifact()) { getLog().info("artifacts are available; skipping installation"); return; } else { getLog().info("artifacts not available; continuing installation"); } } if (!noExtract) downloadAndExtract(); if (!forgeDir.isDirectory()) throw new MojoFailureException("distribution did not extract to the excpected directory"); // run the install script if (!noInstall) { getLog().info("running install script"); try { final PythonLauncher launcher = new PythonLauncher(getLog(), forgeDir); final int result = launcher.execute(new File(forgeDir, "install.py")); if (0 != result) { throw new MojoFailureException("install script returned " + result); } } catch (IOException caught) { throw new MojoFailureException("error calling install script", caught); } } // load Minecraft's POM final Model minecraft = loadModelFromResouce("minecraft.pom"); minecraft.setVersion(getMinecraftVersion()); // figure out Minecraft's dependencies { getLog().info("detecting Minecraft dependencies"); final Artifact lwjgl = locator.findVersion(new File(jarsDir, "bin/lwjgl.jar"), "org.lwjgl.lwjgl", "lwjgl"); final Artifact lwjgl_util = new DefaultArtifact("org.lwjgl.lwjgl", "lwjgl_util", "jar", lwjgl.getVersion()); // don't include jinput.jar // it's a transitive dependency from LWJGL getLog().info("resolving Minecraft dependencies"); for (Artifact target : new Artifact[] {lwjgl, lwjgl_util}) { getLog().info(" " + target); final Artifact resolved = resolveRemoteArtifact(target); if (null == resolved) throw new MojoFailureException("unable to resolve artifact " + target); minecraft.addDependency(artifactToDependency(resolved)); } } // install Minecraft JAR installJar(minecraft, new File(jarsDir, "bin/minecraft.jar")); // figure out Forge's dependencies // using a Map of coordinates => artifact for deduplication // can't use a Set, Artifact#equals() doesn't behave final Map<String, Dependency> forgeDeps = new HashMap<String, Dependency>(); for (File file : (new File(forgeDir, "mcp/lib")).listFiles()) { final Artifact artifact = locator.locate(file); if (null == artifact) throw new MojoFailureException("no artifact found for dependency " + file.getName()); forgeDeps.put(artifact.toString(), artifactToDependency(artifact)); } // add Minecraft client to Forge dependencies { final Artifact artifact = new DefaultArtifact("net.minecraft", "minecraft", "jar", getMinecraftVersion()); forgeDeps.put(artifact.toString(), artifactToDependency(artifact)); } // extract the Forge POM final File pom = new File(forgeDir, "pom.xml"); { final Model model = loadModelFromResouce("mcforge.pom"); model.setVersion(getApiDependency().getVersion()); model.setDependencies(new ArrayList<Dependency>(forgeDeps.values())); writeModelToFile(model, pom); } // execute a build from the Forge POM getLog().info("executing POM to package and install artifacts"); try { final MavenExecutionRequest request = new DefaultMavenExecutionRequest(); requestPopulator.populateDefaults(request); request.setPom(pom); request.setGoals(Collections.singletonList("install")); final MavenExecutionResult result = maven.execute(request); // check for startup exceptions if (result.hasExceptions()) throw new MojoFailureException( "failed to package and install artifacts", result.getExceptions().get(0)); // check for build failure final BuildSummary summary = result.getBuildSummary(result.getProject()); if (summary instanceof BuildFailure) { throw new MojoFailureException( "failed to package and install artifacts", ((BuildFailure) summary).getCause()); } } catch (MojoFailureException caught) { throw caught; } catch (Exception caught) { throw new MojoFailureException("failed to package and install artifacts", caught); } }
public String getArtifactId() { return artifact.getArtifactId(); }
public String getGroupId() { return artifact.getGroupId(); }